target
stringlengths
5
300
feat_repo_name
stringlengths
6
76
text
stringlengths
26
1.05M
src/scenes/home/families/facts/facts.js
tskuse/operationcode_frontend
import React from 'react'; import styles from './facts.css'; import family3 from '../../../../images/Family-3.jpg'; const Facts = () => ( <div className={styles.facts}> <div className={styles.factsList}> <div className={styles.factsHeading}> <h5>The Facts</h5> </div> <ul> <li className={styles.factItem}> There are approximately 710,000 active duty spouses, 93% of whom are female. An additional 500,000 spouses are married to a Reservist or National Guardsman. </li> <li className={styles.factItem}> 84% have some college education; 25% hold an undergraduate degree; and 10% hold a postgraduate degree. </li> <li className={styles.factItem}> 77% of spouses report that they want or need to work. 38% of military spouses are underemployed, compared to approximately 6% rate for civilian spouses. </li> <li className={styles.factItem}> Only 19% of military spouses have adequate full-time employment. </li> </ul> </div> <div className={styles.factsRight}> <img className={styles.factsImage} src={family3} alt="" /> </div> </div> ); export default Facts;
wp-content/plugins/civicrm/civicrm/packages/kcfinder/cache/base.js
glocalcoop/activist-network
/*! jQuery v1.11.0 | (c) 2005, 2014 jQuery Foundation, Inc. | jquery.org/license */ ;!function(d,c){"object"==typeof module&&"object"==typeof module.exports?module.exports=d.document?c(d,!0):function(b){if(!b.document){throw new Error("jQuery requires a window with a document")}return c(b)}:c(d)}("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()||0.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)||"")?0.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 0.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});/*! jQuery UI - v1.10.4 - 2014-02-09 * http://jqueryui.com * Includes: jquery.ui.core.js, jquery.ui.widget.js, jquery.ui.mouse.js, jquery.ui.position.js, jquery.ui.draggable.js, jquery.ui.droppable.js, jquery.ui.resizable.js, jquery.ui.selectable.js, jquery.ui.sortable.js, jquery.ui.accordion.js, jquery.ui.autocomplete.js, jquery.ui.button.js, jquery.ui.datepicker.js, jquery.ui.dialog.js, jquery.ui.menu.js, jquery.ui.progressbar.js, jquery.ui.slider.js, jquery.ui.spinner.js, jquery.ui.tabs.js, jquery.ui.tooltip.js, jquery.ui.effect.js, jquery.ui.effect-blind.js, jquery.ui.effect-bounce.js, jquery.ui.effect-clip.js, jquery.ui.effect-drop.js, jquery.ui.effect-explode.js, jquery.ui.effect-fade.js, jquery.ui.effect-fold.js, jquery.ui.effect-highlight.js, jquery.ui.effect-pulsate.js, jquery.ui.effect-scale.js, jquery.ui.effect-shake.js, jquery.ui.effect-slide.js, jquery.ui.effect-transfer.js * Copyright 2014 jQuery Foundation and other contributors; Licensed MIT */ (function(g,d){function c(k,j){var l,e,n,m=k.nodeName.toLowerCase();return"area"===m?(l=k.parentNode,e=l.name,k.href&&e&&"map"===l.nodeName.toLowerCase()?(n=g("img[usemap=#"+e+"]")[0],!!n&&h(n)):!1):(/input|select|textarea|button|object/.test(m)?!k.disabled:"a"===m?k.href||j:j)&&h(k)}function h(a){return g.expr.filters.visible(a)&&!g(a).parents().addBack().filter(function(){return"hidden"===g.css(this,"visibility")}).length}var f=0,b=/^ui-id-\d+$/;g.ui=g.ui||{},g.extend(g.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}}),g.fn.extend({focus:function(a){return function(e,j){return"number"==typeof e?this.each(function(){var i=this;setTimeout(function(){g(i).focus(),j&&j.call(i)},e)}):a.apply(this,arguments)}}(g.fn.focus),scrollParent:function(){var a;return a=g.ui.ie&&/(static|relative)/.test(this.css("position"))||/absolute/.test(this.css("position"))?this.parents().filter(function(){return/(relative|absolute|fixed)/.test(g.css(this,"position"))&&/(auto|scroll)/.test(g.css(this,"overflow")+g.css(this,"overflow-y")+g.css(this,"overflow-x"))}).eq(0):this.parents().filter(function(){return/(auto|scroll)/.test(g.css(this,"overflow")+g.css(this,"overflow-y")+g.css(this,"overflow-x"))}).eq(0),/fixed/.test(this.css("position"))||!a.length?g(document):a},zIndex:function(j){if(j!==d){return this.css("zIndex",j)}if(this.length){for(var l,k,e=g(this[0]);e.length&&e[0]!==document;){if(l=e.css("position"),("absolute"===l||"relative"===l||"fixed"===l)&&(k=parseInt(e.css("zIndex"),10),!isNaN(k)&&0!==k)){return k}e=e.parent()}}return 0},uniqueId:function(){return this.each(function(){this.id||(this.id="ui-id-"+ ++f)})},removeUniqueId:function(){return this.each(function(){b.test(this.id)&&g(this).removeAttr("id")})}}),g.extend(g.expr[":"],{data:g.expr.createPseudo?g.expr.createPseudo(function(a){return function(e){return !!g.data(e,a)}}):function(e,a,j){return !!g.data(e,j[3])},focusable:function(a){return c(a,!isNaN(g.attr(a,"tabindex")))},tabbable:function(a){var i=g.attr(a,"tabindex"),e=isNaN(i);return(e||i>=0)&&c(a,!e)}}),g("<a>").outerWidth(1).jquery||g.each(["Width","Height"],function(j,p){function k(o,a,r,q){return g.each(e,function(){a-=parseFloat(g.css(o,"padding"+this))||0,r&&(a-=parseFloat(g.css(o,"border"+this+"Width"))||0),q&&(a-=parseFloat(g.css(o,"margin"+this))||0)}),a}var e="Width"===p?["Left","Right"]:["Top","Bottom"],m=p.toLowerCase(),l={innerWidth:g.fn.innerWidth,innerHeight:g.fn.innerHeight,outerWidth:g.fn.outerWidth,outerHeight:g.fn.outerHeight};g.fn["inner"+p]=function(a){return a===d?l["inner"+p].call(this):this.each(function(){g(this).css(m,k(this,a)+"px")})},g.fn["outer"+p]=function(n,a){return"number"!=typeof n?l["outer"+p].call(this,n):this.each(function(){g(this).css(m,k(this,n,!0,a)+"px")})}}),g.fn.addBack||(g.fn.addBack=function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}),g("<a>").data("a-b","a").removeData("a-b").data("a-b")&&(g.fn.removeData=function(a){return function(e){return arguments.length?a.call(this,g.camelCase(e)):a.call(this)}}(g.fn.removeData)),g.ui.ie=!!/msie [\w.]+/.exec(navigator.userAgent.toLowerCase()),g.support.selectstart="onselectstart" in document.createElement("div"),g.fn.extend({disableSelection:function(){return this.bind((g.support.selectstart?"selectstart":"mousedown")+".ui-disableSelection",function(a){a.preventDefault()})},enableSelection:function(){return this.unbind(".ui-disableSelection")}}),g.extend(g.ui,{plugin:{add:function(k,j,m){var l,e=g.ui[k].prototype;for(l in m){e.plugins[l]=e.plugins[l]||[],e.plugins[l].push([j,m[l]])}},call:function(l,j,a){var m,k=l.plugins[j];if(k&&l.element[0].parentNode&&11!==l.element[0].parentNode.nodeType){for(m=0;k.length>m;m++){l.options[k[m][0]]&&k[m][1].apply(l.element,a)}}}},hasScroll:function(e,a){if("hidden"===g(e).css("overflow")){return !1}var k=a&&"left"===a?"scrollLeft":"scrollTop",j=!1;return e[k]>0?!0:(e[k]=1,j=e[k]>0,e[k]=0,j)}})})(jQuery);(function(b,d){var a=0,c=Array.prototype.slice,f=b.cleanData;b.cleanData=function(j){for(var g,h=0;null!=(g=j[h]);h++){try{b(g).triggerHandler("remove")}catch(k){}}f(j)},b.widget=function(m,u,j){var g,t,e,p,k={},q=m.split(".")[0];m=m.split(".")[1],g=q+"-"+m,j||(j=u,u=b.Widget),b.expr[":"][g.toLowerCase()]=function(h){return !!b.data(h,g)},b[q]=b[q]||{},t=b[q][m],e=b[q][m]=function(l,h){return this._createWidget?(arguments.length&&this._createWidget(l,h),d):new e(l,h)},b.extend(e,t,{version:j.version,_proto:b.extend({},j),_childConstructors:[]}),p=new u,p.options=b.widget.extend({},p.options),b.each(j,function(h,l){return b.isFunction(l)?(k[h]=function(){var i=function(){return u.prototype[h].apply(this,arguments)},n=function(o){return u.prototype[h].apply(this,o)};return function(){var r,v=this._super,w=this._superApply;return this._super=i,this._superApply=n,r=l.apply(this,arguments),this._super=v,this._superApply=w,r}}(),d):(k[h]=l,d)}),e.prototype=b.widget.extend(p,{widgetEventPrefix:t?p.widgetEventPrefix||m:m},k,{constructor:e,namespace:q,widgetName:m,widgetFullName:g}),t?(b.each(t._childConstructors,function(n,h){var l=h.prototype;b.widget(l.namespace+"."+l.widgetName,e,h._proto)}),delete t._childConstructors):u._childConstructors.push(e),b.widget.bridge(m,e)},b.widget.extend=function(g){for(var m,l,e=c.call(arguments,1),k=0,j=e.length;j>k;k++){for(m in e[k]){l=e[k][m],e[k].hasOwnProperty(m)&&l!==d&&(g[m]=b.isPlainObject(l)?b.isPlainObject(g[m])?b.widget.extend({},g[m],l):b.widget.extend({},l):l)}}return g},b.widget.bridge=function(e,h){var g=h.prototype.widgetFullName||e;b.fn[e]=function(j){var m="string"==typeof j,k=c.call(arguments,1),i=this;return j=!m&&k.length?b.widget.extend.apply(null,[j].concat(k)):j,m?this.each(function(){var l,o=b.data(this,g);return o?b.isFunction(o[j])&&"_"!==j.charAt(0)?(l=o[j].apply(o,k),l!==o&&l!==d?(i=l&&l.jquery?i.pushStack(l.get()):l,!1):d):b.error("no such method '"+j+"' for "+e+" widget instance"):b.error("cannot call methods on "+e+" prior to initialization; attempted to call method '"+j+"'")}):this.each(function(){var l=b.data(this,g);l?l.option(j||{})._init():b.data(this,g,new h(j,this))}),i}},b.Widget=function(){},b.Widget._childConstructors=[],b.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",defaultElement:"<div>",options:{disabled:!1,create:null},_createWidget:function(h,g){g=b(g||this.defaultElement||this)[0],this.element=b(g),this.uuid=a++,this.eventNamespace="."+this.widgetName+this.uuid,this.options=b.widget.extend({},this.options,this._getCreateOptions(),h),this.bindings=b(),this.hoverable=b(),this.focusable=b(),g!==this&&(b.data(g,this.widgetFullName,this),this._on(!0,this.element,{remove:function(e){e.target===g&&this.destroy()}}),this.document=b(g.style?g.ownerDocument:g.document||g),this.window=b(this.document[0].defaultView||this.document[0].parentWindow)),this._create(),this._trigger("create",null,this._getCreateEventData()),this._init()},_getCreateOptions:b.noop,_getCreateEventData:b.noop,_create:b.noop,_init:b.noop,destroy:function(){this._destroy(),this.element.unbind(this.eventNamespace).removeData(this.widgetName).removeData(this.widgetFullName).removeData(b.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:b.noop,widget:function(){return this.element},option:function(g,h){var l,k,e,j=g;if(0===arguments.length){return b.widget.extend({},this.options)}if("string"==typeof g){if(j={},l=g.split("."),g=l.shift(),l.length){for(k=j[g]=b.widget.extend({},this.options[g]),e=0;l.length-1>e;e++){k[l[e]]=k[l[e]]||{},k=k[l[e]]}if(g=l.pop(),1===arguments.length){return k[g]===d?null:k[g]}k[g]=h}else{if(1===arguments.length){return this.options[g]===d?null:this.options[g]}j[g]=h}}return this._setOptions(j),this},_setOptions:function(g){var h;for(h in g){this._setOption(h,g[h])}return this},_setOption:function(g,h){return this.options[g]=h,"disabled"===g&&(this.widget().toggleClass(this.widgetFullName+"-disabled ui-state-disabled",!!h).attr("aria-disabled",h),this.hoverable.removeClass("ui-state-hover"),this.focusable.removeClass("ui-state-focus")),this},enable:function(){return this._setOption("disabled",!1)},disable:function(){return this._setOption("disabled",!0)},_on:function(g,h,k){var j,e=this;"boolean"!=typeof g&&(k=h,h=g,g=!1),k?(h=j=b(h),this.bindings=this.bindings.add(h)):(k=h,h=this.element,j=this.widget()),b.each(k,function(s,p){function o(){return g||e.options.disabled!==!0&&!b(this).hasClass("ui-state-disabled")?("string"==typeof p?e[p]:p).apply(e,arguments):d}"string"!=typeof p&&(o.guid=p.guid=p.guid||o.guid||b.guid++);var i=s.match(/^(\w+)\s*(.*)$/),q=i[1]+e.eventNamespace,m=i[2];m?j.delegate(m,q,o):h.bind(q,o)})},_off:function(g,h){h=(h||"").split(" ").join(this.eventNamespace+" ")+this.eventNamespace,g.unbind(h).undelegate(h)},_delay:function(h,k){function g(){return("string"==typeof h?j[h]:h).apply(j,arguments)}var j=this;return setTimeout(g,k||0)},_hoverable:function(g){this.hoverable=this.hoverable.add(g),this._on(g,{mouseenter:function(h){b(h.currentTarget).addClass("ui-state-hover")},mouseleave:function(h){b(h.currentTarget).removeClass("ui-state-hover")}})},_focusable:function(g){this.focusable=this.focusable.add(g),this._on(g,{focusin:function(h){b(h.currentTarget).addClass("ui-state-focus")},focusout:function(h){b(h.currentTarget).removeClass("ui-state-focus")}})},_trigger:function(k,h,j){var m,l,g=this.options[k];if(j=j||{},h=b.Event(h),h.type=(k===this.widgetEventPrefix?k:this.widgetEventPrefix+k).toLowerCase(),h.target=this.element[0],l=h.originalEvent){for(m in l){m in h||(h[m]=l[m])}}return this.element.trigger(h,j),!(b.isFunction(g)&&g.apply(this.element[0],[h].concat(j))===!1||h.isDefaultPrevented())}},b.each({show:"fadeIn",hide:"fadeOut"},function(h,g){b.Widget.prototype["_"+h]=function(i,l,k){"string"==typeof l&&(l={effect:l});var e,j=l?l===!0||"number"==typeof l?g:l.effect||g:h;l=l||{},"number"==typeof l&&(l={duration:l}),e=!b.isEmptyObject(l),l.complete=k,l.delay&&i.delay(l.delay),e&&b.effects&&b.effects.effect[j]?i[h](l):j!==h&&i[j]?i[j](l.duration,l.easing,k):i.queue(function(m){b(this)[h](),k&&k.call(i[0]),m()})}})})(jQuery);(function(a){var b=!1;a(document).mouseup(function(){b=!1}),a.widget("ui.mouse",{version:"1.10.4",options:{cancel:"input,textarea,button,select,option",distance:1,delay:0},_mouseInit:function(){var c=this;this.element.bind("mousedown."+this.widgetName,function(d){return c._mouseDown(d)}).bind("click."+this.widgetName,function(d){return !0===a.data(d.target,c.widgetName+".preventClickEvent")?(a.removeData(d.target,c.widgetName+".preventClickEvent"),d.stopImmediatePropagation(),!1):undefined}),this.started=!1},_mouseDestroy:function(){this.element.unbind("."+this.widgetName),this._mouseMoveDelegate&&a(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate)},_mouseDown:function(d){if(!b){this._mouseStarted&&this._mouseUp(d),this._mouseDownEvent=d;var e=this,f=1===d.which,c="string"==typeof this.options.cancel&&d.target.nodeName?a(d.target).closest(this.options.cancel).length:!1;return f&&!c&&this._mouseCapture(d)?(this.mouseDelayMet=!this.options.delay,this.mouseDelayMet||(this._mouseDelayTimer=setTimeout(function(){e.mouseDelayMet=!0},this.options.delay)),this._mouseDistanceMet(d)&&this._mouseDelayMet(d)&&(this._mouseStarted=this._mouseStart(d)!==!1,!this._mouseStarted)?(d.preventDefault(),!0):(!0===a.data(d.target,this.widgetName+".preventClickEvent")&&a.removeData(d.target,this.widgetName+".preventClickEvent"),this._mouseMoveDelegate=function(g){return e._mouseMove(g)},this._mouseUpDelegate=function(g){return e._mouseUp(g)},a(document).bind("mousemove."+this.widgetName,this._mouseMoveDelegate).bind("mouseup."+this.widgetName,this._mouseUpDelegate),d.preventDefault(),b=!0,!0)):!0}},_mouseMove:function(c){return a.ui.ie&&(!document.documentMode||9>document.documentMode)&&!c.button?this._mouseUp(c):this._mouseStarted?(this._mouseDrag(c),c.preventDefault()):(this._mouseDistanceMet(c)&&this._mouseDelayMet(c)&&(this._mouseStarted=this._mouseStart(this._mouseDownEvent,c)!==!1,this._mouseStarted?this._mouseDrag(c):this._mouseUp(c)),!this._mouseStarted)},_mouseUp:function(c){return a(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate),this._mouseStarted&&(this._mouseStarted=!1,c.target===this._mouseDownEvent.target&&a.data(c.target,this.widgetName+".preventClickEvent",!0),this._mouseStop(c)),!1},_mouseDistanceMet:function(c){return Math.max(Math.abs(this._mouseDownEvent.pageX-c.pageX),Math.abs(this._mouseDownEvent.pageY-c.pageY))>=this.options.distance},_mouseDelayMet:function(){return this.mouseDelayMet},_mouseStart:function(){},_mouseDrag:function(){},_mouseStop:function(){},_mouseCapture:function(){return !0}})})(jQuery);(function(C,x){function q(c,d,a){return[parseFloat(c[0])*(g.test(c[0])?d/100:1),parseFloat(c[1])*(g.test(c[1])?a/100:1)]}function D(c,a){return parseInt(C.css(c,a),10)||0}function k(c){var a=c[0];return 9===a.nodeType?{width:c.width(),height:c.height(),offset:{top:0,left:0}}:C.isWindow(a)?{width:c.width(),height:c.height(),offset:{top:c.scrollTop(),left:c.scrollLeft()}}:a.preventDefault?{width:0,height:0,offset:{top:a.pageY,left:a.pageX}}:{width:c.outerWidth(),height:c.outerHeight(),offset:c.offset()}}C.ui=C.ui||{};var A,j=Math.max,b=Math.abs,m=Math.round,v=/left|center|right/,z=/top|center|bottom/,B=/[\+\-]\d+(\.[\d]+)?%?/,y=/^\w+/,g=/%$/,w=C.fn.position;C.position={scrollbarWidth:function(){if(A!==x){return A}var a,c,e=C("<div style='display:block;position:absolute;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>"),d=e.children()[0];return C("body").append(e),a=d.offsetWidth,e.css("overflow","scroll"),c=d.offsetWidth,a===c&&(c=e[0].clientWidth),e.remove(),A=a-c},getScrollInfo:function(h){var d=h.isWindow||h.isDocument?"":h.element.css("overflow-x"),f=h.isWindow||h.isDocument?"":h.element.css("overflow-y"),l="scroll"===d||"auto"===d&&h.width<h.element[0].scrollWidth,c="scroll"===f||"auto"===f&&h.height<h.element[0].scrollHeight;return{width:c?C.position.scrollbarWidth():0,height:l?C.position.scrollbarWidth():0}},getWithinInfo:function(d){var a=C(d||window),c=C.isWindow(a[0]),f=!!a[0]&&9===a[0].nodeType;return{element:a,isWindow:c,isDocument:f,offset:a.offset()||{left:0,top:0},scrollLeft:a.scrollLeft(),scrollTop:a.scrollTop(),width:c?a.width():a.outerWidth(),height:c?a.height():a.outerHeight()}}},C.fn.position=function(l){if(!l||!l.of){return w.apply(this,arguments)}l=C.extend({},l);var r,d,i,f,u,t,o=C(l.of),n=C.position.getWithinInfo(l.within),h=C.position.getScrollInfo(n),s=(l.collision||"flip").split(" "),c={};return t=k(o),o[0].preventDefault&&(l.at="left top"),d=t.width,i=t.height,f=t.offset,u=C.extend({},f),C.each(["my","at"],function(){var e,a,p=(l[this]||"").split(" ");1===p.length&&(p=v.test(p[0])?p.concat(["center"]):z.test(p[0])?["center"].concat(p):["center","center"]),p[0]=v.test(p[0])?p[0]:"center",p[1]=z.test(p[1])?p[1]:"center",e=B.exec(p[0]),a=B.exec(p[1]),c[this]=[e?e[0]:0,a?a[0]:0],l[this]=[y.exec(p[0])[0],y.exec(p[1])[0]]}),1===s.length&&(s[1]=s[0]),"right"===l.at[0]?u.left+=d:"center"===l.at[0]&&(u.left+=d/2),"bottom"===l.at[1]?u.top+=i:"center"===l.at[1]&&(u.top+=i/2),r=q(c.at,d,i),u.left+=r[0],u.top+=r[1],this.each(function(){var e,E,I=C(this),L=I.outerWidth(),H=I.outerHeight(),F=D(this,"marginLeft"),K=D(this,"marginTop"),J=L+F+D(this,"marginRight")+h.width,a=H+K+D(this,"marginBottom")+h.height,G=C.extend({},u),p=q(c.my,I.outerWidth(),I.outerHeight());"right"===l.my[0]?G.left-=L:"center"===l.my[0]&&(G.left-=L/2),"bottom"===l.my[1]?G.top-=H:"center"===l.my[1]&&(G.top-=H/2),G.left+=p[0],G.top+=p[1],C.support.offsetFractions||(G.left=m(G.left),G.top=m(G.top)),e={marginLeft:F,marginTop:K},C.each(["left","top"],function(M,N){C.ui.position[s[M]]&&C.ui.position[s[M]][N](G,{targetWidth:d,targetHeight:i,elemWidth:L,elemHeight:H,collisionPosition:e,collisionWidth:J,collisionHeight:a,offset:[r[0]+p[0],r[1]+p[1]],my:l.my,at:l.at,within:n,elem:I})}),l.using&&(E=function(P){var O=f.left-G.left,Q=O+d-L,R=f.top-G.top,N=R+i-H,M={target:{element:o,left:f.left,top:f.top,width:d,height:i},element:{element:I,left:G.left,top:G.top,width:L,height:H},horizontal:0>Q?"left":O>0?"right":"center",vertical:0>N?"top":R>0?"bottom":"middle"};L>d&&d>b(O+Q)&&(M.horizontal="center"),H>i&&i>b(R+N)&&(M.vertical="middle"),M.important=j(b(O),b(Q))>j(b(R),b(N))?"horizontal":"vertical",l.using.call(this,P,M)}),I.offset(C.extend(G,{using:E}))})},C.ui.position={fit:{left:function(F,u){var o,G=u.within,d=G.isWindow?G.scrollLeft:G.offset.left,E=G.width,c=F.left-u.collisionPosition.marginLeft,f=d-c,p=c+u.collisionWidth-E-d;u.collisionWidth>E?f>0&&0>=p?(o=F.left+f+u.collisionWidth-E-d,F.left+=f-o):F.left=p>0&&0>=f?d:f>p?d+E-u.collisionWidth:d:f>0?F.left+=f:p>0?F.left-=p:F.left=j(F.left-c,F.left)},top:function(F,u){var o,G=u.within,d=G.isWindow?G.scrollTop:G.offset.top,E=u.within.height,c=F.top-u.collisionPosition.marginTop,f=d-c,p=c+u.collisionHeight-E-d;u.collisionHeight>E?f>0&&0>=p?(o=F.top+f+u.collisionHeight-E-d,F.top+=f-o):F.top=p>0&&0>=f?d:f>p?d+E-u.collisionHeight:d:f>0?F.top+=f:p>0?F.top-=p:F.top=j(F.top-c,F.top)}},flip:{left:function(P,K){var H,Q,F=K.within,N=F.offset.left+F.scrollLeft,E=F.width,G=F.isWindow?F.scrollLeft:F.offset.left,I=P.left-K.collisionPosition.marginLeft,M=I-G,O=I+K.collisionWidth-E-G,L="left"===K.my[0]?-K.elemWidth:"right"===K.my[0]?K.elemWidth:0,r="left"===K.at[0]?K.targetWidth:"right"===K.at[0]?-K.targetWidth:0,J=-2*K.offset[0];0>M?(H=P.left+L+r+J+K.collisionWidth-E-N,(0>H||b(M)>H)&&(P.left+=L+r+J)):O>0&&(Q=P.left-K.collisionPosition.marginLeft+L+r+J-G,(Q>0||O>b(Q))&&(P.left+=L+r+J))},top:function(Q,L){var H,R,F=L.within,O=F.offset.top+F.scrollTop,E=F.height,G=F.isWindow?F.scrollTop:F.offset.top,I=Q.top-L.collisionPosition.marginTop,N=I-G,P=I+L.collisionHeight-E-G,M="top"===L.my[1],r=M?-L.elemHeight:"bottom"===L.my[1]?L.elemHeight:0,K="top"===L.at[1]?L.targetHeight:"bottom"===L.at[1]?-L.targetHeight:0,J=-2*L.offset[1];0>N?(R=Q.top+r+K+J+L.collisionHeight-E-O,Q.top+r+K+J>N&&(0>R||b(N)>R)&&(Q.top+=r+K+J)):P>0&&(H=Q.top-L.collisionPosition.marginTop+r+K+J-G,Q.top+r+K+J>P&&(H>0||P>b(H))&&(Q.top+=r+K+J))}},flipfit:{left:function(){C.ui.position.flip.left.apply(this,arguments),C.ui.position.fit.left.apply(this,arguments)},top:function(){C.ui.position.flip.top.apply(this,arguments),C.ui.position.fit.top.apply(this,arguments)}}},function(){var l,d,f,t,c,p=document.getElementsByTagName("body")[0],h=document.createElement("div");l=document.createElement(p?"div":"body"),f={visibility:"hidden",width:0,height:0,border:0,margin:0,background:"none"},p&&C.extend(f,{position:"absolute",left:"-1000px",top:"-1000px"});for(c in f){l.style[c]=f[c]}l.appendChild(h),d=p||document.documentElement,d.insertBefore(l,d.firstChild),h.style.cssText="position: absolute; left: 10.7432222px;",t=C(h).offset().left,C.support.offsetFractions=t>10&&11>t,l.innerHTML="",d.removeChild(l)}()})(jQuery);(function(a){a.widget("ui.draggable",a.ui.mouse,{version:"1.10.4",widgetEventPrefix:"drag",options:{addClasses:!0,appendTo:"parent",axis:!1,connectToSortable:!1,containment:!1,cursor:"auto",cursorAt:!1,grid:!1,handle:!1,helper:"original",iframeFix:!1,opacity:!1,refreshPositions:!1,revert:!1,revertDuration:500,scope:"default",scroll:!0,scrollSensitivity:20,scrollSpeed:20,snap:!1,snapMode:"both",snapTolerance:20,stack:!1,zIndex:!1,drag:null,start:null,stop:null},_create:function(){"original"!==this.options.helper||/^(?:r|a|f)/.test(this.element.css("position"))||(this.element[0].style.position="relative"),this.options.addClasses&&this.element.addClass("ui-draggable"),this.options.disabled&&this.element.addClass("ui-draggable-disabled"),this._mouseInit()},_destroy:function(){this.element.removeClass("ui-draggable ui-draggable-dragging ui-draggable-disabled"),this._mouseDestroy()},_mouseCapture:function(c){var b=this.options;return this.helper||b.disabled||a(c.target).closest(".ui-resizable-handle").length>0?!1:(this.handle=this._getHandle(c),this.handle?(a(b.iframeFix===!0?"iframe":b.iframeFix).each(function(){a("<div class='ui-draggable-iframeFix' style='background: #fff;'></div>").css({width:this.offsetWidth+"px",height:this.offsetHeight+"px",position:"absolute",opacity:"0.001",zIndex:1000}).css(a(this).offset()).appendTo("body")}),!0):!1)},_mouseStart:function(c){var b=this.options;return this.helper=this._createHelper(c),this.helper.addClass("ui-draggable-dragging"),this._cacheHelperProportions(),a.ui.ddmanager&&(a.ui.ddmanager.current=this),this._cacheMargins(),this.cssPosition=this.helper.css("position"),this.scrollParent=this.helper.scrollParent(),this.offsetParent=this.helper.offsetParent(),this.offsetParentCssPosition=this.offsetParent.css("position"),this.offset=this.positionAbs=this.element.offset(),this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left},this.offset.scroll=!1,a.extend(this.offset,{click:{left:c.pageX-this.offset.left,top:c.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()}),this.originalPosition=this.position=this._generatePosition(c),this.originalPageX=c.pageX,this.originalPageY=c.pageY,b.cursorAt&&this._adjustOffsetFromHelper(b.cursorAt),this._setContainment(),this._trigger("start",c)===!1?(this._clear(),!1):(this._cacheHelperProportions(),a.ui.ddmanager&&!b.dropBehaviour&&a.ui.ddmanager.prepareOffsets(this,c),this._mouseDrag(c,!0),a.ui.ddmanager&&a.ui.ddmanager.dragStart(this,c),!0)},_mouseDrag:function(d,b){if("fixed"===this.offsetParentCssPosition&&(this.offset.parent=this._getParentOffset()),this.position=this._generatePosition(d),this.positionAbs=this._convertPositionTo("absolute"),!b){var c=this._uiHash();if(this._trigger("drag",d,c)===!1){return this._mouseUp({}),!1}this.position=c.position}return 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"),a.ui.ddmanager&&a.ui.ddmanager.drag(this,d),!1},_mouseStop:function(d){var b=this,c=!1;return a.ui.ddmanager&&!this.options.dropBehaviour&&(c=a.ui.ddmanager.drop(this,d)),this.dropped&&(c=this.dropped,this.dropped=!1),"original"!==this.options.helper||a.contains(this.element[0].ownerDocument,this.element[0])?("invalid"===this.options.revert&&!c||"valid"===this.options.revert&&c||this.options.revert===!0||a.isFunction(this.options.revert)&&this.options.revert.call(this.element,c)?a(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10),function(){b._trigger("stop",d)!==!1&&b._clear()}):this._trigger("stop",d)!==!1&&this._clear(),!1):!1},_mouseUp:function(b){return a("div.ui-draggable-iframeFix").each(function(){this.parentNode.removeChild(this)}),a.ui.ddmanager&&a.ui.ddmanager.dragStop(this,b),a.ui.mouse.prototype._mouseUp.call(this,b)},cancel:function(){return this.helper.is(".ui-draggable-dragging")?this._mouseUp({}):this._clear(),this},_getHandle:function(b){return this.options.handle?!!a(b.target).closest(this.element.find(this.options.handle)).length:!0},_createHelper:function(d){var b=this.options,c=a.isFunction(b.helper)?a(b.helper.apply(this.element[0],[d])):"clone"===b.helper?this.element.clone().removeAttr("id"):this.element;return c.parents("body").length||c.appendTo("parent"===b.appendTo?this.element[0].parentNode:b.appendTo),c[0]===this.element[0]||/(fixed|absolute)/.test(c.css("position"))||c.css("position","absolute"),c},_adjustOffsetFromHelper:function(b){"string"==typeof b&&(b=b.split(" ")),a.isArray(b)&&(b={left:+b[0],top:+b[1]||0}),"left" in b&&(this.offset.click.left=b.left+this.margins.left),"right" in b&&(this.offset.click.left=this.helperProportions.width-b.right+this.margins.left),"top" in b&&(this.offset.click.top=b.top+this.margins.top),"bottom" in b&&(this.offset.click.top=this.helperProportions.height-b.bottom+this.margins.top)},_getParentOffset:function(){var b=this.offsetParent.offset();return"absolute"===this.cssPosition&&this.scrollParent[0]!==document&&a.contains(this.scrollParent[0],this.offsetParent[0])&&(b.left+=this.scrollParent.scrollLeft(),b.top+=this.scrollParent.scrollTop()),(this.offsetParent[0]===document.body||this.offsetParent[0].tagName&&"html"===this.offsetParent[0].tagName.toLowerCase()&&a.ui.ie)&&(b={top:0,left:0}),{top:b.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:b.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if("relative"===this.cssPosition){var b=this.element.position();return{top:b.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:b.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}return{top:0,left:0}},_cacheMargins:function(){this.margins={left:parseInt(this.element.css("marginLeft"),10)||0,top:parseInt(this.element.css("marginTop"),10)||0,right:parseInt(this.element.css("marginRight"),10)||0,bottom:parseInt(this.element.css("marginBottom"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var d,b,c,f=this.options;return f.containment?"window"===f.containment?(this.containment=[a(window).scrollLeft()-this.offset.relative.left-this.offset.parent.left,a(window).scrollTop()-this.offset.relative.top-this.offset.parent.top,a(window).scrollLeft()+a(window).width()-this.helperProportions.width-this.margins.left,a(window).scrollTop()+(a(window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top],undefined):"document"===f.containment?(this.containment=[0,0,a(document).width()-this.helperProportions.width-this.margins.left,(a(document).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top],undefined):f.containment.constructor===Array?(this.containment=f.containment,undefined):("parent"===f.containment&&(f.containment=this.helper[0].parentNode),b=a(f.containment),c=b[0],c&&(d="hidden"!==b.css("overflow"),this.containment=[(parseInt(b.css("borderLeftWidth"),10)||0)+(parseInt(b.css("paddingLeft"),10)||0),(parseInt(b.css("borderTopWidth"),10)||0)+(parseInt(b.css("paddingTop"),10)||0),(d?Math.max(c.scrollWidth,c.offsetWidth):c.offsetWidth)-(parseInt(b.css("borderRightWidth"),10)||0)-(parseInt(b.css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left-this.margins.right,(d?Math.max(c.scrollHeight,c.offsetHeight):c.offsetHeight)-(parseInt(b.css("borderBottomWidth"),10)||0)-(parseInt(b.css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top-this.margins.bottom],this.relative_container=b),undefined):(this.containment=null,undefined)},_convertPositionTo:function(d,b){b||(b=this.position);var c="absolute"===d?1:-1,f="absolute"!==this.cssPosition||this.scrollParent[0]!==document&&a.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent;return this.offset.scroll||(this.offset.scroll={top:f.scrollTop(),left:f.scrollLeft()}),{top:b.top+this.offset.relative.top*c+this.offset.parent.top*c-("fixed"===this.cssPosition?-this.scrollParent.scrollTop():this.offset.scroll.top)*c,left:b.left+this.offset.relative.left*c+this.offset.parent.left*c-("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():this.offset.scroll.left)*c}},_generatePosition:function(k){var g,p,d,m,c=this.options,b="absolute"!==this.cssPosition||this.scrollParent[0]!==document&&a.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,f=k.pageX,j=k.pageY;return this.offset.scroll||(this.offset.scroll={top:b.scrollTop(),left:b.scrollLeft()}),this.originalPosition&&(this.containment&&(this.relative_container?(p=this.relative_container.offset(),g=[this.containment[0]+p.left,this.containment[1]+p.top,this.containment[2]+p.left,this.containment[3]+p.top]):g=this.containment,k.pageX-this.offset.click.left<g[0]&&(f=g[0]+this.offset.click.left),k.pageY-this.offset.click.top<g[1]&&(j=g[1]+this.offset.click.top),k.pageX-this.offset.click.left>g[2]&&(f=g[2]+this.offset.click.left),k.pageY-this.offset.click.top>g[3]&&(j=g[3]+this.offset.click.top)),c.grid&&(d=c.grid[1]?this.originalPageY+Math.round((j-this.originalPageY)/c.grid[1])*c.grid[1]:this.originalPageY,j=g?d-this.offset.click.top>=g[1]||d-this.offset.click.top>g[3]?d:d-this.offset.click.top>=g[1]?d-c.grid[1]:d+c.grid[1]:d,m=c.grid[0]?this.originalPageX+Math.round((f-this.originalPageX)/c.grid[0])*c.grid[0]:this.originalPageX,f=g?m-this.offset.click.left>=g[0]||m-this.offset.click.left>g[2]?m:m-this.offset.click.left>=g[0]?m-c.grid[0]:m+c.grid[0]:m)),{top:j-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+("fixed"===this.cssPosition?-this.scrollParent.scrollTop():this.offset.scroll.top),left:f-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():this.offset.scroll.left)}},_clear:function(){this.helper.removeClass("ui-draggable-dragging"),this.helper[0]===this.element[0]||this.cancelHelperRemoval||this.helper.remove(),this.helper=null,this.cancelHelperRemoval=!1},_trigger:function(d,b,c){return c=c||this._uiHash(),a.ui.plugin.call(this,d,[b,c]),"drag"===d&&(this.positionAbs=this._convertPositionTo("absolute")),a.Widget.prototype._trigger.call(this,d,b,c)},plugins:{},_uiHash:function(){return{helper:this.helper,position:this.position,originalPosition:this.originalPosition,offset:this.positionAbs}}}),a.ui.plugin.add("draggable","connectToSortable",{start:function(f,c){var d=a(this).data("ui-draggable"),g=d.options,b=a.extend({},c,{item:d.element});d.sortables=[],a(g.connectToSortable).each(function(){var e=a.data(this,"ui-sortable");e&&!e.options.disabled&&(d.sortables.push({instance:e,shouldRevert:e.options.revert}),e.refreshPositions(),e._trigger("activate",f,b))})},stop:function(d,b){var c=a(this).data("ui-draggable"),f=a.extend({},b,{item:c.element});a.each(c.sortables,function(){this.instance.isOver?(this.instance.isOver=0,c.cancelHelperRemoval=!0,this.instance.cancelHelperRemoval=!1,this.shouldRevert&&(this.instance.options.revert=this.shouldRevert),this.instance._mouseStop(d),this.instance.options.helper=this.instance.options._helper,"original"===c.options.helper&&this.instance.currentItem.css({top:"auto",left:"auto"})):(this.instance.cancelHelperRemoval=!1,this.instance._trigger("deactivate",d,f))})},drag:function(d,b){var c=a(this).data("ui-draggable"),f=this;a.each(c.sortables,function(){var e=!1,g=this;this.instance.positionAbs=c.positionAbs,this.instance.helperProportions=c.helperProportions,this.instance.offset.click=c.offset.click,this.instance._intersectsWith(this.instance.containerCache)&&(e=!0,a.each(c.sortables,function(){return this.instance.positionAbs=c.positionAbs,this.instance.helperProportions=c.helperProportions,this.instance.offset.click=c.offset.click,this!==g&&this.instance._intersectsWith(this.instance.containerCache)&&a.contains(g.instance.element[0],this.instance.element[0])&&(e=!1),e})),e?(this.instance.isOver||(this.instance.isOver=1,this.instance.currentItem=a(f).clone().removeAttr("id").appendTo(this.instance.element).data("ui-sortable-item",!0),this.instance.options._helper=this.instance.options.helper,this.instance.options.helper=function(){return b.helper[0]},d.target=this.instance.currentItem[0],this.instance._mouseCapture(d,!0),this.instance._mouseStart(d,!0,!0),this.instance.offset.click.top=c.offset.click.top,this.instance.offset.click.left=c.offset.click.left,this.instance.offset.parent.left-=c.offset.parent.left-this.instance.offset.parent.left,this.instance.offset.parent.top-=c.offset.parent.top-this.instance.offset.parent.top,c._trigger("toSortable",d),c.dropped=this.instance.element,c.currentItem=c.element,this.instance.fromOutside=c),this.instance.currentItem&&this.instance._mouseDrag(d)):this.instance.isOver&&(this.instance.isOver=0,this.instance.cancelHelperRemoval=!0,this.instance.options.revert=!1,this.instance._trigger("out",d,this.instance._uiHash(this.instance)),this.instance._mouseStop(d,!0),this.instance.options.helper=this.instance.options._helper,this.instance.currentItem.remove(),this.instance.placeholder&&this.instance.placeholder.remove(),c._trigger("fromSortable",d),c.dropped=!1)})}}),a.ui.plugin.add("draggable","cursor",{start:function(){var c=a("body"),b=a(this).data("ui-draggable").options;c.css("cursor")&&(b._cursor=c.css("cursor")),c.css("cursor",b.cursor)},stop:function(){var b=a(this).data("ui-draggable").options;b._cursor&&a("body").css("cursor",b._cursor)}}),a.ui.plugin.add("draggable","opacity",{start:function(d,b){var c=a(b.helper),f=a(this).data("ui-draggable").options;c.css("opacity")&&(f._opacity=c.css("opacity")),c.css("opacity",f.opacity)},stop:function(d,b){var c=a(this).data("ui-draggable").options;c._opacity&&a(b.helper).css("opacity",c._opacity)}}),a.ui.plugin.add("draggable","scroll",{start:function(){var b=a(this).data("ui-draggable");b.scrollParent[0]!==document&&"HTML"!==b.scrollParent[0].tagName&&(b.overflowOffset=b.scrollParent.offset())},drag:function(d){var b=a(this).data("ui-draggable"),c=b.options,f=!1;b.scrollParent[0]!==document&&"HTML"!==b.scrollParent[0].tagName?(c.axis&&"x"===c.axis||(b.overflowOffset.top+b.scrollParent[0].offsetHeight-d.pageY<c.scrollSensitivity?b.scrollParent[0].scrollTop=f=b.scrollParent[0].scrollTop+c.scrollSpeed:d.pageY-b.overflowOffset.top<c.scrollSensitivity&&(b.scrollParent[0].scrollTop=f=b.scrollParent[0].scrollTop-c.scrollSpeed)),c.axis&&"y"===c.axis||(b.overflowOffset.left+b.scrollParent[0].offsetWidth-d.pageX<c.scrollSensitivity?b.scrollParent[0].scrollLeft=f=b.scrollParent[0].scrollLeft+c.scrollSpeed:d.pageX-b.overflowOffset.left<c.scrollSensitivity&&(b.scrollParent[0].scrollLeft=f=b.scrollParent[0].scrollLeft-c.scrollSpeed))):(c.axis&&"x"===c.axis||(d.pageY-a(document).scrollTop()<c.scrollSensitivity?f=a(document).scrollTop(a(document).scrollTop()-c.scrollSpeed):a(window).height()-(d.pageY-a(document).scrollTop())<c.scrollSensitivity&&(f=a(document).scrollTop(a(document).scrollTop()+c.scrollSpeed))),c.axis&&"y"===c.axis||(d.pageX-a(document).scrollLeft()<c.scrollSensitivity?f=a(document).scrollLeft(a(document).scrollLeft()-c.scrollSpeed):a(window).width()-(d.pageX-a(document).scrollLeft())<c.scrollSensitivity&&(f=a(document).scrollLeft(a(document).scrollLeft()+c.scrollSpeed)))),f!==!1&&a.ui.ddmanager&&!c.dropBehaviour&&a.ui.ddmanager.prepareOffsets(b,d)}}),a.ui.plugin.add("draggable","snap",{start:function(){var c=a(this).data("ui-draggable"),b=c.options;c.snapElements=[],a(b.snap.constructor!==String?b.snap.items||":data(ui-draggable)":b.snap).each(function(){var d=a(this),e=d.offset();this!==c.element[0]&&c.snapElements.push({item:this,width:d.outerWidth(),height:d.outerHeight(),top:e.top,left:e.left})})},drag:function(F,B){var q,y,J,x,t,A,C,H,k,G,w=a(this).data("ui-draggable"),D=w.options,E=D.snapTolerance,z=B.offset.left,K=z+w.helperProportions.width,j=B.offset.top,I=j+w.helperProportions.height;for(k=w.snapElements.length-1;k>=0;k--){t=w.snapElements[k].left,A=t+w.snapElements[k].width,C=w.snapElements[k].top,H=C+w.snapElements[k].height,t-E>K||z>A+E||C-E>I||j>H+E||!a.contains(w.snapElements[k].item.ownerDocument,w.snapElements[k].item)?(w.snapElements[k].snapping&&w.options.snap.release&&w.options.snap.release.call(w.element,F,a.extend(w._uiHash(),{snapItem:w.snapElements[k].item})),w.snapElements[k].snapping=!1):("inner"!==D.snapMode&&(q=E>=Math.abs(C-I),y=E>=Math.abs(H-j),J=E>=Math.abs(t-K),x=E>=Math.abs(A-z),q&&(B.position.top=w._convertPositionTo("relative",{top:C-w.helperProportions.height,left:0}).top-w.margins.top),y&&(B.position.top=w._convertPositionTo("relative",{top:H,left:0}).top-w.margins.top),J&&(B.position.left=w._convertPositionTo("relative",{top:0,left:t-w.helperProportions.width}).left-w.margins.left),x&&(B.position.left=w._convertPositionTo("relative",{top:0,left:A}).left-w.margins.left)),G=q||y||J||x,"outer"!==D.snapMode&&(q=E>=Math.abs(C-j),y=E>=Math.abs(H-I),J=E>=Math.abs(t-z),x=E>=Math.abs(A-K),q&&(B.position.top=w._convertPositionTo("relative",{top:C,left:0}).top-w.margins.top),y&&(B.position.top=w._convertPositionTo("relative",{top:H-w.helperProportions.height,left:0}).top-w.margins.top),J&&(B.position.left=w._convertPositionTo("relative",{top:0,left:t}).left-w.margins.left),x&&(B.position.left=w._convertPositionTo("relative",{top:0,left:A-w.helperProportions.width}).left-w.margins.left)),!w.snapElements[k].snapping&&(q||y||J||x||G)&&w.options.snap.snap&&w.options.snap.snap.call(w.element,F,a.extend(w._uiHash(),{snapItem:w.snapElements[k].item})),w.snapElements[k].snapping=q||y||J||x||G)}}}),a.ui.plugin.add("draggable","stack",{start:function(){var d,b=this.data("ui-draggable").options,c=a.makeArray(a(b.stack)).sort(function(g,f){return(parseInt(a(g).css("zIndex"),10)||0)-(parseInt(a(f).css("zIndex"),10)||0)});c.length&&(d=parseInt(a(c[0]).css("zIndex"),10)||0,a(c).each(function(e){a(this).css("zIndex",d+e)}),this.css("zIndex",d+c.length))}}),a.ui.plugin.add("draggable","zIndex",{start:function(d,b){var c=a(b.helper),f=a(this).data("ui-draggable").options;c.css("zIndex")&&(f._zIndex=c.css("zIndex")),c.css("zIndex",f.zIndex)},stop:function(d,b){var c=a(this).data("ui-draggable").options;c._zIndex&&a(b.helper).css("zIndex",c._zIndex)}})})(jQuery);(function(a){function b(d,f,c){return d>f&&f+c>d}a.widget("ui.droppable",{version:"1.10.4",widgetEventPrefix:"drop",options:{accept:"*",activeClass:!1,addClasses:!0,greedy:!1,hoverClass:!1,scope:"default",tolerance:"intersect",activate:null,deactivate:null,drop:null,out:null,over:null},_create:function(){var f,c=this.options,d=c.accept;this.isover=!1,this.isout=!0,this.accept=a.isFunction(d)?d:function(e){return e.is(d)},this.proportions=function(){return arguments.length?(f=arguments[0],undefined):f?f:f={width:this.element[0].offsetWidth,height:this.element[0].offsetHeight}},a.ui.ddmanager.droppables[c.scope]=a.ui.ddmanager.droppables[c.scope]||[],a.ui.ddmanager.droppables[c.scope].push(this),c.addClasses&&this.element.addClass("ui-droppable")},_destroy:function(){for(var d=0,c=a.ui.ddmanager.droppables[this.options.scope];c.length>d;d++){c[d]===this&&c.splice(d,1)}this.element.removeClass("ui-droppable ui-droppable-disabled")},_setOption:function(d,c){"accept"===d&&(this.accept=a.isFunction(c)?c:function(e){return e.is(c)}),a.Widget.prototype._setOption.apply(this,arguments)},_activate:function(d){var c=a.ui.ddmanager.current;this.options.activeClass&&this.element.addClass(this.options.activeClass),c&&this._trigger("activate",d,this.ui(c))},_deactivate:function(d){var c=a.ui.ddmanager.current;this.options.activeClass&&this.element.removeClass(this.options.activeClass),c&&this._trigger("deactivate",d,this.ui(c))},_over:function(d){var c=a.ui.ddmanager.current;c&&(c.currentItem||c.element)[0]!==this.element[0]&&this.accept.call(this.element[0],c.currentItem||c.element)&&(this.options.hoverClass&&this.element.addClass(this.options.hoverClass),this._trigger("over",d,this.ui(c)))},_out:function(d){var c=a.ui.ddmanager.current;c&&(c.currentItem||c.element)[0]!==this.element[0]&&this.accept.call(this.element[0],c.currentItem||c.element)&&(this.options.hoverClass&&this.element.removeClass(this.options.hoverClass),this._trigger("out",d,this.ui(c)))},_drop:function(f,c){var d=c||a.ui.ddmanager.current,g=!1;return d&&(d.currentItem||d.element)[0]!==this.element[0]?(this.element.find(":data(ui-droppable)").not(".ui-draggable-dragging").each(function(){var h=a.data(this,"ui-droppable");return h.options.greedy&&!h.options.disabled&&h.options.scope===d.options.scope&&h.accept.call(h.element[0],d.currentItem||d.element)&&a.ui.intersect(d,a.extend(h,{offset:h.element.offset()}),h.options.tolerance)?(g=!0,!1):undefined}),g?!1:this.accept.call(this.element[0],d.currentItem||d.element)?(this.options.activeClass&&this.element.removeClass(this.options.activeClass),this.options.hoverClass&&this.element.removeClass(this.options.hoverClass),this._trigger("drop",f,this.ui(d)),this.element):!1):!1},ui:function(c){return{draggable:c.currentItem||c.element,helper:c.helper,position:c.position,offset:c.positionAbs}}}),a.ui.intersect=function(z,m,A){if(!m.offset){return !1}var j,x,g=(z.positionAbs||z.position.absolute).left,e=(z.positionAbs||z.position.absolute).top,k=g+z.helperProportions.width,q=e+z.helperProportions.height,w=m.offset.left,y=m.offset.top,v=w+m.proportions().width,f=y+m.proportions().height;switch(A){case"fit":return g>=w&&v>=k&&e>=y&&f>=q;case"intersect":return g+z.helperProportions.width/2>w&&v>k-z.helperProportions.width/2&&e+z.helperProportions.height/2>y&&f>q-z.helperProportions.height/2;case"pointer":return j=(z.positionAbs||z.position.absolute).left+(z.clickOffset||z.offset.click).left,x=(z.positionAbs||z.position.absolute).top+(z.clickOffset||z.offset.click).top,b(x,y,m.proportions().height)&&b(j,w,m.proportions().width);case"touch":return(e>=y&&f>=e||q>=y&&f>=q||y>e&&q>f)&&(g>=w&&v>=g||k>=w&&v>=k||w>g&&k>v);default:return !1}},a.ui.ddmanager={current:null,droppables:{"default":[]},prepareOffsets:function(h,d){var f,k,c=a.ui.ddmanager.droppables[h.options.scope]||[],j=d?d.type:null,g=(h.currentItem||h.element).find(":data(ui-droppable)").addBack();a:for(f=0;c.length>f;f++){if(!(c[f].options.disabled||h&&!c[f].accept.call(c[f].element[0],h.currentItem||h.element))){for(k=0;g.length>k;k++){if(g[k]===c[f].element[0]){c[f].proportions().height=0;continue a}}c[f].visible="none"!==c[f].element.css("display"),c[f].visible&&("mousedown"===j&&c[f]._activate.call(c[f],d),c[f].offset=c[f].element.offset(),c[f].proportions({width:c[f].element[0].offsetWidth,height:c[f].element[0].offsetHeight}))}}},drop:function(f,c){var d=!1;return a.each((a.ui.ddmanager.droppables[f.options.scope]||[]).slice(),function(){this.options&&(!this.options.disabled&&this.visible&&a.ui.intersect(f,this,this.options.tolerance)&&(d=this._drop.call(this,c)||d),!this.options.disabled&&this.visible&&this.accept.call(this.element[0],f.currentItem||f.element)&&(this.isout=!0,this.isover=!1,this._deactivate.call(this,c)))}),d},dragStart:function(d,c){d.element.parentsUntil("body").bind("scroll.droppable",function(){d.options.refreshPositions||a.ui.ddmanager.prepareOffsets(d,c)})},drag:function(d,c){d.options.refreshPositions&&a.ui.ddmanager.prepareOffsets(d,c),a.each(a.ui.ddmanager.droppables[d.options.scope]||[],function(){if(!this.options.disabled&&!this.greedyChild&&this.visible){var f,i,e,h=a.ui.intersect(d,this,this.options.tolerance),g=!h&&this.isover?"isout":h&&!this.isover?"isover":null;g&&(this.options.greedy&&(i=this.options.scope,e=this.element.parents(":data(ui-droppable)").filter(function(){return a.data(this,"ui-droppable").options.scope===i}),e.length&&(f=a.data(e[0],"ui-droppable"),f.greedyChild="isover"===g)),f&&"isover"===g&&(f.isover=!1,f.isout=!0,f._out.call(f,c)),this[g]=!0,this["isout"===g?"isover":"isout"]=!1,this["isover"===g?"_over":"_out"].call(this,c),f&&"isout"===g&&(f.isout=!1,f.isover=!0,f._over.call(f,c)))}})},dragStop:function(d,c){d.element.parentsUntil("body").unbind("scroll.droppable"),d.options.refreshPositions||a.ui.ddmanager.prepareOffsets(d,c)}}})(jQuery);(function(b){function c(d){return parseInt(d,10)||0}function a(d){return !isNaN(parseInt(d,10))}b.widget("ui.resizable",b.ui.mouse,{version:"1.10.4",widgetEventPrefix:"resize",options:{alsoResize:!1,animate:!1,animateDuration:"slow",animateEasing:"swing",aspectRatio:!1,autoHide:!1,containment:!1,ghost:!1,grid:!1,handles:"e,s,se",helper:!1,maxHeight:null,maxWidth:null,minHeight:10,minWidth:10,zIndex:90,resize:null,start:null,stop:null},_create:function(){var j,f,g,l,d,k=this,h=this.options;if(this.element.addClass("ui-resizable"),b.extend(this,{_aspectRatio:!!h.aspectRatio,aspectRatio:h.aspectRatio,originalElement:this.element,_proportionallyResizeElements:[],_helper:h.helper||h.ghost||h.animate?h.helper||"ui-resizable-helper":null}),this.element[0].nodeName.match(/canvas|textarea|input|select|button|img/i)&&(this.element.wrap(b("<div class='ui-wrapper' style='overflow: hidden;'></div>").css({position:this.element.css("position"),width:this.element.outerWidth(),height:this.element.outerHeight(),top:this.element.css("top"),left:this.element.css("left")})),this.element=this.element.parent().data("ui-resizable",this.element.data("ui-resizable")),this.elementIsWrapper=!0,this.element.css({marginLeft:this.originalElement.css("marginLeft"),marginTop:this.originalElement.css("marginTop"),marginRight:this.originalElement.css("marginRight"),marginBottom:this.originalElement.css("marginBottom")}),this.originalElement.css({marginLeft:0,marginTop:0,marginRight:0,marginBottom:0}),this.originalResizeStyle=this.originalElement.css("resize"),this.originalElement.css("resize","none"),this._proportionallyResizeElements.push(this.originalElement.css({position:"static",zoom:1,display:"block"})),this.originalElement.css({margin:this.originalElement.css("margin")}),this._proportionallyResize()),this.handles=h.handles||(b(".ui-resizable-handle",this.element).length?{n:".ui-resizable-n",e:".ui-resizable-e",s:".ui-resizable-s",w:".ui-resizable-w",se:".ui-resizable-se",sw:".ui-resizable-sw",ne:".ui-resizable-ne",nw:".ui-resizable-nw"}:"e,s,se"),this.handles.constructor===String){for("all"===this.handles&&(this.handles="n,e,s,w,se,sw,ne,nw"),j=this.handles.split(","),this.handles={},f=0;j.length>f;f++){g=b.trim(j[f]),d="ui-resizable-"+g,l=b("<div class='ui-resizable-handle "+d+"'></div>"),l.css({zIndex:h.zIndex}),"se"===g&&l.addClass("ui-icon ui-icon-gripsmall-diagonal-se"),this.handles[g]=".ui-resizable-"+g,this.element.append(l)}}this._renderAxis=function(q){var o,p,r,m;q=q||this.element;for(o in this.handles){this.handles[o].constructor===String&&(this.handles[o]=b(this.handles[o],this.element).show()),this.elementIsWrapper&&this.originalElement[0].nodeName.match(/textarea|input|select|button/i)&&(p=b(this.handles[o],this.element),m=/sw|ne|nw|se|n|s/.test(o)?p.outerHeight():p.outerWidth(),r=["padding",/ne|nw|n/.test(o)?"Top":/se|sw|s/.test(o)?"Bottom":/^e$/.test(o)?"Right":"Left"].join(""),q.css(r,m),this._proportionallyResize()),b(this.handles[o]).length}},this._renderAxis(this.element),this._handles=b(".ui-resizable-handle",this.element).disableSelection(),this._handles.mouseover(function(){k.resizing||(this.className&&(l=this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i)),k.axis=l&&l[1]?l[1]:"se")}),h.autoHide&&(this._handles.hide(),b(this.element).addClass("ui-resizable-autohide").mouseenter(function(){h.disabled||(b(this).removeClass("ui-resizable-autohide"),k._handles.show())}).mouseleave(function(){h.disabled||k.resizing||(b(this).addClass("ui-resizable-autohide"),k._handles.hide())})),this._mouseInit()},_destroy:function(){this._mouseDestroy();var f,d=function(g){b(g).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing").removeData("resizable").removeData("ui-resizable").unbind(".resizable").find(".ui-resizable-handle").remove()};return this.elementIsWrapper&&(d(this.element),f=this.element,this.originalElement.css({position:f.css("position"),width:f.outerWidth(),height:f.outerHeight(),top:f.css("top"),left:f.css("left")}).insertAfter(f),f.remove()),this.originalElement.css("resize",this.originalResizeStyle),d(this.originalElement),this},_mouseCapture:function(g){var d,f,h=!1;for(d in this.handles){f=b(this.handles[d])[0],(f===g.target||b.contains(f,g.target))&&(h=!0)}return !this.options.disabled&&h},_mouseStart:function(e){var g,l,d,k=this.options,j=this.element.position(),f=this.element;return this.resizing=!0,/absolute/.test(f.css("position"))?f.css({position:"absolute",top:f.css("top"),left:f.css("left")}):f.is(".ui-draggable")&&f.css({position:"absolute",top:j.top,left:j.left}),this._renderProxy(),g=c(this.helper.css("left")),l=c(this.helper.css("top")),k.containment&&(g+=b(k.containment).scrollLeft()||0,l+=b(k.containment).scrollTop()||0),this.offset=this.helper.offset(),this.position={left:g,top:l},this.size=this._helper?{width:this.helper.width(),height:this.helper.height()}:{width:f.width(),height:f.height()},this.originalSize=this._helper?{width:f.outerWidth(),height:f.outerHeight()}:{width:f.width(),height:f.height()},this.originalPosition={left:g,top:l},this.sizeDiff={width:f.outerWidth()-f.width(),height:f.outerHeight()-f.height()},this.originalMousePosition={left:e.pageX,top:e.pageY},this.aspectRatio="number"==typeof k.aspectRatio?k.aspectRatio:this.originalSize.width/this.originalSize.height||1,d=b(".ui-resizable-"+this.axis).css("cursor"),b("body").css("cursor","auto"===d?this.axis+"-resize":d),f.addClass("ui-resizable-resizing"),this._propagate("start",e),!0},_mouseDrag:function(v){var q,A=this.helper,k={},y=this.originalMousePosition,j=this.axis,f=this.position.top,t=this.position.left,m=this.size.width,x=this.size.height,z=v.pageX-y.left||0,w=v.pageY-y.top||0,g=this._change[j];return g?(q=g.apply(this,[v,z,w]),this._updateVirtualBoundaries(v.shiftKey),(this._aspectRatio||v.shiftKey)&&(q=this._updateRatio(q,v)),q=this._respectSize(q,v),this._updateCache(q),this._propagate("resize",v),this.position.top!==f&&(k.top=this.position.top+"px"),this.position.left!==t&&(k.left=this.position.left+"px"),this.size.width!==m&&(k.width=this.size.width+"px"),this.size.height!==x&&(k.height=this.size.height+"px"),A.css(k),!this._helper&&this._proportionallyResizeElements.length&&this._proportionallyResize(),b.isEmptyObject(k)||this._trigger("resize",v,this.ui()),!1):!1},_mouseStop:function(p){this.resizing=!1;var k,u,g,t,f,d,m,j=this.options,q=this;return this._helper&&(k=this._proportionallyResizeElements,u=k.length&&/textarea/i.test(k[0].nodeName),g=u&&b.ui.hasScroll(k[0],"left")?0:q.sizeDiff.height,t=u?0:q.sizeDiff.width,f={width:q.helper.width()-t,height:q.helper.height()-g},d=parseInt(q.element.css("left"),10)+(q.position.left-q.originalPosition.left)||null,m=parseInt(q.element.css("top"),10)+(q.position.top-q.originalPosition.top)||null,j.animate||this.element.css(b.extend(f,{top:m,left:d})),q.helper.height(q.size.height),q.helper.width(q.size.width),this._helper&&!j.animate&&this._proportionallyResize()),b("body").css("cursor","auto"),this.element.removeClass("ui-resizable-resizing"),this._propagate("stop",p),this._helper&&this.helper.remove(),!1},_updateVirtualBoundaries:function(f){var i,g,k,d,j,h=this.options;j={minWidth:a(h.minWidth)?h.minWidth:0,maxWidth:a(h.maxWidth)?h.maxWidth:1/0,minHeight:a(h.minHeight)?h.minHeight:0,maxHeight:a(h.maxHeight)?h.maxHeight:1/0},(this._aspectRatio||f)&&(i=j.minHeight*this.aspectRatio,k=j.minWidth/this.aspectRatio,g=j.maxHeight*this.aspectRatio,d=j.maxWidth/this.aspectRatio,i>j.minWidth&&(j.minWidth=i),k>j.minHeight&&(j.minHeight=k),j.maxWidth>g&&(j.maxWidth=g),j.maxHeight>d&&(j.maxHeight=d)),this._vBoundaries=j},_updateCache:function(d){this.offset=this.helper.offset(),a(d.left)&&(this.position.left=d.left),a(d.top)&&(this.position.top=d.top),a(d.height)&&(this.size.height=d.height),a(d.width)&&(this.size.width=d.width)},_updateRatio:function(d){var g=this.position,f=this.size,h=this.axis;return a(d.height)?d.width=d.height*this.aspectRatio:a(d.width)&&(d.height=d.width/this.aspectRatio),"sw"===h&&(d.left=g.left+(f.width-d.width),d.top=null),"nw"===h&&(d.top=g.top+(f.height-d.height),d.left=g.left+(f.width-d.width)),d},_respectSize:function(v){var k=this._vBoundaries,w=this.axis,g=a(v.width)&&k.maxWidth&&k.maxWidth<v.width,p=a(v.height)&&k.maxHeight&&k.maxHeight<v.height,f=a(v.width)&&k.minWidth&&k.minWidth>v.width,d=a(v.height)&&k.minHeight&&k.minHeight>v.height,j=this.originalPosition.left+this.originalSize.width,i=this.position.top+this.size.height,m=/sw|nw|w/.test(w),q=/nw|ne|n/.test(w);return f&&(v.width=k.minWidth),d&&(v.height=k.minHeight),g&&(v.width=k.maxWidth),p&&(v.height=k.maxHeight),f&&m&&(v.left=j-k.minWidth),g&&m&&(v.left=j-k.maxWidth),d&&q&&(v.top=i-k.minHeight),p&&q&&(v.top=i-k.maxHeight),v.width||v.height||v.left||!v.top?v.width||v.height||v.top||!v.left||(v.left=null):v.top=null,v},_proportionallyResize:function(){if(this._proportionallyResizeElements.length){var g,j,f,h,k,d=this.helper||this.element;for(g=0;this._proportionallyResizeElements.length>g;g++){if(k=this._proportionallyResizeElements[g],!this.borderDif){for(this.borderDif=[],f=[k.css("borderTopWidth"),k.css("borderRightWidth"),k.css("borderBottomWidth"),k.css("borderLeftWidth")],h=[k.css("paddingTop"),k.css("paddingRight"),k.css("paddingBottom"),k.css("paddingLeft")],j=0;f.length>j;j++){this.borderDif[j]=(parseInt(f[j],10)||0)+(parseInt(h[j],10)||0)}}k.css({height:d.height()-this.borderDif[0]-this.borderDif[2]||0,width:d.width()-this.borderDif[1]-this.borderDif[3]||0})}}},_renderProxy:function(){var f=this.element,d=this.options;this.elementOffset=f.offset(),this._helper?(this.helper=this.helper||b("<div style='overflow:hidden;'></div>"),this.helper.addClass(this._helper).css({width:this.element.outerWidth()-1,height:this.element.outerHeight()-1,position:"absolute",left:this.elementOffset.left+"px",top:this.elementOffset.top+"px",zIndex:++d.zIndex}),this.helper.appendTo("body").disableSelection()):this.helper=this.element},_change:{e:function(d,f){return{width:this.originalSize.width+f}},w:function(f,h){var d=this.originalSize,g=this.originalPosition;return{left:g.left+h,width:d.width-h}},n:function(f,h,d){var g=this.originalSize,j=this.originalPosition;return{top:j.top+d,height:g.height-d}},s:function(f,g,d){return{height:this.originalSize.height+d}},se:function(g,d,f){return b.extend(this._change.s.apply(this,arguments),this._change.e.apply(this,[g,d,f]))},sw:function(g,d,f){return b.extend(this._change.s.apply(this,arguments),this._change.w.apply(this,[g,d,f]))},ne:function(g,d,f){return b.extend(this._change.n.apply(this,arguments),this._change.e.apply(this,[g,d,f]))},nw:function(g,d,f){return b.extend(this._change.n.apply(this,arguments),this._change.w.apply(this,[g,d,f]))}},_propagate:function(f,d){b.ui.plugin.call(this,f,[d,this.ui()]),"resize"!==f&&this._trigger(f,d,this.ui())},plugins:{},ui:function(){return{originalElement:this.originalElement,element:this.element,helper:this.helper,position:this.position,size:this.size,originalSize:this.originalSize,originalPosition:this.originalPosition}}}),b.ui.plugin.add("resizable","animate",{stop:function(p){var k=b(this).data("ui-resizable"),u=k.options,g=k._proportionallyResizeElements,t=g.length&&/textarea/i.test(g[0].nodeName),f=t&&b.ui.hasScroll(g[0],"left")?0:k.sizeDiff.height,d=t?0:k.sizeDiff.width,m={width:k.size.width-d,height:k.size.height-f},j=parseInt(k.element.css("left"),10)+(k.position.left-k.originalPosition.left)||null,q=parseInt(k.element.css("top"),10)+(k.position.top-k.originalPosition.top)||null;k.element.animate(b.extend(m,q&&j?{top:q,left:j}:{}),{duration:u.animateDuration,easing:u.animateEasing,step:function(){var e={width:parseInt(k.element.css("width"),10),height:parseInt(k.element.css("height"),10),top:parseInt(k.element.css("top"),10),left:parseInt(k.element.css("left"),10)};g&&g.length&&b(g[0]).css({width:e.width,height:e.height}),k._updateCache(e),k._propagate("resize",p)}})}}),b.ui.plugin.add("resizable","containment",{start:function(){var m,y,j,w,g,e,q,k=b(this).data("ui-resizable"),v=k.options,x=k.element,t=v.containment,f=t instanceof b?t.get(0):/parent/.test(t)?x.parent().get(0):t;f&&(k.containerElement=b(f),/document/.test(t)||t===document?(k.containerOffset={left:0,top:0},k.containerPosition={left:0,top:0},k.parentData={element:b(document),left:0,top:0,width:b(document).width(),height:b(document).height()||document.body.parentNode.scrollHeight}):(m=b(f),y=[],b(["Top","Right","Left","Bottom"]).each(function(d,h){y[d]=c(m.css("padding"+h))}),k.containerOffset=m.offset(),k.containerPosition=m.position(),k.containerSize={height:m.innerHeight()-y[3],width:m.innerWidth()-y[1]},j=k.containerOffset,w=k.containerSize.height,g=k.containerSize.width,e=b.ui.hasScroll(f,"left")?f.scrollWidth:g,q=b.ui.hasScroll(f)?f.scrollHeight:w,k.parentData={element:f,left:j.left,top:j.top,width:e,height:q}))},resize:function(q){var m,y,j,w,g=b(this).data("ui-resizable"),f=g.options,p=g.containerOffset,k=g.position,v=g._aspectRatio||q.shiftKey,x={top:0,left:0},t=g.containerElement;t[0]!==document&&/static/.test(t.css("position"))&&(x=p),k.left<(g._helper?p.left:0)&&(g.size.width=g.size.width+(g._helper?g.position.left-p.left:g.position.left-x.left),v&&(g.size.height=g.size.width/g.aspectRatio),g.position.left=f.helper?p.left:0),k.top<(g._helper?p.top:0)&&(g.size.height=g.size.height+(g._helper?g.position.top-p.top:g.position.top),v&&(g.size.width=g.size.height*g.aspectRatio),g.position.top=g._helper?p.top:0),g.offset.left=g.parentData.left+g.position.left,g.offset.top=g.parentData.top+g.position.top,m=Math.abs((g._helper?g.offset.left-x.left:g.offset.left-x.left)+g.sizeDiff.width),y=Math.abs((g._helper?g.offset.top-x.top:g.offset.top-p.top)+g.sizeDiff.height),j=g.containerElement.get(0)===g.element.parent().get(0),w=/relative|absolute/.test(g.containerElement.css("position")),j&&w&&(m-=Math.abs(g.parentData.left)),m+g.size.width>=g.parentData.width&&(g.size.width=g.parentData.width-m,v&&(g.size.height=g.size.width/g.aspectRatio)),y+g.size.height>=g.parentData.height&&(g.size.height=g.parentData.height-y,v&&(g.size.width=g.size.height*g.aspectRatio))},stop:function(){var p=b(this).data("ui-resizable"),k=p.options,t=p.containerOffset,g=p.containerPosition,q=p.containerElement,f=b(p.helper),d=f.offset(),m=f.outerWidth()-p.sizeDiff.width,j=f.outerHeight()-p.sizeDiff.height;p._helper&&!k.animate&&/relative/.test(q.css("position"))&&b(this).css({left:d.left-g.left-t.left,width:m,height:j}),p._helper&&!k.animate&&/static/.test(q.css("position"))&&b(this).css({left:d.left-g.left-t.left,width:m,height:j})}}),b.ui.plugin.add("resizable","alsoResize",{start:function(){var g=b(this).data("ui-resizable"),d=g.options,f=function(h){b(h).each(function(){var i=b(this);i.data("ui-resizable-alsoresize",{width:parseInt(i.width(),10),height:parseInt(i.height(),10),left:parseInt(i.css("left"),10),top:parseInt(i.css("top"),10)})})};"object"!=typeof d.alsoResize||d.alsoResize.parentNode?f(d.alsoResize):d.alsoResize.length?(d.alsoResize=d.alsoResize[0],f(d.alsoResize)):b.each(d.alsoResize,function(e){f(e)})},resize:function(l,f){var j=b(this).data("ui-resizable"),p=j.options,d=j.originalSize,m=j.originalPosition,k={height:j.size.height-d.height||0,width:j.size.width-d.width||0,top:j.position.top-m.top||0,left:j.position.left-m.left||0},g=function(i,h){b(i).each(function(){var r=b(this),t=b(this).data("ui-resizable-alsoresize"),q={},s=h&&h.length?h:r.parents(f.originalElement[0]).length?["width","height"]:["width","height","top","left"];b.each(s,function(o,u){var n=(t[u]||0)+(k[u]||0);n&&n>=0&&(q[u]=n||null)}),r.css(q)})};"object"!=typeof p.alsoResize||p.alsoResize.nodeType?g(p.alsoResize):b.each(p.alsoResize,function(h,i){g(h,i)})},stop:function(){b(this).removeData("resizable-alsoresize")}}),b.ui.plugin.add("resizable","ghost",{start:function(){var g=b(this).data("ui-resizable"),d=g.options,f=g.size;g.ghost=g.originalElement.clone(),g.ghost.css({opacity:0.25,display:"block",position:"relative",height:f.height,width:f.width,margin:0,left:0,top:0}).addClass("ui-resizable-ghost").addClass("string"==typeof d.ghost?d.ghost:""),g.ghost.appendTo(g.helper)},resize:function(){var d=b(this).data("ui-resizable");d.ghost&&d.ghost.css({position:"relative",height:d.size.height,width:d.size.width})},stop:function(){var d=b(this).data("ui-resizable");d.ghost&&d.helper&&d.helper.get(0).removeChild(d.ghost.get(0))}}),b.ui.plugin.add("resizable","grid",{resize:function(){var C=b(this).data("ui-resizable"),y=C.options,I=C.size,t=C.originalSize,F=C.originalPosition,q=C.axis,j="number"==typeof y.grid?[y.grid,y.grid]:y.grid,z=j[0]||1,x=j[1]||1,E=Math.round((I.width-t.width)/z)*z,H=Math.round((I.height-t.height)/x)*x,D=t.width+E,k=t.height+H,B=y.maxWidth&&D>y.maxWidth,A=y.maxHeight&&k>y.maxHeight,w=y.minWidth&&y.minWidth>D,G=y.minHeight&&y.minHeight>k;y.grid=j,w&&(D+=z),G&&(k+=x),B&&(D-=z),A&&(k-=x),/^(se|s|e)$/.test(q)?(C.size.width=D,C.size.height=k):/^(ne)$/.test(q)?(C.size.width=D,C.size.height=k,C.position.top=F.top-H):/^(sw)$/.test(q)?(C.size.width=D,C.size.height=k,C.position.left=F.left-E):(k-x>0?(C.size.height=k,C.position.top=F.top-H):(C.size.height=x,C.position.top=F.top+t.height-x),D-z>0?(C.size.width=D,C.position.left=F.left-E):(C.size.width=z,C.position.left=F.left+t.width-z))}})})(jQuery);(function(a){a.widget("ui.selectable",a.ui.mouse,{version:"1.10.4",options:{appendTo:"body",autoRefresh:!0,distance:0,filter:"*",tolerance:"touch",selected:null,selecting:null,start:null,stop:null,unselected:null,unselecting:null},_create:function(){var c,b=this;this.element.addClass("ui-selectable"),this.dragged=!1,this.refresh=function(){c=a(b.options.filter,b.element[0]),c.addClass("ui-selectee"),c.each(function(){var f=a(this),d=f.offset();a.data(this,"selectable-item",{element:this,$element:f,left:d.left,top:d.top,right:d.left+f.outerWidth(),bottom:d.top+f.outerHeight(),startselected:!1,selected:f.hasClass("ui-selected"),selecting:f.hasClass("ui-selecting"),unselecting:f.hasClass("ui-unselecting")})})},this.refresh(),this.selectees=c.addClass("ui-selectee"),this._mouseInit(),this.helper=a("<div class='ui-selectable-helper'></div>")},_destroy:function(){this.selectees.removeClass("ui-selectee").removeData("selectable-item"),this.element.removeClass("ui-selectable ui-selectable-disabled"),this._mouseDestroy()},_mouseStart:function(d){var b=this,c=this.options;this.opos=[d.pageX,d.pageY],this.options.disabled||(this.selectees=a(c.filter,this.element[0]),this._trigger("start",d),a(c.appendTo).append(this.helper),this.helper.css({left:d.pageX,top:d.pageY,width:0,height:0}),c.autoRefresh&&this.refresh(),this.selectees.filter(".ui-selected").each(function(){var e=a.data(this,"selectable-item");e.startselected=!0,d.metaKey||d.ctrlKey||(e.$element.removeClass("ui-selected"),e.selected=!1,e.$element.addClass("ui-unselecting"),e.unselecting=!0,b._trigger("unselecting",d,{unselecting:e.element}))}),a(d.target).parents().addBack().each(function(){var e,f=a.data(this,"selectable-item");return f?(e=!d.metaKey&&!d.ctrlKey||!f.$element.hasClass("ui-selected"),f.$element.removeClass(e?"ui-unselecting":"ui-selected").addClass(e?"ui-selecting":"ui-unselecting"),f.unselecting=!e,f.selecting=e,f.selected=e,e?b._trigger("selecting",d,{selecting:f.element}):b._trigger("unselecting",d,{unselecting:f.element}),!1):undefined}))},_mouseDrag:function(h){if(this.dragged=!0,!this.options.disabled){var d,f=this,k=this.options,c=this.opos[0],j=this.opos[1],g=h.pageX,b=h.pageY;return c>g&&(d=g,g=c,c=d),j>b&&(d=b,b=j,j=d),this.helper.css({left:c,top:j,width:g-c,height:b-j}),this.selectees.each(function(){var e=a.data(this,"selectable-item"),l=!1;e&&e.element!==f.element[0]&&("touch"===k.tolerance?l=!(e.left>g||c>e.right||e.top>b||j>e.bottom):"fit"===k.tolerance&&(l=e.left>c&&g>e.right&&e.top>j&&b>e.bottom),l?(e.selected&&(e.$element.removeClass("ui-selected"),e.selected=!1),e.unselecting&&(e.$element.removeClass("ui-unselecting"),e.unselecting=!1),e.selecting||(e.$element.addClass("ui-selecting"),e.selecting=!0,f._trigger("selecting",h,{selecting:e.element}))):(e.selecting&&((h.metaKey||h.ctrlKey)&&e.startselected?(e.$element.removeClass("ui-selecting"),e.selecting=!1,e.$element.addClass("ui-selected"),e.selected=!0):(e.$element.removeClass("ui-selecting"),e.selecting=!1,e.startselected&&(e.$element.addClass("ui-unselecting"),e.unselecting=!0),f._trigger("unselecting",h,{unselecting:e.element}))),e.selected&&(h.metaKey||h.ctrlKey||e.startselected||(e.$element.removeClass("ui-selected"),e.selected=!1,e.$element.addClass("ui-unselecting"),e.unselecting=!0,f._trigger("unselecting",h,{unselecting:e.element})))))}),!1}},_mouseStop:function(c){var b=this;return this.dragged=!1,a(".ui-unselecting",this.element[0]).each(function(){var d=a.data(this,"selectable-item");d.$element.removeClass("ui-unselecting"),d.unselecting=!1,d.startselected=!1,b._trigger("unselected",c,{unselected:d.element})}),a(".ui-selecting",this.element[0]).each(function(){var d=a.data(this,"selectable-item");d.$element.removeClass("ui-selecting").addClass("ui-selected"),d.selecting=!1,d.selected=!0,d.startselected=!0,b._trigger("selected",c,{selected:d.element})}),this._trigger("stop",c),this.helper.remove(),!1}})})(jQuery);(function(b){function c(f,g,d){return f>g&&g+d>f}function a(d){return/left|right/.test(d.css("float"))||/inline|table-cell/.test(d.css("display"))}b.widget("ui.sortable",b.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:1000,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 d=this.options;this.containerCache={},this.element.addClass("ui-sortable"),this.refresh(),this.floating=this.items.length?"x"===d.axis||a(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 d=this.items.length-1;d>=0;d--){this.items[d].item.removeData(this.widgetName+"-item")}return this},_setOption:function(f,d){"disabled"===f?(this.options[f]=d,this.widget().toggleClass("ui-sortable-disabled",!!d)):b.Widget.prototype._setOption.apply(this,arguments)},_mouseCapture:function(g,d){var f=null,j=!1,h=this;return this.reverting?!1:this.options.disabled||"static"===this.options.type?!1:(this._refreshItems(g),b(g.target).parents().each(function(){return b.data(this,h.widgetName+"-item")===h?(f=b(this),!1):undefined}),b.data(g.target,h.widgetName+"-item")===h&&(f=b(g.target)),f?!this.options.handle||d||(b(this.options.handle,f).find("*").addBack().each(function(){this===g.target&&(j=!0)}),j)?(this.currentItem=f,this._removeCurrentsFromItems(),!0):!1:!1)},_mouseStart:function(h,f,g){var k,j,d=this.options;if(this.currentContainer=this,this.refreshPositions(),this.helper=this._createHelper(h),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},b.extend(this.offset,{click:{left:h.pageX-this.offset.left,top:h.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(h),this.originalPageX=h.pageX,this.originalPageY=h.pageY,d.cursorAt&&this._adjustOffsetFromHelper(d.cursorAt),this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]},this.helper[0]!==this.currentItem[0]&&this.currentItem.hide(),this._createPlaceholder(),d.containment&&this._setContainment(),d.cursor&&"auto"!==d.cursor&&(j=this.document.find("body"),this.storedCursor=j.css("cursor"),j.css("cursor",d.cursor),this.storedStylesheet=b("<style>*{ cursor: "+d.cursor+" !important; }</style>").appendTo(j)),d.opacity&&(this.helper.css("opacity")&&(this._storedOpacity=this.helper.css("opacity")),this.helper.css("opacity",d.opacity)),d.zIndex&&(this.helper.css("zIndex")&&(this._storedZIndex=this.helper.css("zIndex")),this.helper.css("zIndex",d.zIndex)),this.scrollParent[0]!==document&&"HTML"!==this.scrollParent[0].tagName&&(this.overflowOffset=this.scrollParent.offset()),this._trigger("start",h,this._uiHash()),this._preserveHelperProportions||this._cacheHelperProportions(),!g){for(k=this.containers.length-1;k>=0;k--){this.containers[k]._trigger("activate",h,this._uiHash(this))}}return b.ui.ddmanager&&(b.ui.ddmanager.current=this),b.ui.ddmanager&&!d.dropBehaviour&&b.ui.ddmanager.prepareOffsets(this,h),this.dragging=!0,this.helper.addClass("ui-sortable-helper"),this._mouseDrag(h),!0},_mouseDrag:function(j){var f,g,l,k,d=this.options,h=!1;for(this.position=this._generatePosition(j),this.positionAbs=this._convertPositionTo("absolute"),this.lastPositionAbs||(this.lastPositionAbs=this.positionAbs),this.options.scroll&&(this.scrollParent[0]!==document&&"HTML"!==this.scrollParent[0].tagName?(this.overflowOffset.top+this.scrollParent[0].offsetHeight-j.pageY<d.scrollSensitivity?this.scrollParent[0].scrollTop=h=this.scrollParent[0].scrollTop+d.scrollSpeed:j.pageY-this.overflowOffset.top<d.scrollSensitivity&&(this.scrollParent[0].scrollTop=h=this.scrollParent[0].scrollTop-d.scrollSpeed),this.overflowOffset.left+this.scrollParent[0].offsetWidth-j.pageX<d.scrollSensitivity?this.scrollParent[0].scrollLeft=h=this.scrollParent[0].scrollLeft+d.scrollSpeed:j.pageX-this.overflowOffset.left<d.scrollSensitivity&&(this.scrollParent[0].scrollLeft=h=this.scrollParent[0].scrollLeft-d.scrollSpeed)):(j.pageY-b(document).scrollTop()<d.scrollSensitivity?h=b(document).scrollTop(b(document).scrollTop()-d.scrollSpeed):b(window).height()-(j.pageY-b(document).scrollTop())<d.scrollSensitivity&&(h=b(document).scrollTop(b(document).scrollTop()+d.scrollSpeed)),j.pageX-b(document).scrollLeft()<d.scrollSensitivity?h=b(document).scrollLeft(b(document).scrollLeft()-d.scrollSpeed):b(window).width()-(j.pageX-b(document).scrollLeft())<d.scrollSensitivity&&(h=b(document).scrollLeft(b(document).scrollLeft()+d.scrollSpeed))),h!==!1&&b.ui.ddmanager&&!d.dropBehaviour&&b.ui.ddmanager.prepareOffsets(this,j)),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"),f=this.items.length-1;f>=0;f--){if(g=this.items[f],l=g.item[0],k=this._intersectsWithPointer(g),k&&g.instance===this.currentContainer&&l!==this.currentItem[0]&&this.placeholder[1===k?"next":"prev"]()[0]!==l&&!b.contains(this.placeholder[0],l)&&("semi-dynamic"===this.options.type?!b.contains(this.element[0],l):!0)){if(this.direction=1===k?"down":"up","pointer"!==this.options.tolerance&&!this._intersectsWithSides(g)){break}this._rearrange(j,g),this._trigger("change",j,this._uiHash());break}}return this._contactContainers(j),b.ui.ddmanager&&b.ui.ddmanager.drag(this,j),this._trigger("sort",j,this._uiHash()),this.lastPositionAbs=this.positionAbs,!1},_mouseStop:function(h,f){if(h){if(b.ui.ddmanager&&!this.options.dropBehaviour&&b.ui.ddmanager.drop(this,h),this.options.revert){var g=this,k=this.placeholder.offset(),j=this.options.axis,d={};j&&"x"!==j||(d.left=k.left-this.offset.parent.left-this.margins.left+(this.offsetParent[0]===document.body?0:this.offsetParent[0].scrollLeft)),j&&"y"!==j||(d.top=k.top-this.offset.parent.top-this.margins.top+(this.offsetParent[0]===document.body?0:this.offsetParent[0].scrollTop)),this.reverting=!0,b(this.helper).animate(d,parseInt(this.options.revert,10)||500,function(){g._clear(h)})}else{this._clear(h,f)}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 d=this.containers.length-1;d>=0;d--){this.containers[d]._trigger("deactivate",null,this._uiHash(this)),this.containers[d].containerCache.over&&(this.containers[d]._trigger("out",null,this._uiHash(this)),this.containers[d].containerCache.over=0)}}return 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(),b.extend(this,{helper:null,dragging:!1,reverting:!1,_noFinalSort:null}),this.domPosition.prev?b(this.domPosition.prev).after(this.currentItem):b(this.domPosition.parent).prepend(this.currentItem)),this},serialize:function(g){var d=this._getItemsAsjQuery(g&&g.connected),f=[];return g=g||{},b(d).each(function(){var e=(b(g.item||this).attr(g.attribute||"id")||"").match(g.expression||/(.+)[\-=_](.+)/);e&&f.push((g.key||e[1]+"[]")+"="+(g.key&&g.expression?e[1]:e[2]))}),!f.length&&g.key&&f.push(g.key+"="),f.join("&")},toArray:function(g){var d=this._getItemsAsjQuery(g&&g.connected),f=[];return g=g||{},d.each(function(){f.push(b(g.item||this).attr(g.attribute||"id")||"")}),f},_intersectsWith:function(B){var w=this.positionAbs.left,q=w+this.helperProportions.width,C=this.positionAbs.top,k=C+this.helperProportions.height,j=B.left,z=j+B.width,f=B.top,v=f+B.height,m=this.offset.click.top,y=this.offset.click.left,A="x"===this.options.axis||C+m>f&&v>C+m,x="y"===this.options.axis||w+y>j&&z>w+y,g=A&&x;return"pointer"===this.options.tolerance||this.options.forcePointerForContainers||"pointer"!==this.options.tolerance&&this.helperProportions[this.floating?"width":"height"]>B[this.floating?"width":"height"]?g:w+this.helperProportions.width/2>j&&z>q-this.helperProportions.width/2&&C+this.helperProportions.height/2>f&&v>k-this.helperProportions.height/2},_intersectsWithPointer:function(f){var e="x"===this.options.axis||c(this.positionAbs.top+this.offset.click.top,f.top,f.height),g="y"===this.options.axis||c(this.positionAbs.left+this.offset.click.left,f.left,f.width),j=e&&g,h=this._getDragVerticalDirection(),d=this._getDragHorizontalDirection();return j?this.floating?d&&"right"===d||"down"===h?2:1:h&&("down"===h?2:1):!1},_intersectsWithSides:function(e){var d=c(this.positionAbs.top+this.offset.click.top,e.top+e.height/2,e.height),f=c(this.positionAbs.left+this.offset.click.left,e.left+e.width/2,e.width),h=this._getDragVerticalDirection(),g=this._getDragHorizontalDirection();return this.floating&&g?"right"===g&&f||"left"===g&&!f:h&&("down"===h&&d||"up"===h&&!d)},_getDragVerticalDirection:function(){var d=this.positionAbs.top-this.lastPositionAbs.top;return 0!==d&&(d>0?"down":"up")},_getDragHorizontalDirection:function(){var d=this.positionAbs.left-this.lastPositionAbs.left;return 0!==d&&(d>0?"right":"left")},refresh:function(d){return this._refreshItems(d),this.refreshPositions(),this},_connectWith:function(){var d=this.options;return d.connectWith.constructor===String?[d.connectWith]:d.connectWith},_getItemsAsjQuery:function(p){function k(){d.push(this)}var t,g,f,q,d=[],m=[],j=this._connectWith();if(j&&p){for(t=j.length-1;t>=0;t--){for(f=b(j[t]),g=f.length-1;g>=0;g--){q=b.data(f[g],this.widgetFullName),q&&q!==this&&!q.options.disabled&&m.push([b.isFunction(q.options.items)?q.options.items.call(q.element):b(q.options.items,q.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),q])}}}for(m.push([b.isFunction(this.options.items)?this.options.items.call(this.element,null,{options:this.options,item:this.currentItem}):b(this.options.items,this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),this]),t=m.length-1;t>=0;t--){m[t][0].each(k)}return b(d)},_removeCurrentsFromItems:function(){var d=this.currentItem.find(":data("+this.widgetName+"-item)");this.items=b.grep(this.items,function(f){for(var e=0;d.length>e;e++){if(d[e]===f.item[0]){return !1}}return !0})},_refreshItems:function(q){this.items=[],this.containers=[this];var m,y,j,g,w,f,p,k,v=this.items,x=[[b.isFunction(this.options.items)?this.options.items.call(this.element[0],q,{item:this.currentItem}):b(this.options.items,this.element),this]],t=this._connectWith();if(t&&this.ready){for(m=t.length-1;m>=0;m--){for(j=b(t[m]),y=j.length-1;y>=0;y--){g=b.data(j[y],this.widgetFullName),g&&g!==this&&!g.options.disabled&&(x.push([b.isFunction(g.options.items)?g.options.items.call(g.element[0],q,{item:this.currentItem}):b(g.options.items,g.element),g]),this.containers.push(g))}}}for(m=x.length-1;m>=0;m--){for(w=x[m][1],f=x[m][0],y=0,k=f.length;k>y;y++){p=b(f[y]),p.data(this.widgetName+"-item",w),v.push({item:p,instance:w,width:0,height:0,left:0,top:0})}}},refreshPositions:function(g){this.offsetParent&&this.helper&&(this.offset.parent=this._getParentOffset());var d,f,j,h;for(d=this.items.length-1;d>=0;d--){f=this.items[d],f.instance!==this.currentContainer&&this.currentContainer&&f.item[0]!==this.currentItem[0]||(j=this.options.toleranceElement?b(this.options.toleranceElement,f.item):f.item,g||(f.width=j.outerWidth(),f.height=j.outerHeight()),h=j.offset(),f.left=h.left,f.top=h.top)}if(this.options.custom&&this.options.custom.refreshContainers){this.options.custom.refreshContainers.call(this)}else{for(d=this.containers.length-1;d>=0;d--){h=this.containers[d].element.offset(),this.containers[d].containerCache.left=h.left,this.containers[d].containerCache.top=h.top,this.containers[d].containerCache.width=this.containers[d].element.outerWidth(),this.containers[d].containerCache.height=this.containers[d].element.outerHeight()}}return this},_createPlaceholder:function(g){g=g||this;var d,f=g.options;f.placeholder&&f.placeholder.constructor!==String||(d=f.placeholder,f.placeholder={element:function(){var e=g.currentItem[0].nodeName.toLowerCase(),h=b("<"+e+">",g.document[0]).addClass(d||g.currentItem[0].className+" ui-sortable-placeholder").removeClass("ui-sortable-helper");return"tr"===e?g.currentItem.children().each(function(){b("<td>&#160;</td>",g.document[0]).attr("colspan",b(this).attr("colspan")||1).appendTo(h)}):"img"===e&&h.attr("src",g.currentItem.attr("src")),d||h.css("visibility","hidden"),h},update:function(e,h){(!d||f.forcePlaceholderSize)&&(h.height()||h.height(g.currentItem.innerHeight()-parseInt(g.currentItem.css("paddingTop")||0,10)-parseInt(g.currentItem.css("paddingBottom")||0,10)),h.width()||h.width(g.currentItem.innerWidth()-parseInt(g.currentItem.css("paddingLeft")||0,10)-parseInt(g.currentItem.css("paddingRight")||0,10)))}}),g.placeholder=b(f.placeholder.element.call(g.element,g.currentItem)),g.currentItem.after(g.placeholder),f.placeholder.update(g,g.placeholder)},_contactContainers:function(A){var k,j,y,e,q,m,x,z,w,i,v=null,t=null;for(k=this.containers.length-1;k>=0;k--){if(!b.contains(this.currentItem[0],this.containers[k].element[0])){if(this._intersectsWith(this.containers[k].containerCache)){if(v&&b.contains(this.containers[k].element[0],v.element[0])){continue}v=this.containers[k],t=k}else{this.containers[k].containerCache.over&&(this.containers[k]._trigger("out",A,this._uiHash(this)),this.containers[k].containerCache.over=0)}}}if(v){if(1===this.containers.length){this.containers[t].containerCache.over||(this.containers[t]._trigger("over",A,this._uiHash(this)),this.containers[t].containerCache.over=1)}else{for(y=10000,e=null,i=v.floating||a(this.currentItem),q=i?"left":"top",m=i?"width":"height",x=this.positionAbs[q]+this.offset.click[q],j=this.items.length-1;j>=0;j--){b.contains(this.containers[t].element[0],this.items[j].item[0])&&this.items[j].item[0]!==this.currentItem[0]&&(!i||c(this.positionAbs.top+this.offset.click.top,this.items[j].top,this.items[j].height))&&(z=this.items[j].item.offset()[q],w=!1,Math.abs(z-x)>Math.abs(z+this.items[j][m]-x)&&(w=!0,z+=this.items[j][m]),y>Math.abs(z-x)&&(y=Math.abs(z-x),e=this.items[j],this.direction=w?"up":"down"))}if(!e&&!this.options.dropOnEmpty){return}if(this.currentContainer===this.containers[t]){return}e?this._rearrange(A,e,null,!0):this._rearrange(A,null,this.containers[t].element,!0),this._trigger("change",A,this._uiHash()),this.containers[t]._trigger("change",A,this._uiHash(this)),this.currentContainer=this.containers[t],this.options.placeholder.update(this.currentContainer,this.placeholder),this.containers[t]._trigger("over",A,this._uiHash(this)),this.containers[t].containerCache.over=1}}},_createHelper:function(g){var d=this.options,f=b.isFunction(d.helper)?b(d.helper.apply(this.element[0],[g,this.currentItem])):"clone"===d.helper?this.currentItem.clone():this.currentItem;return f.parents("body").length||b("parent"!==d.appendTo?d.appendTo:this.currentItem[0].parentNode)[0].appendChild(f[0]),f[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")}),(!f[0].style.width||d.forceHelperSize)&&f.width(this.currentItem.width()),(!f[0].style.height||d.forceHelperSize)&&f.height(this.currentItem.height()),f},_adjustOffsetFromHelper:function(d){"string"==typeof d&&(d=d.split(" ")),b.isArray(d)&&(d={left:+d[0],top:+d[1]||0}),"left" in d&&(this.offset.click.left=d.left+this.margins.left),"right" in d&&(this.offset.click.left=this.helperProportions.width-d.right+this.margins.left),"top" in d&&(this.offset.click.top=d.top+this.margins.top),"bottom" in d&&(this.offset.click.top=this.helperProportions.height-d.bottom+this.margins.top)},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var d=this.offsetParent.offset();return"absolute"===this.cssPosition&&this.scrollParent[0]!==document&&b.contains(this.scrollParent[0],this.offsetParent[0])&&(d.left+=this.scrollParent.scrollLeft(),d.top+=this.scrollParent.scrollTop()),(this.offsetParent[0]===document.body||this.offsetParent[0].tagName&&"html"===this.offsetParent[0].tagName.toLowerCase()&&b.ui.ie)&&(d={top:0,left:0}),{top:d.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:d.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if("relative"===this.cssPosition){var d=this.currentItem.position();return{top:d.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:d.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 g,d,f,h=this.options;"parent"===h.containment&&(h.containment=this.helper[0].parentNode),("document"===h.containment||"window"===h.containment)&&(this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,b("document"===h.containment?document:window).width()-this.helperProportions.width-this.margins.left,(b("document"===h.containment?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top]),/^(document|window|parent)$/.test(h.containment)||(g=b(h.containment)[0],d=b(h.containment).offset(),f="hidden"!==b(g).css("overflow"),this.containment=[d.left+(parseInt(b(g).css("borderLeftWidth"),10)||0)+(parseInt(b(g).css("paddingLeft"),10)||0)-this.margins.left,d.top+(parseInt(b(g).css("borderTopWidth"),10)||0)+(parseInt(b(g).css("paddingTop"),10)||0)-this.margins.top,d.left+(f?Math.max(g.scrollWidth,g.offsetWidth):g.offsetWidth)-(parseInt(b(g).css("borderLeftWidth"),10)||0)-(parseInt(b(g).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left,d.top+(f?Math.max(g.scrollHeight,g.offsetHeight):g.offsetHeight)-(parseInt(b(g).css("borderTopWidth"),10)||0)-(parseInt(b(g).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top])},_convertPositionTo:function(g,d){d||(d=this.position);var f="absolute"===g?1:-1,j="absolute"!==this.cssPosition||this.scrollParent[0]!==document&&b.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,h=/(html|body)/i.test(j[0].tagName);return{top:d.top+this.offset.relative.top*f+this.offset.parent.top*f-("fixed"===this.cssPosition?-this.scrollParent.scrollTop():h?0:j.scrollTop())*f,left:d.left+this.offset.relative.left*f+this.offset.parent.left*f-("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():h?0:j.scrollLeft())*f}},_generatePosition:function(l){var f,j,p=this.options,m=l.pageX,d=l.pageY,k="absolute"!==this.cssPosition||this.scrollParent[0]!==document&&b.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,g=/(html|body)/i.test(k[0].tagName);return"relative"!==this.cssPosition||this.scrollParent[0]!==document&&this.scrollParent[0]!==this.offsetParent[0]||(this.offset.relative=this._getRelativeOffset()),this.originalPosition&&(this.containment&&(l.pageX-this.offset.click.left<this.containment[0]&&(m=this.containment[0]+this.offset.click.left),l.pageY-this.offset.click.top<this.containment[1]&&(d=this.containment[1]+this.offset.click.top),l.pageX-this.offset.click.left>this.containment[2]&&(m=this.containment[2]+this.offset.click.left),l.pageY-this.offset.click.top>this.containment[3]&&(d=this.containment[3]+this.offset.click.top)),p.grid&&(f=this.originalPageY+Math.round((d-this.originalPageY)/p.grid[1])*p.grid[1],d=this.containment?f-this.offset.click.top>=this.containment[1]&&f-this.offset.click.top<=this.containment[3]?f:f-this.offset.click.top>=this.containment[1]?f-p.grid[1]:f+p.grid[1]:f,j=this.originalPageX+Math.round((m-this.originalPageX)/p.grid[0])*p.grid[0],m=this.containment?j-this.offset.click.left>=this.containment[0]&&j-this.offset.click.left<=this.containment[2]?j:j-this.offset.click.left>=this.containment[0]?j-p.grid[0]:j+p.grid[0]:j)),{top:d-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+("fixed"===this.cssPosition?-this.scrollParent.scrollTop():g?0:k.scrollTop()),left:m-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():g?0:k.scrollLeft())}},_rearrange:function(f,h,d,g){d?d[0].appendChild(this.placeholder[0]):h.item[0].parentNode.insertBefore(this.placeholder[0],"down"===this.direction?h.item[0]:h.item[0].nextSibling),this.counter=this.counter?++this.counter:1;var j=this.counter;this._delay(function(){j===this.counter&&this.refreshPositions(!g)})},_clear:function(f,h){function d(l,m,k){return function(e){k._trigger(l,e,m._uiHash(m))}}this.reverting=!1;var g,j=[];if(!this._noFinalSort&&this.currentItem.parent().length&&this.placeholder.before(this.currentItem),this._noFinalSort=null,this.helper[0]===this.currentItem[0]){for(g in this._storedCSS){("auto"===this._storedCSS[g]||"static"===this._storedCSS[g])&&(this._storedCSS[g]="")}this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper")}else{this.currentItem.show()}for(this.fromOutside&&!h&&j.push(function(e){this._trigger("receive",e,this._uiHash(this.fromOutside))}),!this.fromOutside&&this.domPosition.prev===this.currentItem.prev().not(".ui-sortable-helper")[0]&&this.domPosition.parent===this.currentItem.parent()[0]||h||j.push(function(e){this._trigger("update",e,this._uiHash())}),this!==this.currentContainer&&(h||(j.push(function(e){this._trigger("remove",e,this._uiHash())}),j.push(function(e){return function(i){e._trigger("receive",i,this._uiHash(this))}}.call(this,this.currentContainer)),j.push(function(e){return function(i){e._trigger("update",i,this._uiHash(this))}}.call(this,this.currentContainer)))),g=this.containers.length-1;g>=0;g--){h||j.push(d("deactivate",this,this.containers[g])),this.containers[g].containerCache.over&&(j.push(d("out",this,this.containers[g])),this.containers[g].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,this.cancelHelperRemoval){if(!h){for(this._trigger("beforeStop",f,this._uiHash()),g=0;j.length>g;g++){j[g].call(this,f)}this._trigger("stop",f,this._uiHash())}return this.fromOutside=!1,!1}if(h||this._trigger("beforeStop",f,this._uiHash()),this.placeholder[0].parentNode.removeChild(this.placeholder[0]),this.helper[0]!==this.currentItem[0]&&this.helper.remove(),this.helper=null,!h){for(g=0;j.length>g;g++){j[g].call(this,f)}this._trigger("stop",f,this._uiHash())}return this.fromOutside=!1,!0},_trigger:function(){b.Widget.prototype._trigger.apply(this,arguments)===!1&&this.cancel()},_uiHash:function(f){var d=f||this;return{helper:d.helper,placeholder:d.placeholder||b([]),position:d.position,originalPosition:d.originalPosition,offset:d.positionAbs,item:d.currentItem,sender:f?f.element:null}}})})(jQuery);(function(f){var d=0,c={},b={};c.height=c.paddingTop=c.paddingBottom=c.borderTopWidth=c.borderBottomWidth="hide",b.height=b.paddingTop=b.paddingBottom=b.borderTopWidth=b.borderBottomWidth="show",f.widget("ui.accordion",{version:"1.10.4",options:{active:0,animate:{},collapsible:!1,event:"click",header:"> li > :first-child,> :not(li):even",heightStyle:"auto",icons:{activeHeader:"ui-icon-triangle-1-s",header:"ui-icon-triangle-1-e"},activate:null,beforeActivate:null},_create:function(){var a=this.options;this.prevShow=this.prevHide=f(),this.element.addClass("ui-accordion ui-widget ui-helper-reset").attr("role","tablist"),a.collapsible||a.active!==!1&&null!=a.active||(a.active=0),this._processPanels(),0>a.active&&(a.active+=this.headers.length),this._refresh()},_getCreateEventData:function(){return{header:this.active,panel:this.active.length?this.active.next():f(),content:this.active.length?this.active.next():f()}},_createIcons:function(){var a=this.options.icons;a&&(f("<span>").addClass("ui-accordion-header-icon ui-icon "+a.header).prependTo(this.headers),this.active.children(".ui-accordion-header-icon").removeClass(a.header).addClass(a.activeHeader),this.headers.addClass("ui-accordion-icons"))},_destroyIcons:function(){this.headers.removeClass("ui-accordion-icons").children(".ui-accordion-header-icon").remove()},_destroy:function(){var a;this.element.removeClass("ui-accordion ui-widget ui-helper-reset").removeAttr("role"),this.headers.removeClass("ui-accordion-header ui-accordion-header-active ui-helper-reset ui-state-default ui-corner-all ui-state-active ui-state-disabled ui-corner-top").removeAttr("role").removeAttr("aria-expanded").removeAttr("aria-selected").removeAttr("aria-controls").removeAttr("tabIndex").each(function(){/^ui-accordion/.test(this.id)&&this.removeAttribute("id")}),this._destroyIcons(),a=this.headers.next().css("display","").removeAttr("role").removeAttr("aria-hidden").removeAttr("aria-labelledby").removeClass("ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content ui-accordion-content-active ui-state-disabled").each(function(){/^ui-accordion/.test(this.id)&&this.removeAttribute("id")}),"content"!==this.options.heightStyle&&a.css("height","")},_setOption:function(g,a){return"active"===g?(this._activate(a),undefined):("event"===g&&(this.options.event&&this._off(this.headers,this.options.event),this._setupEvents(a)),this._super(g,a),"collapsible"!==g||a||this.options.active!==!1||this._activate(0),"icons"===g&&(this._destroyIcons(),a&&this._createIcons()),"disabled"===g&&this.headers.add(this.headers.next()).toggleClass("ui-state-disabled",!!a),undefined)},_keydown:function(h){if(!h.altKey&&!h.ctrlKey){var g=f.ui.keyCode,e=this.headers.length,j=this.headers.index(h.target),k=!1;switch(h.keyCode){case g.RIGHT:case g.DOWN:k=this.headers[(j+1)%e];break;case g.LEFT:case g.UP:k=this.headers[(j-1+e)%e];break;case g.SPACE:case g.ENTER:this._eventHandler(h);break;case g.HOME:k=this.headers[0];break;case g.END:k=this.headers[e-1]}k&&(f(h.target).attr("tabIndex",-1),f(k).attr("tabIndex",0),k.focus(),h.preventDefault())}},_panelKeyDown:function(a){a.keyCode===f.ui.keyCode.UP&&a.ctrlKey&&f(a.currentTarget).prev().focus()},refresh:function(){var a=this.options;this._processPanels(),a.active===!1&&a.collapsible===!0||!this.headers.length?(a.active=!1,this.active=f()):a.active===!1?this._activate(0):this.active.length&&!f.contains(this.element[0],this.active[0])?this.headers.length===this.headers.find(".ui-state-disabled").length?(a.active=!1,this.active=f()):this._activate(Math.max(0,a.active-1)):a.active=this.headers.index(this.active),this._destroyIcons(),this._refresh()},_processPanels:function(){this.headers=this.element.find(this.options.header).addClass("ui-accordion-header ui-helper-reset ui-state-default ui-corner-all"),this.headers.next().addClass("ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom").filter(":not(.ui-accordion-content-active)").hide()},_refresh:function(){var g,e=this.options,h=e.heightStyle,k=this.element.parent(),j=this.accordionId="ui-accordion-"+(this.element.attr("id")||++d);this.active=this._findActive(e.active).addClass("ui-accordion-header-active ui-state-active ui-corner-top").removeClass("ui-corner-all"),this.active.next().addClass("ui-accordion-content-active").show(),this.headers.attr("role","tab").each(function(o){var m=f(this),l=m.attr("id"),p=m.next(),q=p.attr("id");l||(l=j+"-header-"+o,m.attr("id",l)),q||(q=j+"-panel-"+o,p.attr("id",q)),m.attr("aria-controls",q),p.attr("aria-labelledby",l)}).next().attr("role","tabpanel"),this.headers.not(this.active).attr({"aria-selected":"false","aria-expanded":"false",tabIndex:-1}).next().attr({"aria-hidden":"true"}).hide(),this.active.length?this.active.attr({"aria-selected":"true","aria-expanded":"true",tabIndex:0}).next().attr({"aria-hidden":"false"}):this.headers.eq(0).attr("tabIndex",0),this._createIcons(),this._setupEvents(e.event),"fill"===h?(g=k.height(),this.element.siblings(":visible").each(function(){var l=f(this),i=l.css("position");"absolute"!==i&&"fixed"!==i&&(g-=l.outerHeight(!0))}),this.headers.each(function(){g-=f(this).outerHeight(!0)}),this.headers.next().each(function(){f(this).height(Math.max(0,g-f(this).innerHeight()+f(this).height()))}).css("overflow","auto")):"auto"===h&&(g=0,this.headers.next().each(function(){g=Math.max(g,f(this).css("height","").height())}).height(g))},_activate:function(e){var a=this._findActive(e)[0];a!==this.active[0]&&(a=a||this.active[0],this._eventHandler({target:a,currentTarget:a,preventDefault:f.noop}))},_findActive:function(a){return"number"==typeof a?this.headers.eq(a):f()},_setupEvents:function(e){var a={keydown:"_keydown"};e&&f.each(e.split(" "),function(h,g){a[g]="_eventHandler"}),this._off(this.headers.add(this.headers.next())),this._on(this.headers,a),this._on(this.headers.next(),{keydown:"_panelKeyDown"}),this._hoverable(this.headers),this._focusable(this.headers)},_eventHandler:function(q){var k=this.options,p=this.active,u=f(q.currentTarget),j=u[0]===p[0],e=j&&k.collapsible,g=e?f():u.next(),l=p.next(),m={oldHeader:p,oldPanel:l,newHeader:e?f():u,newPanel:g};q.preventDefault(),j&&!k.collapsible||this._trigger("beforeActivate",q,m)===!1||(k.active=e?!1:this.headers.index(u),this.active=j?f():u,this._toggle(m),p.removeClass("ui-accordion-header-active ui-state-active"),k.icons&&p.children(".ui-accordion-header-icon").removeClass(k.icons.activeHeader).addClass(k.icons.header),j||(u.removeClass("ui-corner-all").addClass("ui-accordion-header-active ui-state-active ui-corner-top"),k.icons&&u.children(".ui-accordion-header-icon").removeClass(k.icons.header).addClass(k.icons.activeHeader),u.next().addClass("ui-accordion-content-active")))},_toggle:function(h){var g=h.newPanel,e=this.prevShow.length?this.prevShow:h.oldPanel;this.prevShow.add(this.prevHide).stop(!0,!0),this.prevShow=g,this.prevHide=e,this.options.animate?this._animate(g,e,h):(e.hide(),g.show(),this._toggleComplete(h)),e.attr({"aria-hidden":"true"}),e.prev().attr("aria-selected","false"),g.length&&e.length?e.prev().attr({tabIndex:-1,"aria-expanded":"false"}):g.length&&this.headers.filter(function(){return 0===f(this).attr("tabIndex")}).attr("tabIndex",-1),g.attr("aria-hidden","false").prev().attr({"aria-selected":"true",tabIndex:0,"aria-expanded":"true"})},_animate:function(m,y,z){var i,a,g,k=this,p=0,q=m.length&&(!y.length||m.index()<y.index()),j=this.options.animate||{},x=q&&j.down||j,w=function(){k._toggleComplete(z)};return"number"==typeof x&&(g=x),"string"==typeof x&&(a=x),a=a||x.easing||j.easing,g=g||x.duration||j.duration,y.length?m.length?(i=m.show().outerHeight(),y.animate(c,{duration:g,easing:a,step:function(l,h){h.now=Math.round(l)}}),m.hide().animate(b,{duration:g,easing:a,complete:w,step:function(l,h){h.now=Math.round(l),"height"!==h.prop?p+=h.now:"content"!==k.options.heightStyle&&(h.now=Math.round(i-y.outerHeight()-p),p=0)}}),undefined):y.animate(c,g,a,w):m.animate(b,g,a,w)},_toggleComplete:function(g){var a=g.oldPanel;a.removeClass("ui-accordion-content-active").prev().removeClass("ui-corner-top").addClass("ui-corner-all"),a.length&&(a.parent()[0].className=a.parent()[0].className),this._trigger("activate",null,g)}})})(jQuery);(function(a){a.widget("ui.autocomplete",{version:"1.10.4",defaultElement:"<input>",options:{appendTo:null,autoFocus:!1,delay:300,minLength:1,position:{my:"left top",at:"left bottom",collision:"none"},source:null,change:null,close:null,focus:null,open:null,response:null,search:null,select:null},requestIndex:0,pending:0,_create:function(){var d,c,e,g=this.element[0].nodeName.toLowerCase(),b="textarea"===g,f="input"===g;this.isMultiLine=b?!0:f?!1:this.element.prop("isContentEditable"),this.valueMethod=this.element[b||f?"val":"text"],this.isNewMenu=!0,this.element.addClass("ui-autocomplete-input").attr("autocomplete","off"),this._on(this.element,{keydown:function(i){if(this.element.prop("readOnly")){return d=!0,e=!0,c=!0,undefined}d=!1,e=!1,c=!1;var h=a.ui.keyCode;switch(i.keyCode){case h.PAGE_UP:d=!0,this._move("previousPage",i);break;case h.PAGE_DOWN:d=!0,this._move("nextPage",i);break;case h.UP:d=!0,this._keyEvent("previous",i);break;case h.DOWN:d=!0,this._keyEvent("next",i);break;case h.ENTER:case h.NUMPAD_ENTER:this.menu.active&&(d=!0,i.preventDefault(),this.menu.select(i));break;case h.TAB:this.menu.active&&this.menu.select(i);break;case h.ESCAPE:this.menu.element.is(":visible")&&(this._value(this.term),this.close(i),i.preventDefault());break;default:c=!0,this._searchTimeout(i)}},keypress:function(h){if(d){return d=!1,(!this.isMultiLine||this.menu.element.is(":visible"))&&h.preventDefault(),undefined}if(!c){var i=a.ui.keyCode;switch(h.keyCode){case i.PAGE_UP:this._move("previousPage",h);break;case i.PAGE_DOWN:this._move("nextPage",h);break;case i.UP:this._keyEvent("previous",h);break;case i.DOWN:this._keyEvent("next",h)}}},input:function(h){return e?(e=!1,h.preventDefault(),undefined):(this._searchTimeout(h),undefined)},focus:function(){this.selectedItem=null,this.previous=this._value()},blur:function(h){return this.cancelBlur?(delete this.cancelBlur,undefined):(clearTimeout(this.searching),this.close(h),this._change(h),undefined)}}),this._initSource(),this.menu=a("<ul>").addClass("ui-autocomplete ui-front").appendTo(this._appendTo()).menu({role:null}).hide().data("ui-menu"),this._on(this.menu.element,{mousedown:function(j){j.preventDefault(),this.cancelBlur=!0,this._delay(function(){delete this.cancelBlur});var h=this.menu.element[0];a(j.target).closest(".ui-menu-item").length||this._delay(function(){var i=this;this.document.one("mousedown",function(k){k.target===i.element[0]||k.target===h||a.contains(h,k.target)||i.close()})})},menufocus:function(j,h){if(this.isNewMenu&&(this.isNewMenu=!1,j.originalEvent&&/^mouse/.test(j.originalEvent.type))){return this.menu.blur(),this.document.one("mousemove",function(){a(j.target).trigger(j.originalEvent)}),undefined}var k=h.item.data("ui-autocomplete-item");!1!==this._trigger("focus",j,{item:k})?j.originalEvent&&/^key/.test(j.originalEvent.type)&&this._value(k.value):this.liveRegion.text(k.value)},menuselect:function(l,j){var h=j.item.data("ui-autocomplete-item"),k=this.previous;this.element[0]!==this.document[0].activeElement&&(this.element.focus(),this.previous=k,this._delay(function(){this.previous=k,this.selectedItem=h})),!1!==this._trigger("select",l,{item:h})&&this._value(h.value),this.term=this._value(),this.close(l),this.selectedItem=h}}),this.liveRegion=a("<span>",{role:"status","aria-live":"polite"}).addClass("ui-helper-hidden-accessible").insertBefore(this.element),this._on(this.window,{beforeunload:function(){this.element.removeAttr("autocomplete")}})},_destroy:function(){clearTimeout(this.searching),this.element.removeClass("ui-autocomplete-input").removeAttr("autocomplete"),this.menu.element.remove(),this.liveRegion.remove()},_setOption:function(c,b){this._super(c,b),"source"===c&&this._initSource(),"appendTo"===c&&this.menu.element.appendTo(this._appendTo()),"disabled"===c&&b&&this.xhr&&this.xhr.abort()},_appendTo:function(){var b=this.options.appendTo;return b&&(b=b.jquery||b.nodeType?a(b):this.document.find(b).eq(0)),b||(b=this.element.closest(".ui-front")),b.length||(b=this.document[0].body),b},_initSource:function(){var c,b,d=this;a.isArray(this.options.source)?(c=this.options.source,this.source=function(e,f){f(a.ui.autocomplete.filter(c,e.term))}):"string"==typeof this.options.source?(b=this.options.source,this.source=function(e,f){d.xhr&&d.xhr.abort(),d.xhr=a.ajax({url:b,data:e,dataType:"json",success:function(g){f(g)},error:function(){f([])}})}):this.source=this.options.source},_searchTimeout:function(b){clearTimeout(this.searching),this.searching=this._delay(function(){this.term!==this._value()&&(this.selectedItem=null,this.search(null,b))},this.options.delay)},search:function(c,b){return c=null!=c?c:this._value(),this.term=this._value(),c.length<this.options.minLength?this.close(b):this._trigger("search",b)!==!1?this._search(c):undefined},_search:function(b){this.pending++,this.element.addClass("ui-autocomplete-loading"),this.cancelSearch=!1,this.source({term:b},this._response())},_response:function(){var b=++this.requestIndex;return a.proxy(function(c){b===this.requestIndex&&this.__response(c),this.pending--,this.pending||this.element.removeClass("ui-autocomplete-loading")},this)},__response:function(b){b&&(b=this._normalize(b)),this._trigger("response",null,{content:b}),!this.options.disabled&&b&&b.length&&!this.cancelSearch?(this._suggest(b),this._trigger("open")):this._close()},close:function(b){this.cancelSearch=!0,this._close(b)},_close:function(b){this.menu.element.is(":visible")&&(this.menu.element.hide(),this.menu.blur(),this.isNewMenu=!0,this._trigger("close",b))},_change:function(b){this.previous!==this._value()&&this._trigger("change",b,{item:this.selectedItem})},_normalize:function(b){return b.length&&b[0].label&&b[0].value?b:a.map(b,function(c){return"string"==typeof c?{label:c,value:c}:a.extend({label:c.label||c.value,value:c.value||c.label},c)})},_suggest:function(c){var b=this.menu.element.empty();this._renderMenu(b,c),this.isNewMenu=!0,this.menu.refresh(),b.show(),this._resizeMenu(),b.position(a.extend({of:this.element},this.options.position)),this.options.autoFocus&&this.menu.next()},_resizeMenu:function(){var b=this.menu.element;b.outerWidth(Math.max(b.width("").outerWidth()+1,this.element.outerWidth()))},_renderMenu:function(c,b){var d=this;a.each(b,function(g,f){d._renderItemData(c,f)})},_renderItemData:function(c,b){return this._renderItem(c,b).data("ui-autocomplete-item",b)},_renderItem:function(c,b){return a("<li>").append(a("<a>").text(b.label)).appendTo(c)},_move:function(c,b){return this.menu.element.is(":visible")?this.menu.isFirstItem()&&/^previous/.test(c)||this.menu.isLastItem()&&/^next/.test(c)?(this._value(this.term),this.menu.blur(),undefined):(this.menu[c](b),undefined):(this.search(null,b),undefined)},widget:function(){return this.menu.element},_value:function(){return this.valueMethod.apply(this.element,arguments)},_keyEvent:function(c,b){(!this.isMultiLine||this.menu.element.is(":visible"))&&(this._move(c,b),b.preventDefault())}}),a.extend(a.ui.autocomplete,{escapeRegex:function(b){return b.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")},filter:function(c,b){var d=RegExp(a.ui.autocomplete.escapeRegex(b),"i");return a.grep(c,function(f){return d.test(f.label||f.value||f)})}}),a.widget("ui.autocomplete",a.ui.autocomplete,{options:{messages:{noResults:"No search results.",results:function(b){return b+(b>1?" results are":" result is")+" available, use up and down arrow keys to navigate."}}},__response:function(c){var b;this._superApply(arguments),this.options.disabled||this.cancelSearch||(b=c&&c.length?this.options.messages.results(c.length):this.options.messages.noResults,this.liveRegion.text(b))}})})(jQuery);(function(g){var d,c="ui-button ui-widget ui-state-default ui-corner-all",h="ui-button-icons-only ui-button-icon-only ui-button-text-icons ui-button-text-icon-primary ui-button-text-icon-secondary ui-button-text-only",f=function(){var a=g(this);setTimeout(function(){a.find(":ui-button").button("refresh")},1)},b=function(e){var a=e.name,k=e.form,j=g([]);return a&&(a=a.replace(/'/g,"\\'"),j=k?g(k).find("[name='"+a+"']"):g("[name='"+a+"']",e.ownerDocument).filter(function(){return !this.form})),j};g.widget("ui.button",{version:"1.10.4",defaultElement:"<button>",options:{disabled:null,text:!0,label:null,icons:{primary:null,secondary:null}},_create:function(){this.element.closest("form").unbind("reset"+this.eventNamespace).bind("reset"+this.eventNamespace,f),"boolean"!=typeof this.options.disabled?this.options.disabled=!!this.element.prop("disabled"):this.element.prop("disabled",this.options.disabled),this._determineButtonType(),this.hasTitle=!!this.buttonElement.attr("title");var j=this,i=this.options,e="checkbox"===this.type||"radio"===this.type,a=e?"":"ui-state-active";null===i.label&&(i.label="input"===this.type?this.buttonElement.val():this.buttonElement.html()),this._hoverable(this.buttonElement),this.buttonElement.addClass(c).attr("role","button").bind("mouseenter"+this.eventNamespace,function(){i.disabled||this===d&&g(this).addClass("ui-state-active")}).bind("mouseleave"+this.eventNamespace,function(){i.disabled||g(this).removeClass(a)}).bind("click"+this.eventNamespace,function(k){i.disabled&&(k.preventDefault(),k.stopImmediatePropagation())}),this._on({focus:function(){this.buttonElement.addClass("ui-state-focus")},blur:function(){this.buttonElement.removeClass("ui-state-focus")}}),e&&this.element.bind("change"+this.eventNamespace,function(){j.refresh()}),"checkbox"===this.type?this.buttonElement.bind("click"+this.eventNamespace,function(){return i.disabled?!1:undefined}):"radio"===this.type?this.buttonElement.bind("click"+this.eventNamespace,function(){if(i.disabled){return !1}g(this).addClass("ui-state-active"),j.buttonElement.attr("aria-pressed","true");var k=j.element[0];b(k).not(k).map(function(){return g(this).button("widget")[0]}).removeClass("ui-state-active").attr("aria-pressed","false")}):(this.buttonElement.bind("mousedown"+this.eventNamespace,function(){return i.disabled?!1:(g(this).addClass("ui-state-active"),d=this,j.document.one("mouseup",function(){d=null}),undefined)}).bind("mouseup"+this.eventNamespace,function(){return i.disabled?!1:(g(this).removeClass("ui-state-active"),undefined)}).bind("keydown"+this.eventNamespace,function(k){return i.disabled?!1:((k.keyCode===g.ui.keyCode.SPACE||k.keyCode===g.ui.keyCode.ENTER)&&g(this).addClass("ui-state-active"),undefined)}).bind("keyup"+this.eventNamespace+" blur"+this.eventNamespace,function(){g(this).removeClass("ui-state-active")}),this.buttonElement.is("a")&&this.buttonElement.keyup(function(k){k.keyCode===g.ui.keyCode.SPACE&&g(this).click()})),this._setOption("disabled",i.disabled),this._resetButton()},_determineButtonType:function(){var k,j,a;this.type=this.element.is("[type=checkbox]")?"checkbox":this.element.is("[type=radio]")?"radio":this.element.is("input")?"input":"button","checkbox"===this.type||"radio"===this.type?(k=this.element.parents().last(),j="label[for='"+this.element.attr("id")+"']",this.buttonElement=k.find(j),this.buttonElement.length||(k=k.length?k.siblings():this.element.siblings(),this.buttonElement=k.filter(j),this.buttonElement.length||(this.buttonElement=k.find(j))),this.element.addClass("ui-helper-hidden-accessible"),a=this.element.is(":checked"),a&&this.buttonElement.addClass("ui-state-active"),this.buttonElement.prop("aria-pressed",a)):this.buttonElement=this.element},widget:function(){return this.buttonElement},_destroy:function(){this.element.removeClass("ui-helper-hidden-accessible"),this.buttonElement.removeClass(c+" ui-state-active "+h).removeAttr("role").removeAttr("aria-pressed").html(this.buttonElement.find(".ui-button-text").html()),this.hasTitle||this.buttonElement.removeAttr("title")},_setOption:function(i,a){return this._super(i,a),"disabled"===i?(this.element.prop("disabled",!!a),a&&this.buttonElement.removeClass("ui-state-focus"),undefined):(this._resetButton(),undefined)},refresh:function(){var a=this.element.is("input, button")?this.element.is(":disabled"):this.element.hasClass("ui-button-disabled");a!==this.options.disabled&&this._setOption("disabled",a),"radio"===this.type?b(this.element[0]).each(function(){g(this).is(":checked")?g(this).button("widget").addClass("ui-state-active").attr("aria-pressed","true"):g(this).button("widget").removeClass("ui-state-active").attr("aria-pressed","false")}):"checkbox"===this.type&&(this.element.is(":checked")?this.buttonElement.addClass("ui-state-active").attr("aria-pressed","true"):this.buttonElement.removeClass("ui-state-active").attr("aria-pressed","false"))},_resetButton:function(){if("input"===this.type){return this.options.label&&this.element.val(this.options.label),undefined}var k=this.buttonElement.removeClass(h),j=g("<span></span>",this.document[0]).addClass("ui-button-text").html(this.options.label).appendTo(k.empty()).text(),l=this.options.icons,e=l.primary&&l.secondary,m=[];l.primary||l.secondary?(this.options.text&&m.push("ui-button-text-icon"+(e?"s":l.primary?"-primary":"-secondary")),l.primary&&k.prepend("<span class='ui-button-icon-primary ui-icon "+l.primary+"'></span>"),l.secondary&&k.append("<span class='ui-button-icon-secondary ui-icon "+l.secondary+"'></span>"),this.options.text||(m.push(e?"ui-button-icons-only":"ui-button-icon-only"),this.hasTitle||k.attr("title",g.trim(j)))):m.push("ui-button-text-only"),k.addClass(m.join(" "))}}),g.widget("ui.buttonset",{version:"1.10.4",options:{items:"button, input[type=button], input[type=submit], input[type=reset], input[type=checkbox], input[type=radio], a, :data(ui-button)"},_create:function(){this.element.addClass("ui-buttonset")},_init:function(){this.refresh()},_setOption:function(i,a){"disabled"===i&&this.buttons.button("option",i,a),this._super(i,a)},refresh:function(){var a="rtl"===this.element.css("direction");this.buttons=this.element.find(this.options.items).filter(":ui-button").button("refresh").end().not(":ui-button").button().end().map(function(){return g(this).button("widget")[0]}).removeClass("ui-corner-all ui-corner-left ui-corner-right").filter(":first").addClass(a?"ui-corner-right":"ui-corner-left").end().filter(":last").addClass(a?"ui-corner-left":"ui-corner-right").end().end()},_destroy:function(){this.element.removeClass("ui-buttonset"),this.buttons.map(function(){return g(this).button("widget")[0]}).removeClass("ui-corner-left ui-corner-right").end().button("destroy")}})})(jQuery);(function(h,d){function c(){this._curInst=null,this._keyEvent=!1,this._disabledInputs=[],this._datepickerShowing=!1,this._inDialog=!1,this._mainDivId="ui-datepicker-div",this._inlineClass="ui-datepicker-inline",this._appendClass="ui-datepicker-append",this._triggerClass="ui-datepicker-trigger",this._dialogClass="ui-datepicker-dialog",this._disableClass="ui-datepicker-disabled",this._unselectableClass="ui-datepicker-unselectable",this._currentClass="ui-datepicker-current-day",this._dayOverClass="ui-datepicker-days-cell-over",this.regional=[],this.regional[""]={closeText:"Done",prevText:"Prev",nextText:"Next",currentText:"Today",monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],monthNamesShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayNamesShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],dayNamesMin:["Su","Mo","Tu","We","Th","Fr","Sa"],weekHeader:"Wk",dateFormat:"mm/dd/yy",firstDay:0,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},this._defaults={showOn:"focus",showAnim:"fadeIn",showOptions:{},defaultDate:null,appendText:"",buttonText:"...",buttonImage:"",buttonImageOnly:!1,hideIfNoPrevNext:!1,navigationAsDateFormat:!1,gotoCurrent:!1,changeMonth:!1,changeYear:!1,yearRange:"c-10:c+10",showOtherMonths:!1,selectOtherMonths:!1,showWeek:!1,calculateWeek:this.iso8601Week,shortYearCutoff:"+10",minDate:null,maxDate:null,duration:"fast",beforeShowDay:null,beforeShow:null,onSelect:null,onChangeMonthYear:null,onClose:null,numberOfMonths:1,showCurrentAtPos:0,stepMonths:1,stepBigMonths:12,altField:"",altFormat:"",constrainInput:!0,showButtonPanel:!1,autoSize:!1,disabled:!1},h.extend(this._defaults,this.regional[""]),this.dpDiv=b(h("<div id='"+this._mainDivId+"' class='ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>"))}function b(e){var a="button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a";return e.delegate(a,"mouseout",function(){h(this).removeClass("ui-state-hover"),-1!==this.className.indexOf("ui-datepicker-prev")&&h(this).removeClass("ui-datepicker-prev-hover"),-1!==this.className.indexOf("ui-datepicker-next")&&h(this).removeClass("ui-datepicker-next-hover")}).delegate(a,"mouseover",function(){h.datepicker._isDisabledDatepicker(j.inline?e.parent()[0]:j.input[0])||(h(this).parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover"),h(this).addClass("ui-state-hover"),-1!==this.className.indexOf("ui-datepicker-prev")&&h(this).addClass("ui-datepicker-prev-hover"),-1!==this.className.indexOf("ui-datepicker-next")&&h(this).addClass("ui-datepicker-next-hover"))})}function f(l,k){h.extend(l,k);for(var e in k){null==k[e]&&(l[e]=k[e])}return l}h.extend(h.ui,{datepicker:{version:"1.10.4"}});var j,g="datepicker";h.extend(c.prototype,{markerClassName:"hasDatepicker",maxRows:4,_widgetDatepicker:function(){return this.dpDiv},setDefaults:function(a){return f(this._defaults,a||{}),this},_attachDatepicker:function(l,k){var e,m,o;e=l.nodeName.toLowerCase(),m="div"===e||"span"===e,l.id||(this.uuid+=1,l.id="dp"+this.uuid),o=this._newInst(h(l),m),o.settings=h.extend({},k||{}),"input"===e?this._connectDatepicker(l,o):m&&this._inlineDatepicker(l,o)},_newInst:function(e,a){var k=e[0].id.replace(/([^A-Za-z0-9_\-])/g,"\\\\$1");return{id:k,input:e,selectedDay:0,selectedMonth:0,selectedYear:0,drawMonth:0,drawYear:0,inline:a,dpDiv:a?b(h("<div class='"+this._inlineClass+" ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>")):this.dpDiv}},_connectDatepicker:function(l,k){var e=h(l);k.append=h([]),k.trigger=h([]),e.hasClass(this.markerClassName)||(this._attachments(e,k),e.addClass(this.markerClassName).keydown(this._doKeyDown).keypress(this._doKeyPress).keyup(this._doKeyUp),this._autoSize(k),h.data(l,g,k),k.settings.disabled&&this._disableDatepicker(l))},_attachments:function(l,k){var e,m,u,p=this._get(k,"appendText"),q=this._get(k,"isRTL");k.append&&k.append.remove(),p&&(k.append=h("<span class='"+this._appendClass+"'>"+p+"</span>"),l[q?"before":"after"](k.append)),l.unbind("focus",this._showDatepicker),k.trigger&&k.trigger.remove(),e=this._get(k,"showOn"),("focus"===e||"both"===e)&&l.focus(this._showDatepicker),("button"===e||"both"===e)&&(m=this._get(k,"buttonText"),u=this._get(k,"buttonImage"),k.trigger=h(this._get(k,"buttonImageOnly")?h("<img/>").addClass(this._triggerClass).attr({src:u,alt:m,title:m}):h("<button type='button'></button>").addClass(this._triggerClass).html(u?h("<img/>").attr({src:u,alt:m,title:m}):m)),l[q?"before":"after"](k.trigger),k.trigger.click(function(){return h.datepicker._datepickerShowing&&h.datepicker._lastInput===l[0]?h.datepicker._hideDatepicker():h.datepicker._datepickerShowing&&h.datepicker._lastInput!==l[0]?(h.datepicker._hideDatepicker(),h.datepicker._showDatepicker(l[0])):h.datepicker._showDatepicker(l[0]),!1}))},_autoSize:function(q){if(this._get(q,"autoSize")&&!q.inline){var m,l,k,o,u=new Date(2009,11,20),p=this._get(q,"dateFormat");p.match(/[DM]/)&&(m=function(a){for(l=0,k=0,o=0;a.length>o;o++){a[o].length>l&&(l=a[o].length,k=o)}return k},u.setMonth(m(this._get(q,p.match(/MM/)?"monthNames":"monthNamesShort"))),u.setDate(m(this._get(q,p.match(/DD/)?"dayNames":"dayNamesShort"))+20-u.getDay())),q.input.attr("size",this._formatDate(q,u).length)}},_inlineDatepicker:function(l,k){var e=h(l);e.hasClass(this.markerClassName)||(e.addClass(this.markerClassName).append(k.dpDiv),h.data(l,g,k),this._setDate(k,this._getDefaultDate(k),!0),this._updateDatepicker(k),this._updateAlternate(k),k.settings.disabled&&this._disableDatepicker(l),k.dpDiv.css("display","block"))},_dialogDatepicker:function(z,r,x,m,k){var y,w,s,q,v,e=this._dialogInst;return e||(this.uuid+=1,y="dp"+this.uuid,this._dialogInput=h("<input type='text' id='"+y+"' style='position: absolute; top: -100px; width: 0px;'/>"),this._dialogInput.keydown(this._doKeyDown),h("body").append(this._dialogInput),e=this._dialogInst=this._newInst(this._dialogInput,!1),e.settings={},h.data(this._dialogInput[0],g,e)),f(e.settings,m||{}),r=r&&r.constructor===Date?this._formatDate(e,r):r,this._dialogInput.val(r),this._pos=k?k.length?k:[k.pageX,k.pageY]:null,this._pos||(w=document.documentElement.clientWidth,s=document.documentElement.clientHeight,q=document.documentElement.scrollLeft||document.body.scrollLeft,v=document.documentElement.scrollTop||document.body.scrollTop,this._pos=[w/2-100+q,s/2-150+v]),this._dialogInput.css("left",this._pos[0]+20+"px").css("top",this._pos[1]+"px"),e.settings.onSelect=x,this._inDialog=!0,this.dpDiv.addClass(this._dialogClass),this._showDatepicker(this._dialogInput[0]),h.blockUI&&h.blockUI(this.dpDiv),h.data(this._dialogInput[0],g,e),this},_destroyDatepicker:function(l){var k,e=h(l),m=h.data(l,g);e.hasClass(this.markerClassName)&&(k=l.nodeName.toLowerCase(),h.removeData(l,g),"input"===k?(m.append.remove(),m.trigger.remove(),e.removeClass(this.markerClassName).unbind("focus",this._showDatepicker).unbind("keydown",this._doKeyDown).unbind("keypress",this._doKeyPress).unbind("keyup",this._doKeyUp)):("div"===k||"span"===k)&&e.removeClass(this.markerClassName).empty())},_enableDatepicker:function(l){var k,e,m=h(l),o=h.data(l,g);m.hasClass(this.markerClassName)&&(k=l.nodeName.toLowerCase(),"input"===k?(l.disabled=!1,o.trigger.filter("button").each(function(){this.disabled=!1}).end().filter("img").css({opacity:"1.0",cursor:""})):("div"===k||"span"===k)&&(e=m.children("."+this._inlineClass),e.children().removeClass("ui-state-disabled"),e.find("select.ui-datepicker-month, select.ui-datepicker-year").prop("disabled",!1)),this._disabledInputs=h.map(this._disabledInputs,function(a){return a===l?null:a}))},_disableDatepicker:function(l){var k,e,m=h(l),o=h.data(l,g);m.hasClass(this.markerClassName)&&(k=l.nodeName.toLowerCase(),"input"===k?(l.disabled=!0,o.trigger.filter("button").each(function(){this.disabled=!0}).end().filter("img").css({opacity:"0.5",cursor:"default"})):("div"===k||"span"===k)&&(e=m.children("."+this._inlineClass),e.children().addClass("ui-state-disabled"),e.find("select.ui-datepicker-month, select.ui-datepicker-year").prop("disabled",!0)),this._disabledInputs=h.map(this._disabledInputs,function(a){return a===l?null:a}),this._disabledInputs[this._disabledInputs.length]=l)},_isDisabledDatepicker:function(i){if(!i){return !1}for(var a=0;this._disabledInputs.length>a;a++){if(this._disabledInputs[a]===i){return !0}}return !1},_getInst:function(e){try{return h.data(e,g)}catch(a){throw"Missing instance data for this datepicker"}},_optionDatepicker:function(l,e,t){var p,q,k,s,m=this._getInst(l);return 2===arguments.length&&"string"==typeof e?"defaults"===e?h.extend({},h.datepicker._defaults):m?"all"===e?h.extend({},m.settings):this._get(m,e):null:(p=e||{},"string"==typeof e&&(p={},p[e]=t),m&&(this._curInst===m&&this._hideDatepicker(),q=this._getDateDatepicker(l,!0),k=this._getMinMaxDate(m,"min"),s=this._getMinMaxDate(m,"max"),f(m.settings,p),null!==k&&p.dateFormat!==d&&p.minDate===d&&(m.settings.minDate=this._formatDate(m,k)),null!==s&&p.dateFormat!==d&&p.maxDate===d&&(m.settings.maxDate=this._formatDate(m,s)),"disabled" in p&&(p.disabled?this._disableDatepicker(l):this._enableDatepicker(l)),this._attachments(h(l),m),this._autoSize(m),this._setDate(m,q),this._updateAlternate(m),this._updateDatepicker(m)),d)},_changeDatepicker:function(l,k,a){this._optionDatepicker(l,k,a)},_refreshDatepicker:function(i){var a=this._getInst(i);a&&this._updateDatepicker(a)},_setDateDatepicker:function(l,k){var a=this._getInst(l);a&&(this._setDate(a,k),this._updateDatepicker(a),this._updateAlternate(a))},_getDateDatepicker:function(l,k){var a=this._getInst(l);return a&&!a.inline&&this._setDateFromField(a,k),a?this._getDate(a):null},_doKeyDown:function(l){var k,e,m,u=h.datepicker._getInst(l.target),p=!0,q=u.dpDiv.is(".ui-datepicker-rtl");if(u._keyEvent=!0,h.datepicker._datepickerShowing){switch(l.keyCode){case 9:h.datepicker._hideDatepicker(),p=!1;break;case 13:return m=h("td."+h.datepicker._dayOverClass+":not(."+h.datepicker._currentClass+")",u.dpDiv),m[0]&&h.datepicker._selectDay(l.target,u.selectedMonth,u.selectedYear,m[0]),k=h.datepicker._get(u,"onSelect"),k?(e=h.datepicker._formatDate(u),k.apply(u.input?u.input[0]:null,[e,u])):h.datepicker._hideDatepicker(),!1;case 27:h.datepicker._hideDatepicker();break;case 33:h.datepicker._adjustDate(l.target,l.ctrlKey?-h.datepicker._get(u,"stepBigMonths"):-h.datepicker._get(u,"stepMonths"),"M");break;case 34:h.datepicker._adjustDate(l.target,l.ctrlKey?+h.datepicker._get(u,"stepBigMonths"):+h.datepicker._get(u,"stepMonths"),"M");break;case 35:(l.ctrlKey||l.metaKey)&&h.datepicker._clearDate(l.target),p=l.ctrlKey||l.metaKey;break;case 36:(l.ctrlKey||l.metaKey)&&h.datepicker._gotoToday(l.target),p=l.ctrlKey||l.metaKey;break;case 37:(l.ctrlKey||l.metaKey)&&h.datepicker._adjustDate(l.target,q?1:-1,"D"),p=l.ctrlKey||l.metaKey,l.originalEvent.altKey&&h.datepicker._adjustDate(l.target,l.ctrlKey?-h.datepicker._get(u,"stepBigMonths"):-h.datepicker._get(u,"stepMonths"),"M");break;case 38:(l.ctrlKey||l.metaKey)&&h.datepicker._adjustDate(l.target,-7,"D"),p=l.ctrlKey||l.metaKey;break;case 39:(l.ctrlKey||l.metaKey)&&h.datepicker._adjustDate(l.target,q?-1:1,"D"),p=l.ctrlKey||l.metaKey,l.originalEvent.altKey&&h.datepicker._adjustDate(l.target,l.ctrlKey?+h.datepicker._get(u,"stepBigMonths"):+h.datepicker._get(u,"stepMonths"),"M");break;case 40:(l.ctrlKey||l.metaKey)&&h.datepicker._adjustDate(l.target,7,"D"),p=l.ctrlKey||l.metaKey;break;default:p=!1}}else{36===l.keyCode&&l.ctrlKey?h.datepicker._showDatepicker(this):p=!1}p&&(l.preventDefault(),l.stopPropagation())},_doKeyPress:function(k){var e,l,m=h.datepicker._getInst(k.target);return h.datepicker._get(m,"constrainInput")?(e=h.datepicker._possibleChars(h.datepicker._get(m,"dateFormat")),l=String.fromCharCode(null==k.charCode?k.keyCode:k.charCode),k.ctrlKey||k.metaKey||" ">l||!e||e.indexOf(l)>-1):d},_doKeyUp:function(l){var k,e=h.datepicker._getInst(l.target);if(e.input.val()!==e.lastVal){try{k=h.datepicker.parseDate(h.datepicker._get(e,"dateFormat"),e.input?e.input.val():null,h.datepicker._getFormatConfig(e)),k&&(h.datepicker._setDateFromField(e),h.datepicker._updateAlternate(e),h.datepicker._updateDatepicker(e))}catch(m){}}return !0},_showDatepicker:function(m){if(m=m.target||m,"input"!==m.nodeName.toLowerCase()&&(m=h("input",m.parentNode)[0]),!h.datepicker._isDisabledDatepicker(m)&&h.datepicker._lastInput!==m){var l,e,v,p,q,k,s;l=h.datepicker._getInst(m),h.datepicker._curInst&&h.datepicker._curInst!==l&&(h.datepicker._curInst.dpDiv.stop(!0,!0),l&&h.datepicker._datepickerShowing&&h.datepicker._hideDatepicker(h.datepicker._curInst.input[0])),e=h.datepicker._get(l,"beforeShow"),v=e?e.apply(m,[m,l]):{},v!==!1&&(f(l.settings,v),l.lastVal=null,h.datepicker._lastInput=m,h.datepicker._setDateFromField(l),h.datepicker._inDialog&&(m.value=""),h.datepicker._pos||(h.datepicker._pos=h.datepicker._findPos(m),h.datepicker._pos[1]+=m.offsetHeight),p=!1,h(m).parents().each(function(){return p|="fixed"===h(this).css("position"),!p}),q={left:h.datepicker._pos[0],top:h.datepicker._pos[1]},h.datepicker._pos=null,l.dpDiv.empty(),l.dpDiv.css({position:"absolute",display:"block",top:"-1000px"}),h.datepicker._updateDatepicker(l),q=h.datepicker._checkOffset(l,q,p),l.dpDiv.css({position:h.datepicker._inDialog&&h.blockUI?"static":p?"fixed":"absolute",display:"none",left:q.left+"px",top:q.top+"px"}),l.inline||(k=h.datepicker._get(l,"showAnim"),s=h.datepicker._get(l,"duration"),l.dpDiv.zIndex(h(m).zIndex()+1),h.datepicker._datepickerShowing=!0,h.effects&&h.effects.effect[k]?l.dpDiv.show(k,h.datepicker._get(l,"showOptions"),s):l.dpDiv[k||"show"](k?s:null),h.datepicker._shouldFocusInput(l)&&l.input.focus(),h.datepicker._curInst=l))}},_updateDatepicker:function(l){this.maxRows=4,j=l,l.dpDiv.empty().append(this._generateHTML(l)),this._attachHandlers(l),l.dpDiv.find("."+this._dayOverClass+" a").mouseover();var k,e=this._getNumberOfMonths(l),m=e[1],n=17;l.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width(""),m>1&&l.dpDiv.addClass("ui-datepicker-multi-"+m).css("width",n*m+"em"),l.dpDiv[(1!==e[0]||1!==e[1]?"add":"remove")+"Class"]("ui-datepicker-multi"),l.dpDiv[(this._get(l,"isRTL")?"add":"remove")+"Class"]("ui-datepicker-rtl"),l===h.datepicker._curInst&&h.datepicker._datepickerShowing&&h.datepicker._shouldFocusInput(l)&&l.input.focus(),l.yearshtml&&(k=l.yearshtml,setTimeout(function(){k===l.yearshtml&&l.yearshtml&&l.dpDiv.find("select.ui-datepicker-year:first").replaceWith(l.yearshtml),k=l.yearshtml=null},0))},_shouldFocusInput:function(a){return a.input&&a.input.is(":visible")&&!a.input.is(":disabled")&&!a.input.is(":focus")},_checkOffset:function(w,m,q){var x=w.dpDiv.outerWidth(),l=w.dpDiv.outerHeight(),e=w.input?w.input.outerWidth():0,k=w.input?w.input.outerHeight():0,v=document.documentElement.clientWidth+(q?0:h(document).scrollLeft()),p=document.documentElement.clientHeight+(q?0:h(document).scrollTop());return m.left-=this._get(w,"isRTL")?x-e:0,m.left-=q&&m.left===w.input.offset().left?h(document).scrollLeft():0,m.top-=q&&m.top===w.input.offset().top+k?h(document).scrollTop():0,m.left-=Math.min(m.left,m.left+x>v&&v>x?Math.abs(m.left+x-v):0),m.top-=Math.min(m.top,m.top+l>p&&p>l?Math.abs(l+k):0),m},_findPos:function(l){for(var k,e=this._getInst(l),m=this._get(e,"isRTL");l&&("hidden"===l.type||1!==l.nodeType||h.expr.filters.hidden(l));){l=l[m?"previousSibling":"nextSibling"]}return k=h(l).offset(),[k.left,k.top]},_hideDatepicker:function(l){var k,e,m,q,p=this._curInst;!p||l&&p!==h.data(l,g)||this._datepickerShowing&&(k=this._get(p,"showAnim"),e=this._get(p,"duration"),m=function(){h.datepicker._tidyDialog(p)},h.effects&&(h.effects.effect[k]||h.effects[k])?p.dpDiv.hide(k,h.datepicker._get(p,"showOptions"),e,m):p.dpDiv["slideDown"===k?"slideUp":"fadeIn"===k?"fadeOut":"hide"](k?e:null,m),k||m(),this._datepickerShowing=!1,q=this._get(p,"onClose"),q&&q.apply(p.input?p.input[0]:null,[p.input?p.input.val():"",p]),this._lastInput=null,this._inDialog&&(this._dialogInput.css({position:"absolute",left:"0",top:"-100px"}),h.blockUI&&(h.unblockUI(),h("body").append(this.dpDiv))),this._inDialog=!1)},_tidyDialog:function(a){a.dpDiv.removeClass(this._dialogClass).unbind(".ui-datepicker-calendar")},_checkExternalClick:function(l){if(h.datepicker._curInst){var k=h(l.target),e=h.datepicker._getInst(k[0]);(k[0].id!==h.datepicker._mainDivId&&0===k.parents("#"+h.datepicker._mainDivId).length&&!k.hasClass(h.datepicker.markerClassName)&&!k.closest("."+h.datepicker._triggerClass).length&&h.datepicker._datepickerShowing&&(!h.datepicker._inDialog||!h.blockUI)||k.hasClass(h.datepicker.markerClassName)&&h.datepicker._curInst!==e)&&h.datepicker._hideDatepicker()}},_adjustDate:function(l,k,e){var m=h(l),o=this._getInst(m[0]);this._isDisabledDatepicker(m[0])||(this._adjustInstDate(o,k+("M"===e?this._get(o,"showCurrentAtPos"):0),e),this._updateDatepicker(o))},_gotoToday:function(l){var k,e=h(l),m=this._getInst(e[0]);this._get(m,"gotoCurrent")&&m.currentDay?(m.selectedDay=m.currentDay,m.drawMonth=m.selectedMonth=m.currentMonth,m.drawYear=m.selectedYear=m.currentYear):(k=new Date,m.selectedDay=k.getDate(),m.drawMonth=m.selectedMonth=k.getMonth(),m.drawYear=m.selectedYear=k.getFullYear()),this._notifyChange(m),this._adjustDate(e)},_selectMonthYear:function(l,k,e){var m=h(l),o=this._getInst(m[0]);o["selected"+("M"===e?"Month":"Year")]=o["draw"+("M"===e?"Month":"Year")]=parseInt(k.options[k.selectedIndex].value,10),this._notifyChange(o),this._adjustDate(m)},_selectDay:function(l,k,e,m){var p,o=h(l);h(m).hasClass(this._unselectableClass)||this._isDisabledDatepicker(o[0])||(p=this._getInst(o[0]),p.selectedDay=p.currentDay=h("a",m).html(),p.selectedMonth=p.currentMonth=k,p.selectedYear=p.currentYear=e,this._selectDate(l,this._formatDate(p,p.currentDay,p.currentMonth,p.currentYear)))},_clearDate:function(e){var a=h(e);this._selectDate(a,"")},_selectDate:function(l,k){var e,m=h(l),o=this._getInst(m[0]);k=null!=k?k:this._formatDate(o),o.input&&o.input.val(k),this._updateAlternate(o),e=this._get(o,"onSelect"),e?e.apply(o.input?o.input[0]:null,[k,o]):o.input&&o.input.trigger("change"),o.inline?this._updateDatepicker(o):(this._hideDatepicker(),this._lastInput=o.input[0],"object"!=typeof o.input[0]&&o.input.focus(),this._lastInput=null)},_updateAlternate:function(l){var k,e,m,o=this._get(l,"altField");o&&(k=this._get(l,"altFormat")||this._get(l,"dateFormat"),e=this._getDate(l),m=this.formatDate(k,e,this._getFormatConfig(l)),h(o).each(function(){h(this).val(m)}))},noWeekends:function(i){var a=i.getDay();return[a>0&&6>a,""]},iso8601Week:function(l){var k,a=new Date(l.getTime());return a.setDate(a.getDate()+4-(a.getDay()||7)),k=a.getTime(),a.setMonth(0),a.setDate(1),Math.floor(Math.round((k-a)/86400000)/7)+1},parseDate:function(K,S,B){if(null==K||null==S){throw"Invalid arguments"}if(S="object"==typeof S?""+S:S+"",""===S){return null}var G,C,F,z,Q=0,L=(B?B.shortYearCutoff:null)||this._defaults.shortYearCutoff,I="string"!=typeof L?L:(new Date).getFullYear()%100+parseInt(L,10),P=(B?B.dayNamesShort:null)||this._defaults.dayNamesShort,E=(B?B.dayNames:null)||this._defaults.dayNames,N=(B?B.monthNamesShort:null)||this._defaults.monthNamesShort,H=(B?B.monthNames:null)||this._defaults.monthNames,O=-1,T=-1,x=-1,J=-1,q=!1,R=function(i){var a=K.length>G+1&&K.charAt(G+1)===i;return a&&G++,a},A=function(m){var k=R(m),a="@"===m?14:"!"===m?20:"y"===m&&k?4:"o"===m?3:2,l=RegExp("^\\d{1,"+a+"}"),o=S.substring(Q).match(l);if(!o){throw"Missing number at position "+Q}return Q+=o[0].length,parseInt(o[0],10)},t=function(a,k,p){var l=-1,m=h.map(R(a)?p:k,function(n,i){return[[i,n]]}).sort(function(n,i){return -(n[1].length-i[1].length)});if(h.each(m,function(r,n){var o=n[1];return S.substr(Q,o.length).toLowerCase()===o.toLowerCase()?(l=n[0],Q+=o.length,!1):d}),-1!==l){return l+1}throw"Unknown name at position "+Q},e=function(){if(S.charAt(Q)!==K.charAt(G)){throw"Unexpected literal at position "+Q}Q++};for(G=0;K.length>G;G++){if(q){"'"!==K.charAt(G)||R("'")?e():q=!1}else{switch(K.charAt(G)){case"d":x=A("d");break;case"D":t("D",P,E);break;case"o":J=A("o");break;case"m":T=A("m");break;case"M":T=t("M",N,H);break;case"y":O=A("y");break;case"@":z=new Date(A("@")),O=z.getFullYear(),T=z.getMonth()+1,x=z.getDate();break;case"!":z=new Date((A("!")-this._ticksTo1970)/10000),O=z.getFullYear(),T=z.getMonth()+1,x=z.getDate();break;case"'":R("'")?e():q=!0;break;default:e()}}}if(S.length>Q&&(F=S.substr(Q),!/^\s+/.test(F))){throw"Extra/unparsed characters found in date: "+F}if(-1===O?O=(new Date).getFullYear():100>O&&(O+=(new Date).getFullYear()-(new Date).getFullYear()%100+(I>=O?0:-100)),J>-1){for(T=1,x=J;;){if(C=this._getDaysInMonth(O,T-1),C>=x){break}T++,x-=C}}if(z=this._daylightSavingAdjust(new Date(O,T-1,x)),z.getFullYear()!==O||z.getMonth()+1!==T||z.getDate()!==x){throw"Invalid date"}return z},ATOM:"yy-mm-dd",COOKIE:"D, dd M yy",ISO_8601:"yy-mm-dd",RFC_822:"D, d M y",RFC_850:"DD, dd-M-y",RFC_1036:"D, d M y",RFC_1123:"D, d M yy",RFC_2822:"D, d M yy",RSS:"D, d M y",TICKS:"!",TIMESTAMP:"@",W3C:"yy-mm-dd",_ticksTo1970:10000000*60*60*24*(718685+Math.floor(492.5)-Math.floor(19.7)+Math.floor(4.925)),formatDate:function(x,C,v){if(!C){return""}var A,D=(v?v.dayNamesShort:null)||this._defaults.dayNamesShort,p=(v?v.dayNames:null)||this._defaults.dayNames,k=(v?v.monthNamesShort:null)||this._defaults.monthNamesShort,m=(v?v.monthNames:null)||this._defaults.monthNames,B=function(e){var a=x.length>A+1&&x.charAt(A+1)===e;return a&&A++,a},z=function(r,o,n){var l=""+o;if(B(r)){for(;n>l.length;){l="0"+l}}return l},w=function(r,o,n,l){return B(r)?l[o]:n[o]},q="",y=!1;if(C){for(A=0;x.length>A;A++){if(y){"'"!==x.charAt(A)||B("'")?q+=x.charAt(A):y=!1}else{switch(x.charAt(A)){case"d":q+=z("d",C.getDate(),2);break;case"D":q+=w("D",C.getDay(),D,p);break;case"o":q+=z("o",Math.round((new Date(C.getFullYear(),C.getMonth(),C.getDate()).getTime()-new Date(C.getFullYear(),0,0).getTime())/86400000),3);break;case"m":q+=z("m",C.getMonth()+1,2);break;case"M":q+=w("M",C.getMonth(),k,m);break;case"y":q+=B("y")?C.getFullYear():(10>C.getYear()%100?"0":"")+C.getYear()%100;break;case"@":q+=C.getTime();break;case"!":q+=10000*C.getTime()+this._ticksTo1970;break;case"'":B("'")?q+="'":y=!0;break;default:q+=x.charAt(A)}}}}return q},_possibleChars:function(o){var m,l="",k=!1,n=function(p){var e=o.length>m+1&&o.charAt(m+1)===p;return e&&m++,e};for(m=0;o.length>m;m++){if(k){"'"!==o.charAt(m)||n("'")?l+=o.charAt(m):k=!1}else{switch(o.charAt(m)){case"d":case"m":case"y":case"@":l+="0123456789";break;case"D":case"M":return null;case"'":n("'")?l+="'":k=!0;break;default:l+=o.charAt(m)}}}return l},_get:function(k,a){return k.settings[a]!==d?k.settings[a]:this._defaults[a]},_setDateFromField:function(u,m){if(u.input.val()!==u.lastVal){var l=this._get(u,"dateFormat"),k=u.lastVal=u.input?u.input.val():null,p=this._getDefaultDate(u),w=p,q=this._getFormatConfig(u);try{w=this.parseDate(l,k,q)||p}catch(v){k=m?"":k}u.selectedDay=w.getDate(),u.drawMonth=u.selectedMonth=w.getMonth(),u.drawYear=u.selectedYear=w.getFullYear(),u.currentDay=k?w.getDate():0,u.currentMonth=k?w.getMonth():0,u.currentYear=k?w.getFullYear():0,this._adjustInstDate(u)}},_getDefaultDate:function(a){return this._restrictMinMax(a,this._determineDate(a,this._get(a,"defaultDate"),new Date))},_determineDate:function(l,k,e){var m=function(i){var a=new Date;return a.setDate(a.getDate()+i),a},p=function(v){try{return h.datepicker.parseDate(h.datepicker._get(l,"dateFormat"),v,h.datepicker._getFormatConfig(l))}catch(q){}for(var w=(v.toLowerCase().match(/^c/)?h.datepicker._getDate(l):null)||new Date,A=w.getFullYear(),x=w.getMonth(),y=w.getDate(),t=/([+\-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g,z=t.exec(v);z;){switch(z[2]||"d"){case"d":case"D":y+=parseInt(z[1],10);break;case"w":case"W":y+=7*parseInt(z[1],10);break;case"m":case"M":x+=parseInt(z[1],10),y=Math.min(y,h.datepicker._getDaysInMonth(A,x));break;case"y":case"Y":A+=parseInt(z[1],10),y=Math.min(y,h.datepicker._getDaysInMonth(A,x))}z=t.exec(v)}return new Date(A,x,y)},o=null==k||""===k?e:"string"==typeof k?p(k):"number"==typeof k?isNaN(k)?e:m(k):new Date(k.getTime());return o=o&&"Invalid Date"==""+o?e:o,o&&(o.setHours(0),o.setMinutes(0),o.setSeconds(0),o.setMilliseconds(0)),this._daylightSavingAdjust(o)},_daylightSavingAdjust:function(a){return a?(a.setHours(a.getHours()>12?a.getHours()+2:0),a):null},_setDate:function(q,m,l){var k=!m,o=q.selectedMonth,u=q.selectedYear,p=this._restrictMinMax(q,this._determineDate(q,m,new Date));q.selectedDay=q.currentDay=p.getDate(),q.drawMonth=q.selectedMonth=q.currentMonth=p.getMonth(),q.drawYear=q.selectedYear=q.currentYear=p.getFullYear(),o===q.selectedMonth&&u===q.selectedYear||l||this._notifyChange(q),this._adjustInstDate(q),q.input&&q.input.val(k?"":this._formatDate(q))},_getDate:function(i){var a=!i.currentYear||i.input&&""===i.input.val()?null:this._daylightSavingAdjust(new Date(i.currentYear,i.currentMonth,i.currentDay));return a},_attachHandlers:function(l){var k=this._get(l,"stepMonths"),e="#"+l.id.replace(/\\\\/g,"\\");l.dpDiv.find("[data-handler]").map(function(){var a={prev:function(){h.datepicker._adjustDate(e,-k,"M")},next:function(){h.datepicker._adjustDate(e,+k,"M")},hide:function(){h.datepicker._hideDatepicker()},today:function(){h.datepicker._gotoToday(e)},selectDay:function(){return h.datepicker._selectDay(e,+this.getAttribute("data-month"),+this.getAttribute("data-year"),this),!1},selectMonth:function(){return h.datepicker._selectMonthYear(e,this,"M"),!1},selectYear:function(){return h.datepicker._selectMonthYear(e,this,"Y"),!1}};h(this).bind(this.getAttribute("data-event"),a[this.getAttribute("data-handler")])})},_generateHTML:function(aY){var aI,aU,a2,aJ,aP,aK,aO,aH,a0,aV,aR,aZ,aN,aW,aQ,aX,a3,aG,aS,aD,a1,ax,aF,an,ay,aE,ar,am,ag,aA,aw,ah,ab,av,ak,al,aT,ap,ai,at=new Date,ad=this._daylightSavingAdjust(new Date(at.getFullYear(),at.getMonth(),at.getDate())),ao=this._get(aY,"isRTL"),af=this._get(aY,"showButtonPanel"),az=this._get(aY,"hideIfNoPrevNext"),aC=this._get(aY,"navigationAsDateFormat"),aL=this._getNumberOfMonths(aY),au=this._get(aY,"showCurrentAtPos"),aq=this._get(aY,"stepMonths"),aj=1!==aL[0]||1!==aL[1],ae=this._daylightSavingAdjust(aY.currentDay?new Date(aY.currentYear,aY.currentMonth,aY.currentDay):new Date(9999,9,9)),aB=this._getMinMaxDate(aY,"min"),ac=this._getMinMaxDate(aY,"max"),aa=aY.drawMonth-au,aM=aY.drawYear;if(0>aa&&(aa+=12,aM--),ac){for(aI=this._daylightSavingAdjust(new Date(ac.getFullYear(),ac.getMonth()-aL[0]*aL[1]+1,ac.getDate())),aI=aB&&aB>aI?aB:aI;this._daylightSavingAdjust(new Date(aM,aa,1))>aI;){aa--,0>aa&&(aa=11,aM--)}}for(aY.drawMonth=aa,aY.drawYear=aM,aU=this._get(aY,"prevText"),aU=aC?this.formatDate(aU,this._daylightSavingAdjust(new Date(aM,aa-aq,1)),this._getFormatConfig(aY)):aU,a2=this._canAdjustMonth(aY,-1,aM,aa)?"<a class='ui-datepicker-prev ui-corner-all' data-handler='prev' data-event='click' title='"+aU+"'><span class='ui-icon ui-icon-circle-triangle-"+(ao?"e":"w")+"'>"+aU+"</span></a>":az?"":"<a class='ui-datepicker-prev ui-corner-all ui-state-disabled' title='"+aU+"'><span class='ui-icon ui-icon-circle-triangle-"+(ao?"e":"w")+"'>"+aU+"</span></a>",aJ=this._get(aY,"nextText"),aJ=aC?this.formatDate(aJ,this._daylightSavingAdjust(new Date(aM,aa+aq,1)),this._getFormatConfig(aY)):aJ,aP=this._canAdjustMonth(aY,1,aM,aa)?"<a class='ui-datepicker-next ui-corner-all' data-handler='next' data-event='click' title='"+aJ+"'><span class='ui-icon ui-icon-circle-triangle-"+(ao?"w":"e")+"'>"+aJ+"</span></a>":az?"":"<a class='ui-datepicker-next ui-corner-all ui-state-disabled' title='"+aJ+"'><span class='ui-icon ui-icon-circle-triangle-"+(ao?"w":"e")+"'>"+aJ+"</span></a>",aK=this._get(aY,"currentText"),aO=this._get(aY,"gotoCurrent")&&aY.currentDay?ae:ad,aK=aC?this.formatDate(aK,aO,this._getFormatConfig(aY)):aK,aH=aY.inline?"":"<button type='button' class='ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all' data-handler='hide' data-event='click'>"+this._get(aY,"closeText")+"</button>",a0=af?"<div class='ui-datepicker-buttonpane ui-widget-content'>"+(ao?aH:"")+(this._isInRange(aY,aO)?"<button type='button' class='ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all' data-handler='today' data-event='click'>"+aK+"</button>":"")+(ao?"":aH)+"</div>":"",aV=parseInt(this._get(aY,"firstDay"),10),aV=isNaN(aV)?0:aV,aR=this._get(aY,"showWeek"),aZ=this._get(aY,"dayNames"),aN=this._get(aY,"dayNamesMin"),aW=this._get(aY,"monthNames"),aQ=this._get(aY,"monthNamesShort"),aX=this._get(aY,"beforeShowDay"),a3=this._get(aY,"showOtherMonths"),aG=this._get(aY,"selectOtherMonths"),aS=this._getDefaultDate(aY),aD="",ax=0;aL[0]>ax;ax++){for(aF="",this.maxRows=4,an=0;aL[1]>an;an++){if(ay=this._daylightSavingAdjust(new Date(aM,aa,aY.selectedDay)),aE=" ui-corner-all",ar="",aj){if(ar+="<div class='ui-datepicker-group",aL[1]>1){switch(an){case 0:ar+=" ui-datepicker-group-first",aE=" ui-corner-"+(ao?"right":"left");break;case aL[1]-1:ar+=" ui-datepicker-group-last",aE=" ui-corner-"+(ao?"left":"right");break;default:ar+=" ui-datepicker-group-middle",aE=""}}ar+="'>"}for(ar+="<div class='ui-datepicker-header ui-widget-header ui-helper-clearfix"+aE+"'>"+(/all|left/.test(aE)&&0===ax?ao?aP:a2:"")+(/all|right/.test(aE)&&0===ax?ao?a2:aP:"")+this._generateMonthYearHeader(aY,aa,aM,aB,ac,ax>0||an>0,aW,aQ)+"</div><table class='ui-datepicker-calendar'><thead><tr>",am=aR?"<th class='ui-datepicker-week-col'>"+this._get(aY,"weekHeader")+"</th>":"",a1=0;7>a1;a1++){ag=(a1+aV)%7,am+="<th"+((a1+aV+6)%7>=5?" class='ui-datepicker-week-end'":"")+"><span title='"+aZ[ag]+"'>"+aN[ag]+"</span></th>"}for(ar+=am+"</tr></thead><tbody>",aA=this._getDaysInMonth(aM,aa),aM===aY.selectedYear&&aa===aY.selectedMonth&&(aY.selectedDay=Math.min(aY.selectedDay,aA)),aw=(this._getFirstDayOfMonth(aM,aa)-aV+7)%7,ah=Math.ceil((aw+aA)/7),ab=aj?this.maxRows>ah?this.maxRows:ah:ah,this.maxRows=ab,av=this._daylightSavingAdjust(new Date(aM,aa,1-aw)),ak=0;ab>ak;ak++){for(ar+="<tr>",al=aR?"<td class='ui-datepicker-week-col'>"+this._get(aY,"calculateWeek")(av)+"</td>":"",a1=0;7>a1;a1++){aT=aX?aX.apply(aY.input?aY.input[0]:null,[av]):[!0,""],ap=av.getMonth()!==aa,ai=ap&&!aG||!aT[0]||aB&&aB>av||ac&&av>ac,al+="<td class='"+((a1+aV+6)%7>=5?" ui-datepicker-week-end":"")+(ap?" ui-datepicker-other-month":"")+(av.getTime()===ay.getTime()&&aa===aY.selectedMonth&&aY._keyEvent||aS.getTime()===av.getTime()&&aS.getTime()===ay.getTime()?" "+this._dayOverClass:"")+(ai?" "+this._unselectableClass+" ui-state-disabled":"")+(ap&&!a3?"":" "+aT[1]+(av.getTime()===ae.getTime()?" "+this._currentClass:"")+(av.getTime()===ad.getTime()?" ui-datepicker-today":""))+"'"+(ap&&!a3||!aT[2]?"":" title='"+aT[2].replace(/'/g,"&#39;")+"'")+(ai?"":" data-handler='selectDay' data-event='click' data-month='"+av.getMonth()+"' data-year='"+av.getFullYear()+"'")+">"+(ap&&!a3?"&#xa0;":ai?"<span class='ui-state-default'>"+av.getDate()+"</span>":"<a class='ui-state-default"+(av.getTime()===ad.getTime()?" ui-state-highlight":"")+(av.getTime()===ae.getTime()?" ui-state-active":"")+(ap?" ui-priority-secondary":"")+"' href='#'>"+av.getDate()+"</a>")+"</td>",av.setDate(av.getDate()+1),av=this._daylightSavingAdjust(av)}ar+=al+"</tr>"}aa++,aa>11&&(aa=0,aM++),ar+="</tbody></table>"+(aj?"</div>"+(aL[0]>0&&an===aL[1]-1?"<div class='ui-datepicker-row-break'></div>":""):""),aF+=ar}aD+=aF}return aD+=a0,aY._keyEvent=!1,aD},_generateMonthYearHeader:function(M,z,I,P,A,E,B,D){var x,O,J,G,N,C,K,F,L=this._get(M,"changeMonth"),Q=this._get(M,"changeYear"),w=this._get(M,"showMonthAfterYear"),H="<div class='ui-datepicker-title'>",q="";if(E||!L){q+="<span class='ui-datepicker-month'>"+B[z]+"</span>"}else{for(x=P&&P.getFullYear()===I,O=A&&A.getFullYear()===I,q+="<select class='ui-datepicker-month' data-handler='selectMonth' data-event='change'>",J=0;12>J;J++){(!x||J>=P.getMonth())&&(!O||A.getMonth()>=J)&&(q+="<option value='"+J+"'"+(J===z?" selected='selected'":"")+">"+D[J]+"</option>")}q+="</select>"}if(w||(H+=q+(!E&&L&&Q?"":"&#xa0;")),!M.yearshtml){if(M.yearshtml="",E||!Q){H+="<span class='ui-datepicker-year'>"+I+"</span>"}else{for(G=this._get(M,"yearRange").split(":"),N=(new Date).getFullYear(),C=function(i){var a=i.match(/c[+\-].*/)?I+parseInt(i.substring(1),10):i.match(/[+\-].*/)?N+parseInt(i,10):parseInt(i,10);return isNaN(a)?N:a},K=C(G[0]),F=Math.max(K,C(G[1]||"")),K=P?Math.max(K,P.getFullYear()):K,F=A?Math.min(F,A.getFullYear()):F,M.yearshtml+="<select class='ui-datepicker-year' data-handler='selectYear' data-event='change'>";F>=K;K++){M.yearshtml+="<option value='"+K+"'"+(K===I?" selected='selected'":"")+">"+K+"</option>"}M.yearshtml+="</select>",H+=M.yearshtml,M.yearshtml=null}}return H+=this._get(M,"yearSuffix"),w&&(H+=(!E&&L&&Q?"":"&#xa0;")+q),H+="</div>"},_adjustInstDate:function(q,m,l){var k=q.drawYear+("Y"===l?m:0),o=q.drawMonth+("M"===l?m:0),u=Math.min(q.selectedDay,this._getDaysInMonth(k,o))+("D"===l?m:0),p=this._restrictMinMax(q,this._daylightSavingAdjust(new Date(k,o,u)));q.selectedDay=p.getDate(),q.drawMonth=q.selectedMonth=p.getMonth(),q.drawYear=q.selectedYear=p.getFullYear(),("M"===l||"Y"===l)&&this._notifyChange(q)},_restrictMinMax:function(o,m){var l=this._getMinMaxDate(o,"min"),k=this._getMinMaxDate(o,"max"),n=l&&l>m?l:m;return k&&n>k?k:n},_notifyChange:function(i){var a=this._get(i,"onChangeMonthYear");a&&a.apply(i.input?i.input[0]:null,[i.selectedYear,i.selectedMonth+1,i])},_getNumberOfMonths:function(i){var a=this._get(i,"numberOfMonths");return null==a?[1,1]:"number"==typeof a?[1,a]:a},_getMinMaxDate:function(i,a){return this._determineDate(i,this._get(i,a+"Date"),null)},_getDaysInMonth:function(i,a){return 32-this._daylightSavingAdjust(new Date(i,a,32)).getDate()},_getFirstDayOfMonth:function(i,a){return new Date(i,a,1).getDay()},_canAdjustMonth:function(p,m,l,k){var o=this._getNumberOfMonths(p),q=this._daylightSavingAdjust(new Date(l,k+(0>m?m:o[0]*o[1]),1));return 0>m&&q.setDate(this._getDaysInMonth(q.getFullYear(),q.getMonth())),this._isInRange(p,q)},_isInRange:function(q,x){var p,v,y=this._getMinMaxDate(q,"min"),m=this._getMinMaxDate(q,"max"),k=null,l=null,w=this._get(q,"yearRange");return w&&(p=w.split(":"),v=(new Date).getFullYear(),k=parseInt(p[0],10),l=parseInt(p[1],10),p[0].match(/[+\-].*/)&&(k+=v),p[1].match(/[+\-].*/)&&(l+=v)),(!y||x.getTime()>=y.getTime())&&(!m||x.getTime()<=m.getTime())&&(!k||x.getFullYear()>=k)&&(!l||l>=x.getFullYear())},_getFormatConfig:function(i){var a=this._get(i,"shortYearCutoff");return a="string"!=typeof a?a:(new Date).getFullYear()%100+parseInt(a,10),{shortYearCutoff:a,dayNamesShort:this._get(i,"dayNamesShort"),dayNames:this._get(i,"dayNames"),monthNamesShort:this._get(i,"monthNamesShort"),monthNames:this._get(i,"monthNames")}},_formatDate:function(o,m,l,k){m||(o.currentDay=o.selectedDay,o.currentMonth=o.selectedMonth,o.currentYear=o.selectedYear);var n=m?"object"==typeof m?m:this._daylightSavingAdjust(new Date(k,l,m)):this._daylightSavingAdjust(new Date(o.currentYear,o.currentMonth,o.currentDay));return this.formatDate(this._get(o,"dateFormat"),n,this._getFormatConfig(o))}}),h.fn.datepicker=function(e){if(!this.length){return this}h.datepicker.initialized||(h(document).mousedown(h.datepicker._checkExternalClick),h.datepicker.initialized=!0),0===h("#"+h.datepicker._mainDivId).length&&h("body").append(h.datepicker.dpDiv);var a=Array.prototype.slice.call(arguments,1);return"string"!=typeof e||"isDisabled"!==e&&"getDate"!==e&&"widget"!==e?"option"===e&&2===arguments.length&&"string"==typeof arguments[1]?h.datepicker["_"+e+"Datepicker"].apply(h.datepicker,[this[0]].concat(a)):this.each(function(){"string"==typeof e?h.datepicker["_"+e+"Datepicker"].apply(h.datepicker,[this].concat(a)):h.datepicker._attachDatepicker(this,e)}):h.datepicker["_"+e+"Datepicker"].apply(h.datepicker,[this[0]].concat(a))},h.datepicker=new c,h.datepicker.initialized=!1,h.datepicker.uuid=(new Date).getTime(),h.datepicker.version="1.10.4"})(jQuery);(function(c){var b={buttons:!0,height:!0,maxHeight:!0,maxWidth:!0,minHeight:!0,minWidth:!0,width:!0},a={maxHeight:!0,maxWidth:!0,minHeight:!0,minWidth:!0};c.widget("ui.dialog",{version:"1.10.4",options:{appendTo:"body",autoOpen:!0,buttons:[],closeOnEscape:!0,closeText:"close",dialogClass:"",draggable:!0,hide:null,height:"auto",maxHeight:null,maxWidth:null,minHeight:150,minWidth:150,modal:!1,position:{my:"center",at:"center",of:window,collision:"fit",using:function(e){var d=c(this).css(e).offset().top;0>d&&c(this).css("top",e.top-d)}},resizable:!0,show:null,title:null,width:300,beforeClose:null,close:null,drag:null,dragStart:null,dragStop:null,focus:null,open:null,resize:null,resizeStart:null,resizeStop:null},_create:function(){this.originalCss={display:this.element[0].style.display,width:this.element[0].style.width,minHeight:this.element[0].style.minHeight,maxHeight:this.element[0].style.maxHeight,height:this.element[0].style.height},this.originalPosition={parent:this.element.parent(),index:this.element.parent().children().index(this.element)},this.originalTitle=this.element.attr("title"),this.options.title=this.options.title||this.originalTitle,this._createWrapper(),this.element.show().removeAttr("title").addClass("ui-dialog-content ui-widget-content").appendTo(this.uiDialog),this._createTitlebar(),this._createButtonPane(),this.options.draggable&&c.fn.draggable&&this._makeDraggable(),this.options.resizable&&c.fn.resizable&&this._makeResizable(),this._isOpen=!1},_init:function(){this.options.autoOpen&&this.open()},_appendTo:function(){var d=this.options.appendTo;return d&&(d.jquery||d.nodeType)?c(d):this.document.find(d||"body").eq(0)},_destroy:function(){var f,d=this.originalPosition;this._destroyOverlay(),this.element.removeUniqueId().removeClass("ui-dialog-content ui-widget-content").css(this.originalCss).detach(),this.uiDialog.stop(!0,!0).remove(),this.originalTitle&&this.element.attr("title",this.originalTitle),f=d.parent.children().eq(d.index),f.length&&f[0]!==this.element[0]?f.before(this.element):d.parent.append(this.element)},widget:function(){return this.uiDialog},disable:c.noop,enable:c.noop,close:function(f){var e,d=this;if(this._isOpen&&this._trigger("beforeClose",f)!==!1){if(this._isOpen=!1,this._destroyOverlay(),!this.opener.filter(":focusable").focus().length){try{e=this.document[0].activeElement,e&&"body"!==e.nodeName.toLowerCase()&&c(e).blur()}catch(g){}}this._hide(this.uiDialog,this.options.hide,function(){d._trigger("close",f)})}},isOpen:function(){return this._isOpen},moveToTop:function(){this._moveToTop()},_moveToTop:function(g,f){var d=!!this.uiDialog.nextAll(":visible").insertBefore(this.uiDialog).length;return d&&!f&&this._trigger("focus",g),d},open:function(){var d=this;return this._isOpen?(this._moveToTop()&&this._focusTabbable(),undefined):(this._isOpen=!0,this.opener=c(this.document[0].activeElement),this._size(),this._position(),this._createOverlay(),this._moveToTop(null,!0),this._show(this.uiDialog,this.options.show,function(){d._focusTabbable(),d._trigger("focus")}),this._trigger("open"),undefined)},_focusTabbable:function(){var d=this.element.find("[autofocus]");d.length||(d=this.element.find(":tabbable")),d.length||(d=this.uiDialogButtonPane.find(":tabbable")),d.length||(d=this.uiDialogTitlebarClose.filter(":tabbable")),d.length||(d=this.uiDialog),d.eq(0).focus()},_keepFocus:function(e){function d(){var g=this.document[0].activeElement,f=this.uiDialog[0]===g||c.contains(this.uiDialog[0],g);f||this._focusTabbable()}e.preventDefault(),d.call(this),this._delay(d)},_createWrapper:function(){this.uiDialog=c("<div>").addClass("ui-dialog ui-widget ui-widget-content ui-corner-all ui-front "+this.options.dialogClass).hide().attr({tabIndex:-1,role:"dialog"}).appendTo(this._appendTo()),this._on(this.uiDialog,{keydown:function(f){if(this.options.closeOnEscape&&!f.isDefaultPrevented()&&f.keyCode&&f.keyCode===c.ui.keyCode.ESCAPE){return f.preventDefault(),this.close(f),undefined}if(f.keyCode===c.ui.keyCode.TAB){var e=this.uiDialog.find(":tabbable"),d=e.filter(":first"),g=e.filter(":last");f.target!==g[0]&&f.target!==this.uiDialog[0]||f.shiftKey?f.target!==d[0]&&f.target!==this.uiDialog[0]||!f.shiftKey||(g.focus(1),f.preventDefault()):(d.focus(1),f.preventDefault())}},mousedown:function(d){this._moveToTop(d)&&this._focusTabbable()}}),this.element.find("[aria-describedby]").length||this.uiDialog.attr({"aria-describedby":this.element.uniqueId().attr("id")})},_createTitlebar:function(){var d;this.uiDialogTitlebar=c("<div>").addClass("ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix").prependTo(this.uiDialog),this._on(this.uiDialogTitlebar,{mousedown:function(e){c(e.target).closest(".ui-dialog-titlebar-close")||this.uiDialog.focus()}}),this.uiDialogTitlebarClose=c("<button type='button'></button>").button({label:this.options.closeText,icons:{primary:"ui-icon-closethick"},text:!1}).addClass("ui-dialog-titlebar-close").appendTo(this.uiDialogTitlebar),this._on(this.uiDialogTitlebarClose,{click:function(f){f.preventDefault(),this.close(f)}}),d=c("<span>").uniqueId().addClass("ui-dialog-title").prependTo(this.uiDialogTitlebar),this._title(d),this.uiDialog.attr({"aria-labelledby":d.attr("id")})},_title:function(d){this.options.title||d.html("&#160;"),d.text(this.options.title)},_createButtonPane:function(){this.uiDialogButtonPane=c("<div>").addClass("ui-dialog-buttonpane ui-widget-content ui-helper-clearfix"),this.uiButtonSet=c("<div>").addClass("ui-dialog-buttonset").appendTo(this.uiDialogButtonPane),this._createButtons()},_createButtons:function(){var e=this,d=this.options.buttons;return this.uiDialogButtonPane.remove(),this.uiButtonSet.empty(),c.isEmptyObject(d)||c.isArray(d)&&!d.length?(this.uiDialog.removeClass("ui-dialog-buttons"),undefined):(c.each(d,function(g,f){var h,j;f=c.isFunction(f)?{click:f,text:g}:f,f=c.extend({type:"button"},f),h=f.click,f.click=function(){h.apply(e.element[0],arguments)},j={icons:f.icons,text:f.showText},delete f.icons,delete f.showText,c("<button></button>",f).button(j).appendTo(e.uiButtonSet)}),this.uiDialog.addClass("ui-dialog-buttons"),this.uiDialogButtonPane.appendTo(this.uiDialog),undefined)},_makeDraggable:function(){function f(g){return{position:g.position,offset:g.offset}}var e=this,d=this.options;this.uiDialog.draggable({cancel:".ui-dialog-content, .ui-dialog-titlebar-close",handle:".ui-dialog-titlebar",containment:"document",start:function(g,h){c(this).addClass("ui-dialog-dragging"),e._blockFrames(),e._trigger("dragStart",g,f(h))},drag:function(h,g){e._trigger("drag",h,f(g))},stop:function(g,h){d.position=[h.position.left-e.document.scrollLeft(),h.position.top-e.document.scrollTop()],c(this).removeClass("ui-dialog-dragging"),e._unblockFrames(),e._trigger("dragStop",g,f(h))}})},_makeResizable:function(){function f(i){return{originalPosition:i.originalPosition,originalSize:i.originalSize,position:i.position,size:i.size}}var e=this,d=this.options,g=d.resizable,j=this.uiDialog.css("position"),h="string"==typeof g?g:"n,e,s,w,se,sw,ne,nw";this.uiDialog.resizable({cancel:".ui-dialog-content",containment:"document",alsoResize:this.element,maxWidth:d.maxWidth,maxHeight:d.maxHeight,minWidth:d.minWidth,minHeight:this._minHeight(),handles:h,start:function(i,k){c(this).addClass("ui-dialog-resizing"),e._blockFrames(),e._trigger("resizeStart",i,f(k))},resize:function(k,i){e._trigger("resize",k,f(i))},stop:function(i,k){d.height=c(this).height(),d.width=c(this).width(),c(this).removeClass("ui-dialog-resizing"),e._unblockFrames(),e._trigger("resizeStop",i,f(k))}}).css("position",j)},_minHeight:function(){var d=this.options;return"auto"===d.height?d.minHeight:Math.min(d.minHeight,d.height)},_position:function(){var d=this.uiDialog.is(":visible");d||this.uiDialog.show(),this.uiDialog.position(this.options.position),d||this.uiDialog.hide()},_setOptions:function(d){var e=this,g=!1,f={};c.each(d,function(i,h){e._setOption(i,h),i in b&&(g=!0),i in a&&(f[i]=h)}),g&&(this._size(),this._position()),this.uiDialog.is(":data(ui-resizable)")&&this.uiDialog.resizable("option",f)},_setOption:function(j,g){var f,d,h=this.uiDialog;"dialogClass"===j&&h.removeClass(this.options.dialogClass).addClass(g),"disabled"!==j&&(this._super(j,g),"appendTo"===j&&this.uiDialog.appendTo(this._appendTo()),"buttons"===j&&this._createButtons(),"closeText"===j&&this.uiDialogTitlebarClose.button({label:""+g}),"draggable"===j&&(f=h.is(":data(ui-draggable)"),f&&!g&&h.draggable("destroy"),!f&&g&&this._makeDraggable()),"position"===j&&this._position(),"resizable"===j&&(d=h.is(":data(ui-resizable)"),d&&!g&&h.resizable("destroy"),d&&"string"==typeof g&&h.resizable("option","handles",g),d||g===!1||this._makeResizable()),"title"===j&&this._title(this.uiDialogTitlebar.find(".ui-dialog-title")))},_size:function(){var h,g,f,d=this.options;this.element.show().css({width:"auto",minHeight:0,maxHeight:"none",height:0}),d.minWidth>d.width&&(d.width=d.minWidth),h=this.uiDialog.css({height:"auto",width:d.width}).outerHeight(),g=Math.max(0,d.minHeight-h),f="number"==typeof d.maxHeight?Math.max(0,d.maxHeight-h):"none","auto"===d.height?this.element.css({minHeight:g,maxHeight:f,height:"auto"}):this.element.height(Math.max(0,d.height-h)),this.uiDialog.is(":data(ui-resizable)")&&this.uiDialog.resizable("option","minHeight",this._minHeight())},_blockFrames:function(){this.iframeBlocks=this.document.find("iframe").map(function(){var d=c(this);return c("<div>").css({position:"absolute",width:d.outerWidth(),height:d.outerHeight()}).appendTo(d.parent()).offset(d.offset())[0]})},_unblockFrames:function(){this.iframeBlocks&&(this.iframeBlocks.remove(),delete this.iframeBlocks)},_allowInteraction:function(d){return c(d.target).closest(".ui-dialog").length?!0:!!c(d.target).closest(".ui-datepicker").length},_createOverlay:function(){if(this.options.modal){var e=this,d=this.widgetFullName;c.ui.dialog.overlayInstances||this._delay(function(){c.ui.dialog.overlayInstances&&this.document.bind("focusin.dialog",function(f){e._allowInteraction(f)||(f.preventDefault(),c(".ui-dialog:visible:last .ui-dialog-content").data(d)._focusTabbable())})}),this.overlay=c("<div>").addClass("ui-widget-overlay ui-front").appendTo(this._appendTo()),this._on(this.overlay,{mousedown:"_keepFocus"}),c.ui.dialog.overlayInstances++}},_destroyOverlay:function(){this.options.modal&&this.overlay&&(c.ui.dialog.overlayInstances--,c.ui.dialog.overlayInstances||this.document.unbind("focusin.dialog"),this.overlay.remove(),this.overlay=null)}}),c.ui.dialog.overlayInstances=0,c.uiBackCompat!==!1&&c.widget("ui.dialog",c.ui.dialog,{_position:function(){var f,e=this.options.position,d=[],g=[0,0];e?(("string"==typeof e||"object"==typeof e&&"0" in e)&&(d=e.split?e.split(" "):[e[0],e[1]],1===d.length&&(d[1]=d[0]),c.each(["left","top"],function(i,h){+d[i]===d[i]&&(g[i]=d[i],d[i]=h)}),e={my:d[0]+(0>g[0]?g[0]:"+"+g[0])+" "+d[1]+(0>g[1]?g[1]:"+"+g[1]),at:d.join(" ")}),e=c.extend({},c.ui.dialog.prototype.options.position,e)):e=c.ui.dialog.prototype.options.position,f=this.uiDialog.is(":visible"),f||this.uiDialog.show(),this.uiDialog.position(e),f||this.uiDialog.hide()}})})(jQuery);(function(a){a.widget("ui.menu",{version:"1.10.4",defaultElement:"<ul>",delay:300,options:{icons:{submenu:"ui-icon-carat-1-e"},menus:"ul",position:{my:"left top",at:"right top"},role:"menu",blur:null,focus:null,select:null},_create:function(){this.activeMenu=this.element,this.mouseHandled=!1,this.element.uniqueId().addClass("ui-menu ui-widget ui-widget-content ui-corner-all").toggleClass("ui-menu-icons",!!this.element.find(".ui-icon").length).attr({role:this.options.role,tabIndex:0}).bind("click"+this.eventNamespace,a.proxy(function(b){this.options.disabled&&b.preventDefault()},this)),this.options.disabled&&this.element.addClass("ui-state-disabled").attr("aria-disabled","true"),this._on({"mousedown .ui-menu-item > a":function(b){b.preventDefault()},"click .ui-state-disabled > a":function(b){b.preventDefault()},"click .ui-menu-item:has(a)":function(c){var b=a(c.target).closest(".ui-menu-item");!this.mouseHandled&&b.not(".ui-state-disabled").length&&(this.select(c),c.isPropagationStopped()||(this.mouseHandled=!0),b.has(".ui-menu").length?this.expand(c):!this.element.is(":focus")&&a(this.document[0].activeElement).closest(".ui-menu").length&&(this.element.trigger("focus",[!0]),this.active&&1===this.active.parents(".ui-menu").length&&clearTimeout(this.timer)))},"mouseenter .ui-menu-item":function(c){var b=a(c.currentTarget);b.siblings().children(".ui-state-active").removeClass("ui-state-active"),this.focus(c,b)},mouseleave:"collapseAll","mouseleave .ui-menu":"collapseAll",focus:function(c,d){var b=this.active||this.element.children(".ui-menu-item").eq(0);d||this.focus(c,b)},blur:function(b){this._delay(function(){a.contains(this.element[0],this.document[0].activeElement)||this.collapseAll(b)})},keydown:"_keydown"}),this.refresh(),this._on(this.document,{click:function(b){a(b.target).closest(".ui-menu").length||this.collapseAll(b),this.mouseHandled=!1}})},_destroy:function(){this.element.removeAttr("aria-activedescendant").find(".ui-menu").addBack().removeClass("ui-menu ui-widget ui-widget-content ui-corner-all ui-menu-icons").removeAttr("role").removeAttr("tabIndex").removeAttr("aria-labelledby").removeAttr("aria-expanded").removeAttr("aria-hidden").removeAttr("aria-disabled").removeUniqueId().show(),this.element.find(".ui-menu-item").removeClass("ui-menu-item").removeAttr("role").removeAttr("aria-disabled").children("a").removeUniqueId().removeClass("ui-corner-all ui-state-hover").removeAttr("tabIndex").removeAttr("role").removeAttr("aria-haspopup").children().each(function(){var b=a(this);b.data("ui-menu-submenu-carat")&&b.remove()}),this.element.find(".ui-menu-divider").removeClass("ui-menu-divider ui-widget-content")},_keydown:function(h){function d(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}var f,k,c,j,g,b=!0;switch(h.keyCode){case a.ui.keyCode.PAGE_UP:this.previousPage(h);break;case a.ui.keyCode.PAGE_DOWN:this.nextPage(h);break;case a.ui.keyCode.HOME:this._move("first","first",h);break;case a.ui.keyCode.END:this._move("last","last",h);break;case a.ui.keyCode.UP:this.previous(h);break;case a.ui.keyCode.DOWN:this.next(h);break;case a.ui.keyCode.LEFT:this.collapse(h);break;case a.ui.keyCode.RIGHT:this.active&&!this.active.is(".ui-state-disabled")&&this.expand(h);break;case a.ui.keyCode.ENTER:case a.ui.keyCode.SPACE:this._activate(h);break;case a.ui.keyCode.ESCAPE:this.collapse(h);break;default:b=!1,k=this.previousFilter||"",c=String.fromCharCode(h.keyCode),j=!1,clearTimeout(this.filterTimer),c===k?j=!0:c=k+c,g=RegExp("^"+d(c),"i"),f=this.activeMenu.children(".ui-menu-item").filter(function(){return g.test(a(this).children("a").text())}),f=j&&-1!==f.index(this.active.next())?this.active.nextAll(".ui-menu-item"):f,f.length||(c=String.fromCharCode(h.keyCode),g=RegExp("^"+d(c),"i"),f=this.activeMenu.children(".ui-menu-item").filter(function(){return g.test(a(this).children("a").text())})),f.length?(this.focus(h,f),f.length>1?(this.previousFilter=c,this.filterTimer=this._delay(function(){delete this.previousFilter},1000)):delete this.previousFilter):delete this.previousFilter}b&&h.preventDefault()},_activate:function(b){this.active.is(".ui-state-disabled")||(this.active.children("a[aria-haspopup='true']").length?this.expand(b):this.select(b))},refresh:function(){var d,b=this.options.icons.submenu,c=this.element.find(this.options.menus);this.element.toggleClass("ui-menu-icons",!!this.element.find(".ui-icon").length),c.filter(":not(.ui-menu)").addClass("ui-menu ui-widget ui-widget-content ui-corner-all").hide().attr({role:this.options.role,"aria-hidden":"true","aria-expanded":"false"}).each(function(){var g=a(this),f=g.prev("a"),h=a("<span>").addClass("ui-menu-icon ui-icon "+b).data("ui-menu-submenu-carat",!0);f.attr("aria-haspopup","true").prepend(h),g.attr("aria-labelledby",f.attr("id"))}),d=c.add(this.element),d.children(":not(.ui-menu-item):has(a)").addClass("ui-menu-item").attr("role","presentation").children("a").uniqueId().addClass("ui-corner-all").attr({tabIndex:-1,role:this._itemRole()}),d.children(":not(.ui-menu-item)").each(function(){var f=a(this);/[^\-\u2014\u2013\s]/.test(f.text())||f.addClass("ui-widget-content ui-menu-divider")}),d.children(".ui-state-disabled").attr("aria-disabled","true"),this.active&&!a.contains(this.element[0],this.active[0])&&this.blur()},_itemRole:function(){return{menu:"menuitem",listbox:"option"}[this.options.role]},_setOption:function(b,c){"icons"===b&&this.element.find(".ui-menu-icon").removeClass(this.options.icons.submenu).addClass(c.submenu),this._super(b,c)},focus:function(c,f){var b,d;this.blur(c,c&&"focus"===c.type),this._scrollIntoView(f),this.active=f.first(),d=this.active.children("a").addClass("ui-state-focus"),this.options.role&&this.element.attr("aria-activedescendant",d.attr("id")),this.active.parent().closest(".ui-menu-item").children("a:first").addClass("ui-state-active"),c&&"keydown"===c.type?this._close():this.timer=this._delay(function(){this._close()},this.delay),b=f.children(".ui-menu"),b.length&&c&&/^mouse/.test(c.type)&&this._startOpening(b),this.activeMenu=f.parent(),this._trigger("focus",c,{item:f})},_scrollIntoView:function(g){var c,d,j,b,h,f;this._hasScroll()&&(c=parseFloat(a.css(this.activeMenu[0],"borderTopWidth"))||0,d=parseFloat(a.css(this.activeMenu[0],"paddingTop"))||0,j=g.offset().top-this.activeMenu.offset().top-c-d,b=this.activeMenu.scrollTop(),h=this.activeMenu.height(),f=g.height(),0>j?this.activeMenu.scrollTop(b+j):j+f>h&&this.activeMenu.scrollTop(b+j-h+f))},blur:function(b,c){c||clearTimeout(this.timer),this.active&&(this.active.children("a").removeClass("ui-state-focus"),this.active=null,this._trigger("blur",b,{item:this.active}))},_startOpening:function(b){clearTimeout(this.timer),"true"===b.attr("aria-hidden")&&(this.timer=this._delay(function(){this._close(),this._open(b)},this.delay))},_open:function(c){var b=a.extend({of:this.active},this.options.position);clearTimeout(this.timer),this.element.find(".ui-menu").not(c.parents(".ui-menu")).hide().attr("aria-hidden","true"),c.show().removeAttr("aria-hidden").attr("aria-expanded","true").position(b)},collapseAll:function(c,b){clearTimeout(this.timer),this.timer=this._delay(function(){var d=b?this.element:a(c&&c.target).closest(this.element.find(".ui-menu"));d.length||(d=this.element),this._close(d),this.blur(c),this.activeMenu=d},this.delay)},_close:function(b){b||(b=this.active?this.active.parent():this.element),b.find(".ui-menu").hide().attr("aria-hidden","true").attr("aria-expanded","false").end().find("a.ui-state-active").removeClass("ui-state-active")},collapse:function(b){var c=this.active&&this.active.parent().closest(".ui-menu-item",this.element);c&&c.length&&(this._close(),this.focus(b,c))},expand:function(b){var c=this.active&&this.active.children(".ui-menu ").children(".ui-menu-item").first();c&&c.length&&(this._open(c.parent()),this._delay(function(){this.focus(b,c)}))},next:function(b){this._move("next","first",b)},previous:function(b){this._move("prev","last",b)},isFirstItem:function(){return this.active&&!this.active.prevAll(".ui-menu-item").length},isLastItem:function(){return this.active&&!this.active.nextAll(".ui-menu-item").length},_move:function(c,f,b){var d;this.active&&(d="first"===c||"last"===c?this.active["first"===c?"prevAll":"nextAll"](".ui-menu-item").eq(-1):this.active[c+"All"](".ui-menu-item").eq(0)),d&&d.length&&this.active||(d=this.activeMenu.children(".ui-menu-item")[f]()),this.focus(b,d)},nextPage:function(d){var b,c,f;return this.active?(this.isLastItem()||(this._hasScroll()?(c=this.active.offset().top,f=this.element.height(),this.active.nextAll(".ui-menu-item").each(function(){return b=a(this),0>b.offset().top-c-f}),this.focus(d,b)):this.focus(d,this.activeMenu.children(".ui-menu-item")[this.active?"last":"first"]())),undefined):(this.next(d),undefined)},previousPage:function(d){var b,c,f;return this.active?(this.isFirstItem()||(this._hasScroll()?(c=this.active.offset().top,f=this.element.height(),this.active.prevAll(".ui-menu-item").each(function(){return b=a(this),b.offset().top-c+f>0}),this.focus(d,b)):this.focus(d,this.activeMenu.children(".ui-menu-item").first())),undefined):(this.next(d),undefined)},_hasScroll:function(){return this.element.outerHeight()<this.element.prop("scrollHeight")},select:function(c){this.active=this.active||a(c.target).closest(".ui-menu-item");var b={item:this.active};this.active.has(".ui-menu").length||this.collapseAll(c,!0),this._trigger("select",c,b)}})})(jQuery);(function(a,b){a.widget("ui.progressbar",{version:"1.10.4",options:{max:100,value:0,change:null,complete:null},min:0,_create:function(){this.oldValue=this.options.value=this._constrainedValue(),this.element.addClass("ui-progressbar ui-widget ui-widget-content ui-corner-all").attr({role:"progressbar","aria-valuemin":this.min}),this.valueDiv=a("<div class='ui-progressbar-value ui-widget-header ui-corner-left'></div>").appendTo(this.element),this._refreshValue()},_destroy:function(){this.element.removeClass("ui-progressbar ui-widget ui-widget-content ui-corner-all").removeAttr("role").removeAttr("aria-valuemin").removeAttr("aria-valuemax").removeAttr("aria-valuenow"),this.valueDiv.remove()},value:function(c){return c===b?this.options.value:(this.options.value=this._constrainedValue(c),this._refreshValue(),b)},_constrainedValue:function(c){return c===b&&(c=this.options.value),this.indeterminate=c===!1,"number"!=typeof c&&(c=0),this.indeterminate?!1:Math.min(this.options.max,Math.max(this.min,c))},_setOptions:function(c){var d=c.value;delete c.value,this._super(c),this.options.value=this._constrainedValue(d),this._refreshValue()},_setOption:function(c,d){"max"===c&&(d=Math.max(this.min,d)),this._super(c,d)},_percentage:function(){return this.indeterminate?100:100*(this.options.value-this.min)/(this.options.max-this.min)},_refreshValue:function(){var d=this.options.value,c=this._percentage();this.valueDiv.toggle(this.indeterminate||d>this.min).toggleClass("ui-corner-right",d===this.options.max).width(c.toFixed(0)+"%"),this.element.toggleClass("ui-progressbar-indeterminate",this.indeterminate),this.indeterminate?(this.element.removeAttr("aria-valuenow"),this.overlayDiv||(this.overlayDiv=a("<div class='ui-progressbar-overlay'></div>").appendTo(this.valueDiv))):(this.element.attr({"aria-valuemax":this.options.max,"aria-valuenow":d}),this.overlayDiv&&(this.overlayDiv.remove(),this.overlayDiv=null)),this.oldValue!==d&&(this.oldValue=d,this._trigger("change")),d===this.options.max&&this._trigger("complete")}})})(jQuery);(function(a){var b=5;a.widget("ui.slider",a.ui.mouse,{version:"1.10.4",widgetEventPrefix:"slide",options:{animate:!1,distance:0,max:100,min:0,orientation:"horizontal",range:!1,step:1,value:0,values:null,change:null,slide:null,start:null,stop:null},_create:function(){this._keySliding=!1,this._mouseSliding=!1,this._animateOff=!0,this._handleIndex=null,this._detectOrientation(),this._mouseInit(),this.element.addClass("ui-slider ui-slider-"+this.orientation+" ui-widget ui-widget-content ui-corner-all"),this._refresh(),this._setOption("disabled",this.options.disabled),this._animateOff=!1},_refresh:function(){this._createRange(),this._createHandles(),this._setupEvents(),this._refreshValue()},_createHandles:function(){var g,d,f=this.options,j=this.element.find(".ui-slider-handle").addClass("ui-state-default ui-corner-all"),c="<a class='ui-slider-handle ui-state-default ui-corner-all' href='#'></a>",h=[];for(d=f.values&&f.values.length||1,j.length>d&&(j.slice(d).remove(),j=j.slice(0,d)),g=j.length;d>g;g++){h.push(c)}this.handles=j.add(a(h.join("")).appendTo(this.element)),this.handle=this.handles.eq(0),this.handles.each(function(i){a(this).data("ui-slider-handle-index",i)})},_createRange:function(){var d=this.options,c="";d.range?(d.range===!0&&(d.values?d.values.length&&2!==d.values.length?d.values=[d.values[0],d.values[0]]:a.isArray(d.values)&&(d.values=d.values.slice(0)):d.values=[this._valueMin(),this._valueMin()]),this.range&&this.range.length?this.range.removeClass("ui-slider-range-min ui-slider-range-max").css({left:"",bottom:""}):(this.range=a("<div></div>").appendTo(this.element),c="ui-slider-range ui-widget-header ui-corner-all"),this.range.addClass(c+("min"===d.range||"max"===d.range?" ui-slider-range-"+d.range:""))):(this.range&&this.range.remove(),this.range=null)},_setupEvents:function(){var c=this.handles.add(this.range).filter("a");this._off(c),this._on(c,this._handleEvents),this._hoverable(c),this._focusable(c)},_destroy:function(){this.handles.remove(),this.range&&this.range.remove(),this.element.removeClass("ui-slider ui-slider-horizontal ui-slider-vertical ui-widget ui-widget-content ui-corner-all"),this._mouseDestroy()},_mouseCapture:function(p){var k,w,g,t,f,d,j,m,v=this,q=this.options;return q.disabled?!1:(this.elementSize={width:this.element.outerWidth(),height:this.element.outerHeight()},this.elementOffset=this.element.offset(),k={x:p.pageX,y:p.pageY},w=this._normValueFromMouse(k),g=this._valueMax()-this._valueMin()+1,this.handles.each(function(h){var c=Math.abs(w-v.values(h));(g>c||g===c&&(h===v._lastChangedValue||v.values(h)===q.min))&&(g=c,t=a(this),f=h)}),d=this._start(p,f),d===!1?!1:(this._mouseSliding=!0,this._handleIndex=f,t.addClass("ui-state-active").focus(),j=t.offset(),m=!a(p.target).parents().addBack().is(".ui-slider-handle"),this._clickOffset=m?{left:0,top:0}:{left:p.pageX-j.left-t.width()/2,top:p.pageY-j.top-t.height()/2-(parseInt(t.css("borderTopWidth"),10)||0)-(parseInt(t.css("borderBottomWidth"),10)||0)+(parseInt(t.css("marginTop"),10)||0)},this.handles.hasClass("ui-state-hover")||this._slide(p,f,w),this._animateOff=!0,!0))},_mouseStart:function(){return !0},_mouseDrag:function(d){var f={x:d.pageX,y:d.pageY},c=this._normValueFromMouse(f);return this._slide(d,this._handleIndex,c),!1},_mouseStop:function(c){return this.handles.removeClass("ui-state-active"),this._mouseSliding=!1,this._stop(c,this._handleIndex),this._change(c,this._handleIndex),this._handleIndex=null,this._clickOffset=null,this._animateOff=!1,!1},_detectOrientation:function(){this.orientation="vertical"===this.options.orientation?"vertical":"horizontal"},_normValueFromMouse:function(f){var h,d,g,j,c;return"horizontal"===this.orientation?(h=this.elementSize.width,d=f.x-this.elementOffset.left-(this._clickOffset?this._clickOffset.left:0)):(h=this.elementSize.height,d=f.y-this.elementOffset.top-(this._clickOffset?this._clickOffset.top:0)),g=d/h,g>1&&(g=1),0>g&&(g=0),"vertical"===this.orientation&&(g=1-g),j=this._valueMax()-this._valueMin(),c=this._valueMin()+g*j,this._trimAlignValue(c)},_start:function(d,f){var c={handle:this.handles[f],value:this.value()};return this.options.values&&this.options.values.length&&(c.value=this.values(f),c.values=this.values()),this._trigger("start",d,c)},_slide:function(f,h,d){var g,j,c;this.options.values&&this.options.values.length?(g=this.values(h?0:1),2===this.options.values.length&&this.options.range===!0&&(0===h&&d>g||1===h&&g>d)&&(d=g),d!==this.values(h)&&(j=this.values(),j[h]=d,c=this._trigger("slide",f,{handle:this.handles[h],value:d,values:j}),g=this.values(h?0:1),c!==!1&&this.values(h,d))):d!==this.value()&&(c=this._trigger("slide",f,{handle:this.handles[h],value:d}),c!==!1&&this.value(d))},_stop:function(d,f){var c={handle:this.handles[f],value:this.value()};this.options.values&&this.options.values.length&&(c.value=this.values(f),c.values=this.values()),this._trigger("stop",d,c)},_change:function(d,f){if(!this._keySliding&&!this._mouseSliding){var c={handle:this.handles[f],value:this.value()};this.options.values&&this.options.values.length&&(c.value=this.values(f),c.values=this.values()),this._lastChangedValue=f,this._trigger("change",d,c)}},value:function(c){return arguments.length?(this.options.value=this._trimAlignValue(c),this._refreshValue(),this._change(null,0),undefined):this._value()},values:function(g,d){var f,h,c;if(arguments.length>1){return this.options.values[g]=this._trimAlignValue(d),this._refreshValue(),this._change(null,g),undefined}if(!arguments.length){return this._values()}if(!a.isArray(arguments[0])){return this.options.values&&this.options.values.length?this._values(g):this.value()}for(f=this.options.values,h=arguments[0],c=0;f.length>c;c+=1){f[c]=this._trimAlignValue(h[c]),this._change(null,c)}this._refreshValue()},_setOption:function(f,c){var d,g=0;switch("range"===f&&this.options.range===!0&&("min"===c?(this.options.value=this._values(0),this.options.values=null):"max"===c&&(this.options.value=this._values(this.options.values.length-1),this.options.values=null)),a.isArray(this.options.values)&&(g=this.options.values.length),a.Widget.prototype._setOption.apply(this,arguments),f){case"orientation":this._detectOrientation(),this.element.removeClass("ui-slider-horizontal ui-slider-vertical").addClass("ui-slider-"+this.orientation),this._refreshValue();break;case"value":this._animateOff=!0,this._refreshValue(),this._change(null,0),this._animateOff=!1;break;case"values":for(this._animateOff=!0,this._refreshValue(),d=0;g>d;d+=1){this._change(null,d)}this._animateOff=!1;break;case"min":case"max":this._animateOff=!0,this._refreshValue(),this._animateOff=!1;break;case"range":this._animateOff=!0,this._refresh(),this._animateOff=!1}},_value:function(){var c=this.options.value;return c=this._trimAlignValue(c)},_values:function(d){var g,c,f;if(arguments.length){return g=this.options.values[d],g=this._trimAlignValue(g)}if(this.options.values&&this.options.values.length){for(c=this.options.values.slice(),f=0;c.length>f;f+=1){c[f]=this._trimAlignValue(c[f])}return c}return[]},_trimAlignValue:function(d){if(this._valueMin()>=d){return this._valueMin()}if(d>=this._valueMax()){return this._valueMax()}var g=this.options.step>0?this.options.step:1,c=(d-this._valueMin())%g,f=d-c;return 2*Math.abs(c)>=g&&(f+=c>0?g:-g),parseFloat(f.toFixed(5))},_valueMin:function(){return this.options.min},_valueMax:function(){return this.options.max},_refreshValue:function(){var m,j,t,f,p,d=this.options.range,c=this.options,g=this,k=this._animateOff?!1:c.animate,q={};this.options.values&&this.options.values.length?this.handles.each(function(e){j=100*((g.values(e)-g._valueMin())/(g._valueMax()-g._valueMin())),q["horizontal"===g.orientation?"left":"bottom"]=j+"%",a(this).stop(1,1)[k?"animate":"css"](q,c.animate),g.options.range===!0&&("horizontal"===g.orientation?(0===e&&g.range.stop(1,1)[k?"animate":"css"]({left:j+"%"},c.animate),1===e&&g.range[k?"animate":"css"]({width:j-m+"%"},{queue:!1,duration:c.animate})):(0===e&&g.range.stop(1,1)[k?"animate":"css"]({bottom:j+"%"},c.animate),1===e&&g.range[k?"animate":"css"]({height:j-m+"%"},{queue:!1,duration:c.animate}))),m=j}):(t=this.value(),f=this._valueMin(),p=this._valueMax(),j=p!==f?100*((t-f)/(p-f)):0,q["horizontal"===this.orientation?"left":"bottom"]=j+"%",this.handle.stop(1,1)[k?"animate":"css"](q,c.animate),"min"===d&&"horizontal"===this.orientation&&this.range.stop(1,1)[k?"animate":"css"]({width:j+"%"},c.animate),"max"===d&&"horizontal"===this.orientation&&this.range[k?"animate":"css"]({width:100-j+"%"},{queue:!1,duration:c.animate}),"min"===d&&"vertical"===this.orientation&&this.range.stop(1,1)[k?"animate":"css"]({height:j+"%"},c.animate),"max"===d&&"vertical"===this.orientation&&this.range[k?"animate":"css"]({height:100-j+"%"},{queue:!1,duration:c.animate}))},_handleEvents:{keydown:function(d){var e,h,c,g,f=a(d.target).data("ui-slider-handle-index");switch(d.keyCode){case a.ui.keyCode.HOME:case a.ui.keyCode.END:case a.ui.keyCode.PAGE_UP:case a.ui.keyCode.PAGE_DOWN:case a.ui.keyCode.UP:case a.ui.keyCode.RIGHT:case a.ui.keyCode.DOWN:case a.ui.keyCode.LEFT:if(d.preventDefault(),!this._keySliding&&(this._keySliding=!0,a(d.target).addClass("ui-state-active"),e=this._start(d,f),e===!1)){return}}switch(g=this.options.step,h=c=this.options.values&&this.options.values.length?this.values(f):this.value(),d.keyCode){case a.ui.keyCode.HOME:c=this._valueMin();break;case a.ui.keyCode.END:c=this._valueMax();break;case a.ui.keyCode.PAGE_UP:c=this._trimAlignValue(h+(this._valueMax()-this._valueMin())/b);break;case a.ui.keyCode.PAGE_DOWN:c=this._trimAlignValue(h-(this._valueMax()-this._valueMin())/b);break;case a.ui.keyCode.UP:case a.ui.keyCode.RIGHT:if(h===this._valueMax()){return}c=this._trimAlignValue(h+g);break;case a.ui.keyCode.DOWN:case a.ui.keyCode.LEFT:if(h===this._valueMin()){return}c=this._trimAlignValue(h-g)}this._slide(d,f,c)},click:function(c){c.preventDefault()},keyup:function(d){var c=a(d.target).data("ui-slider-handle-index");this._keySliding&&(this._keySliding=!1,this._stop(d,c),this._change(d,c),a(d.target).removeClass("ui-state-active"))}}})})(jQuery);(function(a){function b(c){return function(){var d=this.element.val();c.apply(this,arguments),this._refresh(),d!==this.element.val()&&this._trigger("change")}}a.widget("ui.spinner",{version:"1.10.4",defaultElement:"<input>",widgetEventPrefix:"spin",options:{culture:null,icons:{down:"ui-icon-triangle-1-s",up:"ui-icon-triangle-1-n"},incremental:!0,max:null,min:null,numberFormat:null,page:10,step:1,change:null,spin:null,start:null,stop:null},_create:function(){this._setOption("max",this.options.max),this._setOption("min",this.options.min),this._setOption("step",this.options.step),""!==this.value()&&this._value(this.element.val(),!0),this._draw(),this._on(this._events),this._refresh(),this._on(this.window,{beforeunload:function(){this.element.removeAttr("autocomplete")}})},_getCreateOptions:function(){var d={},c=this.element;return a.each(["min","max","step"],function(e,f){var g=c.attr(f);void 0!==g&&g.length&&(d[f]=g)}),d},_events:{keydown:function(c){this._start(c)&&this._keydown(c)&&c.preventDefault()},keyup:"_stop",focus:function(){this.previous=this.element.val()},blur:function(c){return this.cancelBlur?(delete this.cancelBlur,void 0):(this._stop(),this._refresh(),this.previous!==this.element.val()&&this._trigger("change",c),void 0)},mousewheel:function(c,d){if(d){if(!this.spinning&&!this._start(c)){return !1}this._spin((d>0?1:-1)*this.options.step,c),clearTimeout(this.mousewheelTimer),this.mousewheelTimer=this._delay(function(){this.spinning&&this._stop(c)},100),c.preventDefault()}},"mousedown .ui-spinner-button":function(f){function c(){var e=this.element[0]===this.document[0].activeElement;e||(this.element.focus(),this.previous=d,this._delay(function(){this.previous=d}))}var d;d=this.element[0]===this.document[0].activeElement?this.previous:this.element.val(),f.preventDefault(),c.call(this),this.cancelBlur=!0,this._delay(function(){delete this.cancelBlur,c.call(this)}),this._start(f)!==!1&&this._repeat(null,a(f.currentTarget).hasClass("ui-spinner-up")?1:-1,f)},"mouseup .ui-spinner-button":"_stop","mouseenter .ui-spinner-button":function(c){return a(c.currentTarget).hasClass("ui-state-active")?this._start(c)===!1?!1:(this._repeat(null,a(c.currentTarget).hasClass("ui-spinner-up")?1:-1,c),void 0):void 0},"mouseleave .ui-spinner-button":"_stop"},_draw:function(){var c=this.uiSpinner=this.element.addClass("ui-spinner-input").attr("autocomplete","off").wrap(this._uiSpinnerHtml()).parent().append(this._buttonHtml());this.element.attr("role","spinbutton"),this.buttons=c.find(".ui-spinner-button").attr("tabIndex",-1).button().removeClass("ui-corner-all"),this.buttons.height()>Math.ceil(0.5*c.height())&&c.height()>0&&c.height(c.height()),this.options.disabled&&this.disable()},_keydown:function(f){var c=this.options,d=a.ui.keyCode;switch(f.keyCode){case d.UP:return this._repeat(null,1,f),!0;case d.DOWN:return this._repeat(null,-1,f),!0;case d.PAGE_UP:return this._repeat(null,c.page,f),!0;case d.PAGE_DOWN:return this._repeat(null,-c.page,f),!0}return !1},_uiSpinnerHtml:function(){return"<span class='ui-spinner ui-widget ui-widget-content ui-corner-all'></span>"},_buttonHtml:function(){return"<a class='ui-spinner-button ui-spinner-up ui-corner-tr'><span class='ui-icon "+this.options.icons.up+"'>&#9650;</span></a><a class='ui-spinner-button ui-spinner-down ui-corner-br'><span class='ui-icon "+this.options.icons.down+"'>&#9660;</span></a>"},_start:function(c){return this.spinning||this._trigger("start",c)!==!1?(this.counter||(this.counter=1),this.spinning=!0,!0):!1},_repeat:function(d,f,c){d=d||500,clearTimeout(this.timer),this.timer=this._delay(function(){this._repeat(40,f,c)},d),this._spin(f*this.options.step,c)},_spin:function(d,f){var c=this.value()||0;this.counter||(this.counter=1),c=this._adjustValue(c+d*this._increment(this.counter)),this.spinning&&this._trigger("spin",f,{value:c})===!1||(this._value(c),this.counter++)},_increment:function(d){var c=this.options.incremental;return c?a.isFunction(c)?c(d):Math.floor(d*d*d/50000-d*d/500+17*d/200+1):1},_precision:function(){var c=this._precisionOf(this.options.step);return null!==this.options.min&&(c=Math.max(c,this._precisionOf(this.options.min))),c},_precisionOf:function(d){var f=""+d,c=f.indexOf(".");return -1===c?0:f.length-c-1},_adjustValue:function(d){var g,c,f=this.options;return g=null!==f.min?f.min:0,c=d-g,c=Math.round(c/f.step)*f.step,d=g+c,d=parseFloat(d.toFixed(this._precision())),null!==f.max&&d>f.max?f.max:null!==f.min&&f.min>d?f.min:d},_stop:function(c){this.spinning&&(clearTimeout(this.timer),clearTimeout(this.mousewheelTimer),this.counter=0,this.spinning=!1,this._trigger("stop",c))},_setOption:function(d,f){if("culture"===d||"numberFormat"===d){var c=this._parse(this.element.val());return this.options[d]=f,this.element.val(this._format(c)),void 0}("max"===d||"min"===d||"step"===d)&&"string"==typeof f&&(f=this._parse(f)),"icons"===d&&(this.buttons.first().find(".ui-icon").removeClass(this.options.icons.up).addClass(f.up),this.buttons.last().find(".ui-icon").removeClass(this.options.icons.down).addClass(f.down)),this._super(d,f),"disabled"===d&&(f?(this.element.prop("disabled",!0),this.buttons.button("disable")):(this.element.prop("disabled",!1),this.buttons.button("enable")))},_setOptions:b(function(c){this._super(c),this._value(this.element.val())}),_parse:function(c){return"string"==typeof c&&""!==c&&(c=window.Globalize&&this.options.numberFormat?Globalize.parseFloat(c,10,this.options.culture):+c),""===c||isNaN(c)?null:c},_format:function(c){return""===c?"":window.Globalize&&this.options.numberFormat?Globalize.format(c,this.options.numberFormat,this.options.culture):c},_refresh:function(){this.element.attr({"aria-valuemin":this.options.min,"aria-valuemax":this.options.max,"aria-valuenow":this._parse(this.element.val())})},_value:function(d,f){var c;""!==d&&(c=this._parse(d),null!==c&&(f||(c=this._adjustValue(c)),d=this._format(c))),this.element.val(d),this._refresh()},_destroy:function(){this.element.removeClass("ui-spinner-input").prop("disabled",!1).removeAttr("autocomplete").removeAttr("role").removeAttr("aria-valuemin").removeAttr("aria-valuemax").removeAttr("aria-valuenow"),this.uiSpinner.replaceWith(this.element)},stepUp:b(function(c){this._stepUp(c)}),_stepUp:function(c){this._start()&&(this._spin((c||1)*this.options.step),this._stop())},stepDown:b(function(c){this._stepDown(c)}),_stepDown:function(c){this._start()&&(this._spin((c||1)*-this.options.step),this._stop())},pageUp:b(function(c){this._stepUp((c||1)*this.options.page)}),pageDown:b(function(c){this._stepDown((c||1)*this.options.page)}),value:function(c){return arguments.length?(b(this._value).call(this,c),void 0):this._parse(this.element.val())},widget:function(){return this.uiSpinner}})})(jQuery);(function(d,g){function c(){return ++h}function f(a){return a=a.cloneNode(!1),a.hash.length>1&&decodeURIComponent(a.href.replace(b,""))===decodeURIComponent(location.href.replace(b,""))}var h=0,b=/#.*$/;d.widget("ui.tabs",{version:"1.10.4",delay:300,options:{active:null,collapsible:!1,event:"click",heightStyle:"content",hide:null,show:null,activate:null,beforeActivate:null,beforeLoad:null,load:null},_create:function(){var j=this,a=this.options;this.running=!1,this.element.addClass("ui-tabs ui-widget ui-widget-content ui-corner-all").toggleClass("ui-tabs-collapsible",a.collapsible).delegate(".ui-tabs-nav > li","mousedown"+this.eventNamespace,function(i){d(this).is(".ui-state-disabled")&&i.preventDefault()}).delegate(".ui-tabs-anchor","focus"+this.eventNamespace,function(){d(this).closest("li").is(".ui-state-disabled")&&this.blur()}),this._processTabs(),a.active=this._initialActive(),d.isArray(a.disabled)&&(a.disabled=d.unique(a.disabled.concat(d.map(this.tabs.filter(".ui-state-disabled"),function(e){return j.tabs.index(e)}))).sort()),this.active=this.options.active!==!1&&this.anchors.length?this._findActive(a.active):d(),this._refresh(),this.active.length&&this.load(a.active)},_initialActive:function(){var a=this.options.active,e=this.options.collapsible,j=location.hash.substring(1);return null===a&&(j&&this.tabs.each(function(k,i){return d(i).attr("aria-controls")===j?(a=k,!1):g}),null===a&&(a=this.tabs.index(this.tabs.filter(".ui-tabs-active"))),(null===a||-1===a)&&(a=this.tabs.length?0:!1)),a!==!1&&(a=this.tabs.index(this.tabs.eq(a)),-1===a&&(a=e?!1:0)),!e&&a===!1&&this.anchors.length&&(a=0),a},_getCreateEventData:function(){return{tab:this.active,panel:this.active.length?this._getPanelForTab(this.active):d()}},_tabKeydown:function(j){var k=d(this.document[0].activeElement).closest("li"),l=this.tabs.index(k),e=!0;if(!this._handlePageNav(j)){switch(j.keyCode){case d.ui.keyCode.RIGHT:case d.ui.keyCode.DOWN:l++;break;case d.ui.keyCode.UP:case d.ui.keyCode.LEFT:e=!1,l--;break;case d.ui.keyCode.END:l=this.anchors.length-1;break;case d.ui.keyCode.HOME:l=0;break;case d.ui.keyCode.SPACE:return j.preventDefault(),clearTimeout(this.activating),this._activate(l),g;case d.ui.keyCode.ENTER:return j.preventDefault(),clearTimeout(this.activating),this._activate(l===this.options.active?!1:l),g;default:return}j.preventDefault(),clearTimeout(this.activating),l=this._focusNextTab(l,e),j.ctrlKey||(k.attr("aria-selected","false"),this.tabs.eq(l).attr("aria-selected","true"),this.activating=this._delay(function(){this.option("active",l)},this.delay))}},_panelKeydown:function(a){this._handlePageNav(a)||a.ctrlKey&&a.keyCode===d.ui.keyCode.UP&&(a.preventDefault(),this.active.focus())},_handlePageNav:function(a){return a.altKey&&a.keyCode===d.ui.keyCode.PAGE_UP?(this._activate(this._focusNextTab(this.options.active-1,!1)),!0):a.altKey&&a.keyCode===d.ui.keyCode.PAGE_DOWN?(this._activate(this._focusNextTab(this.options.active+1,!0)),!0):g},_findNextTab:function(k,a){function j(){return k>l&&(k=0),0>k&&(k=l),k}for(var l=this.tabs.length-1;-1!==d.inArray(j(),this.options.disabled);){k=a?k+1:k-1}return k},_focusNextTab:function(a,i){return a=this._findNextTab(a,i),this.tabs.eq(a).focus(),a},_setOption:function(e,a){return"active"===e?(this._activate(a),g):"disabled"===e?(this._setupDisabled(a),g):(this._super(e,a),"collapsible"===e&&(this.element.toggleClass("ui-tabs-collapsible",a),a||this.options.active!==!1||this._activate(0)),"event"===e&&this._setupEvents(a),"heightStyle"===e&&this._setupHeightStyle(a),g)},_tabId:function(a){return a.attr("aria-controls")||"ui-tabs-"+c()},_sanitizeSelector:function(a){return a?a.replace(/[!"$%&'()*+,.\/:;<=>?@\[\]\^`{|}~]/g,"\\$&"):""},refresh:function(){var j=this.options,a=this.tablist.children(":has(a[href])");j.disabled=d.map(a.filter(".ui-state-disabled"),function(e){return a.index(e)}),this._processTabs(),j.active!==!1&&this.anchors.length?this.active.length&&!d.contains(this.tablist[0],this.active[0])?this.tabs.length===j.disabled.length?(j.active=!1,this.active=d()):this._activate(this._findNextTab(Math.max(0,j.active-1),!1)):j.active=this.tabs.index(this.active):(j.active=!1,this.active=d()),this._refresh()},_refresh:function(){this._setupDisabled(this.options.disabled),this._setupEvents(this.options.event),this._setupHeightStyle(this.options.heightStyle),this.tabs.not(this.active).attr({"aria-selected":"false",tabIndex:-1}),this.panels.not(this._getPanelForTab(this.active)).hide().attr({"aria-expanded":"false","aria-hidden":"true"}),this.active.length?(this.active.addClass("ui-tabs-active ui-state-active").attr({"aria-selected":"true",tabIndex:0}),this._getPanelForTab(this.active).show().attr({"aria-expanded":"true","aria-hidden":"false"})):this.tabs.eq(0).attr("tabIndex",0)},_processTabs:function(){var a=this;this.tablist=this._getList().addClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all").attr("role","tablist"),this.tabs=this.tablist.find("> li:has(a[href])").addClass("ui-state-default ui-corner-top").attr({role:"tab",tabIndex:-1}),this.anchors=this.tabs.map(function(){return d("a",this)[0]}).addClass("ui-tabs-anchor").attr({role:"presentation",tabIndex:-1}),this.panels=d(),this.anchors.each(function(k,t){var j,q,p,m=d(t).uniqueId().attr("id"),e=d(t).closest("li"),s=e.attr("aria-controls");f(t)?(j=t.hash,q=a.element.find(a._sanitizeSelector(j))):(p=a._tabId(e),j="#"+p,q=a.element.find(j),q.length||(q=a._createPanel(p),q.insertAfter(a.panels[k-1]||a.tablist)),q.attr("aria-live","polite")),q.length&&(a.panels=a.panels.add(q)),s&&e.data("ui-tabs-aria-controls",s),e.attr({"aria-controls":j.substring(1),"aria-labelledby":m}),q.attr("aria-labelledby",m)}),this.panels.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").attr("role","tabpanel")},_getList:function(){return this.tablist||this.element.find("ol,ul").eq(0)},_createPanel:function(a){return d("<div>").attr("id",a).addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").data("ui-tabs-destroy",!0)},_setupDisabled:function(k){d.isArray(k)&&(k.length?k.length===this.anchors.length&&(k=!0):k=!1);for(var a,j=0;a=this.tabs[j];j++){k===!0||-1!==d.inArray(j,k)?d(a).addClass("ui-state-disabled").attr("aria-disabled","true"):d(a).removeClass("ui-state-disabled").removeAttr("aria-disabled")}this.options.disabled=k},_setupEvents:function(j){var a={click:function(e){e.preventDefault()}};j&&d.each(j.split(" "),function(i,k){a[k]="_eventHandler"}),this._off(this.anchors.add(this.tabs).add(this.panels)),this._on(this.anchors,a),this._on(this.tabs,{keydown:"_tabKeydown"}),this._on(this.panels,{keydown:"_panelKeydown"}),this._focusable(this.tabs),this._hoverable(this.tabs)},_setupHeightStyle:function(k){var a,j=this.element.parent();"fill"===k?(a=j.height(),a-=this.element.outerHeight()-this.element.height(),this.element.siblings(":visible").each(function(){var l=d(this),i=l.css("position");"absolute"!==i&&"fixed"!==i&&(a-=l.outerHeight(!0))}),this.element.children().not(this.panels).each(function(){a-=d(this).outerHeight(!0)}),this.panels.each(function(){d(this).height(Math.max(0,a-d(this).innerHeight()+d(this).height()))}).css("overflow","auto")):"auto"===k&&(a=0,this.panels.each(function(){a=Math.max(a,d(this).height("").height())}).height(a))},_eventHandler:function(u){var q=this.options,x=this.active,m=d(u.currentTarget),w=m.closest("li"),k=w[0]===x[0],j=k&&q.collapsible,t=j?d():this._getPanelForTab(w),p=x.length?this._getPanelForTab(x):d(),v={oldTab:x,oldPanel:p,newTab:j?d():w,newPanel:t};u.preventDefault(),w.hasClass("ui-state-disabled")||w.hasClass("ui-tabs-loading")||this.running||k&&!q.collapsible||this._trigger("beforeActivate",u,v)===!1||(q.active=j?!1:this.tabs.index(w),this.active=k?d():w,this.xhr&&this.xhr.abort(),p.length||t.length||d.error("jQuery UI Tabs: Mismatching fragment identifier."),t.length&&this.load(this.tabs.index(w),u),this._toggle(u,v))},_toggle:function(p,k){function l(){j.running=!1,j._trigger("activate",p,k)}function t(){k.newTab.closest("li").addClass("ui-tabs-active ui-state-active"),q.length&&j.options.show?j._show(q,j.options.show,l):(q.show(),l())}var j=this,q=k.newPanel,m=k.oldPanel;this.running=!0,m.length&&this.options.hide?this._hide(m,this.options.hide,function(){k.oldTab.closest("li").removeClass("ui-tabs-active ui-state-active"),t()}):(k.oldTab.closest("li").removeClass("ui-tabs-active ui-state-active"),m.hide(),t()),m.attr({"aria-expanded":"false","aria-hidden":"true"}),k.oldTab.attr("aria-selected","false"),q.length&&m.length?k.oldTab.attr("tabIndex",-1):q.length&&this.tabs.filter(function(){return 0===d(this).attr("tabIndex")}).attr("tabIndex",-1),q.attr({"aria-expanded":"true","aria-hidden":"false"}),k.newTab.attr({"aria-selected":"true",tabIndex:0})},_activate:function(k){var a,j=this._findActive(k);j[0]!==this.active[0]&&(j.length||(j=this.active),a=j.find(".ui-tabs-anchor")[0],this._eventHandler({target:a,currentTarget:a,preventDefault:d.noop}))},_findActive:function(a){return a===!1?d():this.tabs.eq(a)},_getIndex:function(a){return"string"==typeof a&&(a=this.anchors.index(this.anchors.filter("[href$='"+a+"']"))),a},_destroy:function(){this.xhr&&this.xhr.abort(),this.element.removeClass("ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible"),this.tablist.removeClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all").removeAttr("role"),this.anchors.removeClass("ui-tabs-anchor").removeAttr("role").removeAttr("tabIndex").removeUniqueId(),this.tabs.add(this.panels).each(function(){d.data(this,"ui-tabs-destroy")?d(this).remove():d(this).removeClass("ui-state-default ui-state-active ui-state-disabled ui-corner-top ui-corner-bottom ui-widget-content ui-tabs-active ui-tabs-panel").removeAttr("tabIndex").removeAttr("aria-live").removeAttr("aria-busy").removeAttr("aria-selected").removeAttr("aria-labelledby").removeAttr("aria-hidden").removeAttr("aria-expanded").removeAttr("role")}),this.tabs.each(function(){var j=d(this),a=j.data("ui-tabs-aria-controls");a?j.attr("aria-controls",a).removeData("ui-tabs-aria-controls"):j.removeAttr("aria-controls")}),this.panels.show(),"content"!==this.options.heightStyle&&this.panels.css("height","")},enable:function(a){var e=this.options.disabled;e!==!1&&(a===g?e=!1:(a=this._getIndex(a),e=d.isArray(e)?d.map(e,function(i){return i!==a?i:null}):d.map(this.tabs,function(i,j){return j!==a?j:null})),this._setupDisabled(e))},disable:function(a){var e=this.options.disabled;if(e!==!0){if(a===g){e=!0}else{if(a=this._getIndex(a),-1!==d.inArray(a,e)){return}e=d.isArray(e)?d.merge([a],e).sort():[a]}this._setupDisabled(e)}},load:function(p,k){p=this._getIndex(p);var s=this,j=this.tabs.eq(p),q=j.find(".ui-tabs-anchor"),m=this._getPanelForTab(j),l={tab:j,panel:m};f(q[0])||(this.xhr=d.ajax(this._ajaxSettings(q,k,l)),this.xhr&&"canceled"!==this.xhr.statusText&&(j.addClass("ui-tabs-loading"),m.attr("aria-busy","true"),this.xhr.success(function(a){setTimeout(function(){m.html(a),s._trigger("load",k,l)},1)}).complete(function(a,i){setTimeout(function(){"abort"===i&&s.panels.stop(!1,!0),j.removeClass("ui-tabs-loading"),m.removeAttr("aria-busy"),a===s.xhr&&delete s.xhr},1)})))},_ajaxSettings:function(k,a,j){var l=this;return{url:k.attr("href"),beforeSend:function(m,i){return l._trigger("beforeLoad",a,d.extend({jqXHR:m,ajaxSettings:i},j))}}},_getPanelForTab:function(j){var a=d(j).attr("aria-controls");return this.element.find(this._sanitizeSelector("#"+a))}})})(jQuery);(function(b){function d(h,f){var g=(h.attr("aria-describedby")||"").split(/\s+/);g.push(f),h.data("ui-tooltip-id",f).attr("aria-describedby",b.trim(g.join(" ")))}function a(h){var f=h.data("ui-tooltip-id"),g=(h.attr("aria-describedby")||"").split(/\s+/),j=b.inArray(f,g);-1!==j&&g.splice(j,1),h.removeData("ui-tooltip-id"),g=b.trim(g.join(" ")),g?h.attr("aria-describedby",g):h.removeAttr("aria-describedby")}var c=0;b.widget("ui.tooltip",{version:"1.10.4",options:{content:function(){var f=b(this).attr("title")||"";return b("<a>").text(f).html()},hide:!0,items:"[title]:not([disabled])",position:{my:"left top+15",at:"left bottom",collision:"flipfit flip"},show:!0,tooltipClass:null,track:!1,close:null,open:null},_create:function(){this._on({mouseover:"open",focusin:"open"}),this.tooltips={},this.parents={},this.options.disabled&&this._disable()},_setOption:function(h,f){var g=this;return"disabled"===h?(this[f?"_disable":"_enable"](),this.options[h]=f,void 0):(this._super(h,f),"content"===h&&b.each(this.tooltips,function(i,j){g._updateContent(j)}),void 0)},_disable:function(){var f=this;b.each(this.tooltips,function(e,g){var h=b.Event("blur");h.target=h.currentTarget=g[0],f.close(h,!0)}),this.element.find(this.options.items).addBack().each(function(){var g=b(this);g.is("[title]")&&g.data("ui-tooltip-title",g.attr("title")).attr("title","")})},_enable:function(){this.element.find(this.options.items).addBack().each(function(){var f=b(this);f.data("ui-tooltip-title")&&f.attr("title",f.data("ui-tooltip-title"))})},open:function(h){var f=this,g=b(h?h.target:this.element).closest(this.options.items);g.length&&!g.data("ui-tooltip-id")&&(g.attr("title")&&g.data("ui-tooltip-title",g.attr("title")),g.data("ui-tooltip-open",!0),h&&"mouseover"===h.type&&g.parents().each(function(){var j,i=b(this);i.data("ui-tooltip-open")&&(j=b.Event("blur"),j.target=j.currentTarget=this,f.close(j,!0)),i.attr("title")&&(i.uniqueId(),f.parents[this.id]={element:this,title:i.attr("title")},i.attr("title",""))}),this._updateContent(g,h))},_updateContent:function(g,j){var f,h=this.options.content,l=this,k=j?j.type:null;return"string"==typeof h?this._open(j,g,h):(f=h.call(g[0],function(e){g.data("ui-tooltip-open")&&l._delay(function(){j&&(j.type=k),this._open(j,g,e)})}),f&&this._open(j,g,f),void 0)},_open:function(g,k,q){function p(h){e.of=h,f.is(":hidden")||f.position(e)}var f,m,j,e=b.extend({},this.options.position);if(q){if(f=this._find(k),f.length){return f.find(".ui-tooltip-content").html(q),void 0}k.is("[title]")&&(g&&"mouseover"===g.type?k.attr("title",""):k.removeAttr("title")),f=this._tooltip(k),d(k,f.attr("id")),f.find(".ui-tooltip-content").html(q),this.options.track&&g&&/^mouse/.test(g.type)?(this._on(this.document,{mousemove:p}),p(g)):f.position(b.extend({of:k},this.options.position)),f.hide(),this._show(f,this.options.show),this.options.show&&this.options.show.delay&&(j=this.delayedShow=setInterval(function(){f.is(":visible")&&(p(e.of),clearInterval(j))},b.fx.interval)),this._trigger("open",g,{tooltip:f}),m={keyup:function(l){if(l.keyCode===b.ui.keyCode.ESCAPE){var h=b.Event(l);h.currentTarget=k[0],this.close(h,!0)}},remove:function(){this._removeTooltip(f)}},g&&"mouseover"!==g.type||(m.mouseleave="close"),g&&"focusin"!==g.type||(m.focusout="close"),this._on(!0,k,m)}},close:function(g){var f=this,i=b(g?g.currentTarget:this.element),h=this._find(i);this.closing||(clearInterval(this.delayedShow),i.data("ui-tooltip-title")&&i.attr("title",i.data("ui-tooltip-title")),a(i),h.stop(!0),this._hide(h,this.options.hide,function(){f._removeTooltip(b(this))}),i.removeData("ui-tooltip-open"),this._off(i,"mouseleave focusout keyup"),i[0]!==this.element[0]&&this._off(i,"remove"),this._off(this.document,"mousemove"),g&&"mouseleave"===g.type&&b.each(this.parents,function(k,j){b(j.element).attr("title",j.title),delete f.parents[k]}),this.closing=!0,this._trigger("close",g,{tooltip:h}),this.closing=!1)},_tooltip:function(g){var f="ui-tooltip-"+c++,h=b("<div>").attr({id:f,role:"tooltip"}).addClass("ui-tooltip ui-widget ui-corner-all ui-widget-content "+(this.options.tooltipClass||""));return b("<div>").addClass("ui-tooltip-content").appendTo(h),h.appendTo(this.document[0].body),this.tooltips[f]=g,h},_find:function(g){var f=g.data("ui-tooltip-id");return f?b("#"+f):b()},_removeTooltip:function(e){e.remove(),delete this.tooltips[e.attr("id")]},_destroy:function(){var f=this;b.each(this.tooltips,function(e,g){var h=b.Event("blur");h.target=h.currentTarget=g[0],f.close(h,!0),b("#"+e).remove(),g.data("ui-tooltip-title")&&(g.attr("title",g.data("ui-tooltip-title")),g.removeData("ui-tooltip-title"))})}})})(jQuery);(function(b,c){var a="ui-effects-";b.effects={effect:{}},function(D,y){function v(f,l,d){var h=C[l.type]||{};return null==f?d||!l.def?null:l.def:(f=h.floor?~~f:parseFloat(f),isNaN(f)?l.def:h.mod?(f+h.mod)%h.mod:0>f?0:f>h.max?h.max:f)}function E(d){var e=w(),f=e._rgba=[];return d=d.toLowerCase(),x(q,function(p,n){var F,u=n.re.exec(d),i=u&&n.parse(u),s=n.space||"rgba";return i?(F=e[s](i),e[A[s].cache]=F[A[s].cache],f=e._rgba=F._rgba,!1):y}),f.length?("0,0,0,0"===f.join()&&D.extend(f,B.transparent),e):B[d]}function m(f,h,d){return d=(d+1)%1,1>6*d?f+6*(h-f)*d:1>2*d?h:2>3*d?f+6*(h-f)*(2/3-d):f}var B,k="backgroundColor borderBottomColor borderLeftColor borderRightColor borderTopColor color columnRuleColor outlineColor textDecorationColor textEmphasisColor",g=/^([\-+])=\s*(\d+\.?\d*)/,q=[{re:/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,parse:function(d){return[d[1],d[2],d[3],d[4]]}},{re:/rgba?\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,parse:function(d){return[2.55*d[1],2.55*d[2],2.55*d[3],d[4]]}},{re:/#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})/,parse:function(d){return[parseInt(d[1],16),parseInt(d[2],16),parseInt(d[3],16)]}},{re:/#([a-f0-9])([a-f0-9])([a-f0-9])/,parse:function(d){return[parseInt(d[1]+d[1],16),parseInt(d[2]+d[2],16),parseInt(d[3]+d[3],16)]}},{re:/hsla?\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,space:"hsla",parse:function(d){return[d[1],d[2]/100,d[3]/100,d[4]]}}],w=D.Color=function(h,d,f,l){return new D.Color.fn.parse(h,d,f,l)},A={rgba:{props:{red:{idx:0,type:"byte"},green:{idx:1,type:"byte"},blue:{idx:2,type:"byte"}}},hsla:{props:{hue:{idx:0,type:"degrees"},saturation:{idx:1,type:"percent"},lightness:{idx:2,type:"percent"}}}},C={"byte":{floor:!0,max:255},percent:{max:1},degrees:{mod:360,floor:!0}},z=w.support={},j=D("<p>")[0],x=D.each;j.style.cssText="background-color:rgba(1,1,1,.5)",z.rgba=j.style.backgroundColor.indexOf("rgba")>-1,x(A,function(d,f){f.cache="_"+d,f.props.alpha={idx:3,type:"percent",def:1}}),w.fn=D.extend(w.prototype,{parse:function(F,t,h,e){if(F===y){return this._rgba=[null,null,null,null],this}(F.jquery||F.nodeType)&&(F=D(F).css(t),t=y);var f=this,s=D.type(F),i=this._rgba=[];return t!==y&&(F=[F,t,h,e],s="array"),"string"===s?this.parse(E(F)||B._default):"array"===s?(x(A.rgba.props,function(d,l){i[l.idx]=v(F[l.idx],l)}),this):"object"===s?(F instanceof w?x(A,function(d,l){F[l.cache]&&(f[l.cache]=F[l.cache].slice())}):x(A,function(n,l){var d=l.cache;x(l.props,function(o,p){if(!f[d]&&l.to){if("alpha"===o||null==F[o]){return}f[d]=l.to(f._rgba)}f[d][p.idx]=v(F[o],p,!0)}),f[d]&&0>D.inArray(null,f[d].slice(0,3))&&(f[d][3]=1,l.from&&(f._rgba=l.from(f[d])))}),this):y},is:function(e){var d=w(e),f=!0,h=this;return x(A,function(l,i){var p,n=d[i.cache];return n&&(p=h[i.cache]||i.to&&i.to(h._rgba)||[],x(i.props,function(r,o){return null!=n[o.idx]?f=n[o.idx]===p[o.idx]:y})),f}),f},_space:function(){var d=[],f=this;return x(A,function(e,h){f[h.cache]&&d.push(e)}),d.pop()},transition:function(h,u){var i=w(h),G=i._space(),f=A[G],F=0===this.alpha()?w("transparent"):this,p=F[f.cache]||f.to(F._rgba),d=p.slice();return i=i[f.cache],x(f.props,function(l,I){var e=I.idx,s=p[e],r=i[e],H=C[I.type]||{};null!==r&&(null===s?d[e]=r:(H.mod&&(r-s>H.mod/2?s+=H.mod:s-r>H.mod/2&&(s-=H.mod)),d[e]=v((r-s)*u+s,I)))}),this[G](d)},blend:function(h){if(1===this._rgba[3]){return this}var d=this._rgba.slice(),f=d.pop(),l=w(h)._rgba;return w(D.map(d,function(i,n){return(1-f)*l[n]+f*i}))},toRgbaString:function(){var f="rgba(",d=D.map(this._rgba,function(h,i){return null==h?i>2?1:0:h});return 1===d[3]&&(d.pop(),f="rgb("),f+d.join()+")"},toHslaString:function(){var f="hsla(",d=D.map(this.hsla(),function(h,i){return null==h&&(h=i>2?1:0),i&&3>i&&(h=Math.round(100*h)+"%"),h});return 1===d[3]&&(d.pop(),f="hsl("),f+d.join()+")"},toHexString:function(h){var d=this._rgba.slice(),f=d.pop();return h&&d.push(~~(255*f)),"#"+D.map(d,function(e){return e=(e||0).toString(16),1===e.length?"0"+e:e}).join("")},toString:function(){return 0===this._rgba[3]?"transparent":this.toRgbaString()}}),w.fn.parse.prototype=w.fn,A.hsla.to=function(M){if(null==M[0]||null==M[1]||null==M[2]){return[null,null,null,M[3]]}var I,G,N=M[0]/255,p=M[1]/255,K=M[2]/255,f=M[3],d=Math.max(N,p,K),F=Math.min(N,p,K),H=d-F,J=d+F,L=0.5*J;return I=F===d?0:N===d?60*(p-K)/H+360:p===d?60*(K-N)/H+120:60*(N-p)/H+240,G=0===H?0:0.5>=L?H/J:H/(2-J),[Math.round(I)%360,G,L,null==f?1:f]},A.hsla.from=function(h){if(null==h[0]||null==h[1]||null==h[2]){return[null,null,null,h[3]]}var p=h[0]/360,f=h[1],l=h[2],d=h[3],u=0.5>=l?l*(1+f):l+f-l*f,n=2*l-u;return[Math.round(255*m(n,u,p+1/3)),Math.round(255*m(n,u,p)),Math.round(255*m(n,u,p-1/3)),d]},x(A,function(f,p){var e=p.props,h=p.cache,d=p.to,i=p.from;w.fn[f]=function(o){if(d&&!this[h]&&(this[h]=d(this._rgba)),o===y){return this[h].slice()}var G,t=D.type(o),l="array"===t||"object"===t?o:arguments,F=this[h].slice();return x(e,function(n,u){var r=l["object"===t?n:u.idx];null==r&&(r=F[u.idx]),F[u.idx]=v(r,u)}),i?(G=w(i(F)),G[h]=F,G):w(F)},x(e,function(n,l){w.fn[n]||(w.fn[n]=function(G){var s,u=D.type(G),r="alpha"===n?this._hsla?"hsla":"rgba":f,t=this[r](),F=t[l.idx];return"undefined"===u?F:("function"===u&&(G=G.call(this,F),u=D.type(G)),null==G&&l.empty?this:("string"===u&&(s=g.exec(G),s&&(G=F+parseFloat(s[2])*("+"===s[1]?1:-1))),t[l.idx]=G,this[r](t)))})})}),w.hook=function(f){var d=f.split(" ");x(d,function(l,h){D.cssHooks[h]={set:function(t,F){var p,u,s="";if("transparent"!==F&&("string"!==D.type(F)||(p=E(F)))){if(F=w(p||F),!z.rgba&&1!==F._rgba[3]){for(u="backgroundColor"===h?t.parentNode:t;(""===s||"transparent"===s)&&u&&u.style;){try{s=D.css(u,"backgroundColor"),u=u.parentNode}catch(i){}}F=F.blend(s&&"transparent"!==s?s:"_default")}F=F.toRgbaString()}try{t.style[h]=F}catch(i){}}},D.fx.step[h]=function(i){i.colorInit||(i.start=w(i.elem,h),i.end=w(i.end),i.colorInit=!0),D.cssHooks[h].set(i.elem,i.start.transition(i.end,i.pos))}})},w.hook(k),D.cssHooks.borderColor={expand:function(d){var f={};return x(["Top","Right","Bottom","Left"],function(e,h){f["border"+h+"Color"]=d}),f}},B=D.Color.names={aqua:"#00ffff",black:"#000000",blue:"#0000ff",fuchsia:"#ff00ff",gray:"#808080",green:"#008000",lime:"#00ff00",maroon:"#800000",navy:"#000080",olive:"#808000",purple:"#800080",red:"#ff0000",silver:"#c0c0c0",teal:"#008080",white:"#ffffff",yellow:"#ffff00",transparent:[null,null,null,0],_default:"#ffffff"}}(jQuery),function(){function e(l){var j,k,m=l.ownerDocument.defaultView?l.ownerDocument.defaultView.getComputedStyle(l,null):l.currentStyle,h={};if(m&&m.length&&m[0]&&m[m[0]]){for(k=m.length;k--;){j=m[k],"string"==typeof m[j]&&(h[b.camelCase(j)]=m[j])}}else{for(j in m){"string"==typeof m[j]&&(h[j]=m[j])}}return h}function f(k,h){var j,m,l={};for(j in h){m=h[j],k[j]!==m&&(d[j]||(b.fx.step[j]||!isNaN(parseFloat(m)))&&(l[j]=m))}return l}var g=["add","remove","toggle"],d={border:1,borderBottom:1,borderColor:1,borderLeft:1,borderRight:1,borderTop:1,borderWidth:1,margin:1,padding:1};b.each(["borderLeftStyle","borderRightStyle","borderBottomStyle","borderTopStyle"],function(j,h){b.fx.step[h]=function(i){("none"!==i.end&&!i.setAttr||1===i.pos&&!i.setAttr)&&(jQuery.style(i.elem,h,i.end),i.setAttr=!0)}}),b.fn.addBack||(b.fn.addBack=function(h){return this.add(null==h?this.prevObject:this.prevObject.filter(h))}),b.effects.animateClass=function(k,i,m,j){var h=b.speed(i,m,j);return this.queue(function(){var l,q=b(this),p=q.attr("class")||"",n=h.children?q.find("*").addBack():q;n=n.map(function(){var o=b(this);return{el:o,start:e(this)}}),l=function(){b.each(g,function(r,o){k[o]&&q[o+"Class"](k[o])})},l(),n=n.map(function(){return this.end=e(this.el[0]),this.diff=f(this.start,this.end),this}),q.attr("class",p),n=n.map(function(){var t=this,o=b.Deferred(),r=b.extend({},h,{queue:!1,complete:function(){o.resolve(t)}});return this.el.animate(this.diff,r),o.promise()}),b.when.apply(b,n.get()).done(function(){l(),b.each(arguments,function(){var o=this.el;b.each(this.diff,function(r){o.css(r,"")})}),h.complete.call(q[0])})})},b.fn.extend({addClass:function(h){return function(k,l,m,j){return l?b.effects.animateClass.call(this,{add:k},l,m,j):h.apply(this,arguments)}}(b.fn.addClass),removeClass:function(h){return function(k,l,m,j){return arguments.length>1?b.effects.animateClass.call(this,{remove:k},l,m,j):h.apply(this,arguments)}}(b.fn.removeClass),toggleClass:function(h){return function(j,m,i,l,k){return"boolean"==typeof m||m===c?i?b.effects.animateClass.call(this,m?{add:j}:{remove:j},i,l,k):h.apply(this,arguments):b.effects.animateClass.call(this,{toggle:j},m,i,l)}}(b.fn.toggleClass),switchClass:function(l,j,k,m,h){return b.effects.animateClass.call(this,{add:j,remove:l},k,m,h)}})}(),function(){function d(h,f,g,j){return b.isPlainObject(h)&&(f=h,h=h.effect),h={effect:h},null==f&&(f={}),b.isFunction(f)&&(j=f,g=null,f={}),("number"==typeof f||b.fx.speeds[f])&&(j=g,g=f,f={}),b.isFunction(g)&&(j=g,g=null),f&&b.extend(h,f),g=g||f.duration,h.duration=b.fx.off?0:"number"==typeof g?g:g in b.fx.speeds?b.fx.speeds[g]:b.fx.speeds._default,h.complete=j||f.complete,h}function e(f){return !f||"number"==typeof f||b.fx.speeds[f]?!0:"string"!=typeof f||b.effects.effect[f]?b.isFunction(f)?!0:"object"!=typeof f||f.effect?!1:!0:!0}b.extend(b.effects,{version:"1.10.4",save:function(f,h){for(var g=0;h.length>g;g++){null!==h[g]&&f.data(a+h[g],f[0].style[h[g]])}},restore:function(g,h){var i,f;for(f=0;h.length>f;f++){null!==h[f]&&(i=g.data(a+h[f]),i===c&&(i=""),g.css(h[f],i))}},setMode:function(f,g){return"toggle"===g&&(g=f.is(":hidden")?"show":"hide"),g},getBaseline:function(g,j){var f,h;switch(g[0]){case"top":f=0;break;case"middle":f=0.5;break;case"bottom":f=1;break;default:f=g[0]/j.height}switch(g[1]){case"left":h=0;break;case"center":h=0.5;break;case"right":h=1;break;default:h=g[1]/j.width}return{x:h,y:f}},createWrapper:function(j){if(j.parent().is(".ui-effects-wrapper")){return j.parent()}var g={width:j.outerWidth(!0),height:j.outerHeight(!0),"float":j.css("float")},h=b("<div></div>").addClass("ui-effects-wrapper").css({fontSize:"100%",background:"transparent",border:"none",margin:0,padding:0}),l={width:j.width(),height:j.height()},f=document.activeElement;try{f.id}catch(k){f=document.body}return j.wrap(h),(j[0]===f||b.contains(j[0],f))&&b(f).focus(),h=j.parent(),"static"===j.css("position")?(h.css({position:"relative"}),j.css({position:"relative"})):(b.extend(g,{position:j.css("position"),zIndex:j.css("z-index")}),b.each(["top","left","bottom","right"],function(i,m){g[m]=j.css(m),isNaN(parseInt(g[m],10))&&(g[m]="auto")}),j.css({position:"relative",top:0,left:0,right:"auto",bottom:"auto"})),j.css(l),h.css(g).show()},removeWrapper:function(g){var f=document.activeElement;return g.parent().is(".ui-effects-wrapper")&&(g.parent().replaceWith(g),(g[0]===f||b.contains(g[0],f))&&b(f).focus()),g},setTransition:function(h,f,g,j){return j=j||{},b.each(f,function(m,l){var k=h.cssUnit(l);k[0]>0&&(j[l]=k[0]*g+k[1])}),j}}),b.fn.extend({effect:function(){function h(o){function l(){b.isFunction(i)&&i.call(p[0]),b.isFunction(o)&&o()}var p=b(this),i=g.complete,m=g.mode;(p.is(":hidden")?"hide"===m:"show"===m)?(p[m](),l()):j.call(p[0],g,l)}var g=d.apply(this,arguments),k=g.mode,f=g.queue,j=b.effects.effect[g.effect];return b.fx.off||!j?k?this[k](g.duration,g.complete):this.each(function(){g.complete&&g.complete.call(this)}):f===!1?this.each(h):this.queue(f||"fx",h)},show:function(f){return function(h){if(e(h)){return f.apply(this,arguments)}var g=d.apply(this,arguments);return g.mode="show",this.effect.call(this,g)}}(b.fn.show),hide:function(f){return function(h){if(e(h)){return f.apply(this,arguments)}var g=d.apply(this,arguments);return g.mode="hide",this.effect.call(this,g)}}(b.fn.hide),toggle:function(f){return function(h){if(e(h)||"boolean"==typeof h){return f.apply(this,arguments)}var g=d.apply(this,arguments);return g.mode="toggle",this.effect.call(this,g)}}(b.fn.toggle),cssUnit:function(h){var f=this.css(h),g=[];return b.each(["em","px","%","pt"],function(i,j){f.indexOf(j)>0&&(g=[parseFloat(f),j])}),g}})}(),function(){var d={};b.each(["Quad","Cubic","Quart","Quint","Expo"],function(f,e){d[e]=function(g){return Math.pow(g,f+2)}}),b.extend(d,{Sine:function(e){return 1-Math.cos(e*Math.PI/2)},Circ:function(e){return 1-Math.sqrt(1-e*e)},Elastic:function(e){return 0===e||1===e?e:-Math.pow(2,8*(e-1))*Math.sin((80*(e-1)-7.5)*Math.PI/15)},Back:function(e){return e*e*(3*e-2)},Bounce:function(g){for(var h,f=4;((h=Math.pow(2,--f))-1)/11>g;){}return 1/Math.pow(4,3-f)-7.5625*Math.pow((3*h-2)/22-g,2)}}),b.each(d,function(g,f){b.easing["easeIn"+g]=f,b.easing["easeOut"+g]=function(e){return 1-f(1-e)},b.easing["easeInOut"+g]=function(e){return 0.5>e?f(2*e)/2:1-f(-2*e+2)/2}})}()})(jQuery);(function(b){var c=/up|down|vertical/,a=/up|left|vertical|horizontal/;b.effects.effect.blind=function(E,k){var B,j,e,t=b(this),w=["position","top","bottom","left","right","height","width"],A=b.effects.setMode(t,E.mode||"hide"),D=E.direction||"up",z=c.test(D),i=z?"height":"width",y=z?"top":"left",x=a.test(D),q={},C="show"===A;t.parent().is(".ui-effects-wrapper")?b.effects.save(t.parent(),w):b.effects.save(t,w),t.show(),B=b.effects.createWrapper(t).css({overflow:"hidden"}),j=B[i](),e=parseFloat(B.css(y))||0,q[i]=C?j:0,x||(t.css(z?"bottom":"right",0).css(z?"top":"left","auto").css({position:"absolute"}),q[y]=C?e:j+e),C&&(B.css(i,0),x||B.css(y,e+j)),B.animate(q,{duration:E.duration,easing:E.easing,queue:!1,complete:function(){"hide"===A&&t.hide(),b.effects.restore(t,w),b.effects.removeWrapper(t),k()}})}})(jQuery);(function(a){a.effects.effect.bounce=function(H,D){var t,A,L,z=a(this),w=["position","top","bottom","left","right","height","width"],C=a.effects.setMode(z,H.mode||"effect"),E="hide"===C,J="show"===C,q=H.direction||"up",I=H.distance,x=H.times||5,G=2*x+(J||E?1:0),F=H.duration/G,B=H.easing,k="up"===q||"down"===q?"top":"left",M="up"===q||"left"===q,K=z.queue(),j=K.length;for((J||E)&&w.push("opacity"),a.effects.save(z,w),z.show(),a.effects.createWrapper(z),I||(I=z["top"===k?"outerHeight":"outerWidth"]()/3),J&&(L={opacity:1},L[k]=0,z.css("opacity",0).css(k,M?2*-I:2*I).animate(L,F,B)),E&&(I/=Math.pow(2,x-1)),L={},L[k]=0,t=0;x>t;t++){A={},A[k]=(M?"-=":"+=")+I,z.animate(A,F,B).animate(L,F,B),I=E?2*I:I/2}E&&(A={opacity:0},A[k]=(M?"-=":"+=")+I,z.animate(A,F,B)),z.queue(function(){E&&z.hide(),a.effects.restore(z,w),a.effects.removeWrapper(z),D()}),j>1&&K.splice.apply(K,[1,0].concat(K.splice(j,G+1))),z.dequeue()}})(jQuery);(function(a){a.effects.effect.clip=function(w,q){var B,k,z,j=a(this),b=["position","top","bottom","left","right","height","width"],m=a.effects.setMode(j,w.mode||"hide"),t="show"===m,y=w.direction||"vertical",A="vertical"===y,x=A?"height":"width",g=A?"top":"left",v={};a.effects.save(j,b),j.show(),B=a.effects.createWrapper(j).css({overflow:"hidden"}),k="IMG"===j[0].tagName?B:j,z=k[x](),t&&(k.css(x,0),k.css(g,z/2)),v[x]=t?z:0,v[g]=t?0:z/2,k.animate(v,{queue:!1,duration:w.duration,easing:w.easing,complete:function(){t||j.hide(),a.effects.restore(j,b),a.effects.removeWrapper(j),q()}})}})(jQuery);(function(a){a.effects.effect.drop=function(m,j){var v,f=a(this),q=["position","top","bottom","left","right","opacity","height","width"],d=a.effects.setMode(f,m.mode||"hide"),b="show"===d,g=m.direction||"left",k="up"===g||"down"===g?"top":"left",p="up"===g||"left"===g?"pos":"neg",t={opacity:b?1:0};a.effects.save(f,q),f.show(),a.effects.createWrapper(f),v=m.distance||f["top"===k?"outerHeight":"outerWidth"](!0)/2,b&&f.css("opacity",0).css(k,"pos"===p?-v:v),t[k]=(b?"pos"===p?"+=":"-=":"pos"===p?"-=":"+=")+v,f.animate(t,{queue:!1,duration:m.duration,easing:m.easing,complete:function(){"hide"===d&&f.hide(),a.effects.restore(f,q),a.effects.removeWrapper(f),j()}})}})(jQuery);(function(a){a.effects.effect.explode=function(F,B){function q(){I.push(this),I.length===k*G&&y()}function y(){w.css({visibility:"visible"}),a(I).remove(),D||w.hide(),B()}var J,x,t,A,C,H,k=F.pieces?Math.round(Math.sqrt(F.pieces)):3,G=k,w=a(this),E=a.effects.setMode(w,F.mode||"hide"),D="show"===E,z=w.show().css("visibility","hidden").offset(),j=Math.ceil(w.outerWidth()/G),K=Math.ceil(w.outerHeight()/k),I=[];for(J=0;k>J;J++){for(A=z.top+J*K,H=J-(k-1)/2,x=0;G>x;x++){t=z.left+x*j,C=x-(G-1)/2,w.clone().appendTo("body").wrap("<div></div>").css({position:"absolute",visibility:"visible",left:-x*j,top:-J*K}).parent().addClass("ui-effects-explode").css({position:"absolute",overflow:"hidden",width:j,height:K,left:t+(D?C*j:0),top:A+(D?H*K:0),opacity:D?0:1}).animate({left:t+(D?0:C*j),top:A+(D?0:H*K),opacity:D?1:0},F.duration||500,F.easing,q)}}}})(jQuery);(function(a){a.effects.effect.fade=function(d,b){var c=a(this),f=a.effects.setMode(c,d.mode||"toggle");c.animate({opacity:f},{queue:!1,duration:d.duration,easing:d.easing,complete:b})}})(jQuery);(function(a){a.effects.effect.fold=function(B,x){var H,q,E=a(this),k=["position","top","bottom","left","right","height","width"],b=a.effects.setMode(E,B.mode||"hide"),w="show"===b,y="hide"===b,D=B.size||15,G=/([0-9]+)%/.exec(D),C=!!B.horizFirst,j=w!==C,A=j?["width","height"]:["height","width"],z=B.duration/2,t={},F={};a.effects.save(E,k),E.show(),H=a.effects.createWrapper(E).css({overflow:"hidden"}),q=j?[H.width(),H.height()]:[H.height(),H.width()],G&&(D=parseInt(G[1],10)/100*q[y?0:1]),w&&H.css(C?{height:0,width:D}:{height:D,width:0}),t[A[0]]=w?q[0]:D,F[A[1]]=w?q[1]:0,H.animate(t,z,B.easing).animate(F,z,B.easing,function(){y&&E.hide(),a.effects.restore(E,k),a.effects.removeWrapper(E),x()})}})(jQuery);(function(a){a.effects.effect.highlight=function(f,c){var d=a(this),h=["backgroundImage","backgroundColor","opacity"],b=a.effects.setMode(d,f.mode||"show"),g={backgroundColor:d.css("backgroundColor")};"hide"===b&&(g.opacity=0),a.effects.save(d,h),d.show().css({backgroundImage:"none",backgroundColor:f.color||"#ffff99"}).animate(g,{queue:!1,duration:f.duration,easing:f.easing,complete:function(){"hide"===b&&d.hide(),a.effects.restore(d,h),c()}})}})(jQuery);(function(a){a.effects.effect.pulsate=function(t,m){var z,j=a(this),x=a.effects.setMode(j,t.mode||"show"),g="show"===x,b="hide"===x,k=g||"hide"===x,q=2*(t.times||5)+(k?1:0),w=t.duration/q,y=0,v=j.queue(),f=v.length;for((g||!j.is(":visible"))&&(j.css("opacity",0).show(),y=1),z=1;q>z;z++){j.animate({opacity:y},w,t.easing),y=1-y}j.animate({opacity:y},w,t.easing),j.queue(function(){b&&j.hide(),m()}),f>1&&v.splice.apply(v,[1,0].concat(v.splice(f,q+1))),j.dequeue()}})(jQuery);(function(a){a.effects.effect.puff=function(h,d){var f=a(this),k=a.effects.setMode(f,h.mode||"hide"),c="hide"===k,j=parseInt(h.percent,10)||150,g=j/100,b={height:f.height(),width:f.width(),outerHeight:f.outerHeight(),outerWidth:f.outerWidth()};a.extend(h,{effect:"scale",queue:!1,fade:!0,mode:k,complete:d,percent:c?j:100,from:c?b:{height:b.height*g,width:b.width*g,outerHeight:b.outerHeight*g,outerWidth:b.outerWidth*g}}),f.effect(h)},a.effects.effect.scale=function(m,j){var t=a(this),f=a.extend(!0,{},m),q=a.effects.setMode(t,m.mode||"effect"),d=parseInt(m.percent,10)||(0===parseInt(m.percent,10)?0:"hide"===q?0:100),b=m.direction||"both",g=m.origin,k={height:t.height(),width:t.width(),outerHeight:t.outerHeight(),outerWidth:t.outerWidth()},p={y:"horizontal"!==b?d/100:1,x:"vertical"!==b?d/100:1};f.effect="size",f.queue=!1,f.complete=j,"effect"!==q&&(f.origin=g||["middle","center"],f.restore=!0),f.from=m.from||("show"===q?{height:0,width:0,outerHeight:0,outerWidth:0}:k),f.to={height:k.height*p.y,width:k.width*p.x,outerHeight:k.outerHeight*p.y,outerWidth:k.outerWidth*p.x},f.fade&&("show"===q&&(f.from.opacity=0,f.to.opacity=1),"hide"===q&&(f.from.opacity=1,f.to.opacity=0)),t.effect(f)},a.effects.effect.size=function(F,B){var q,y,J,x=a(this),t=["position","top","bottom","left","right","width","height","overflow","opacity"],A=["position","top","bottom","left","right","overflow","opacity"],C=["width","height","overflow"],H=["fontSize"],k=["borderTopWidth","borderBottomWidth","paddingTop","paddingBottom"],G=["borderLeftWidth","borderRightWidth","paddingLeft","paddingRight"],w=a.effects.setMode(x,F.mode||"effect"),E=F.restore||"effect"!==w,D=F.scale||"both",z=F.origin||["middle","center"],j=x.css("position"),K=E?t:A,I={height:0,width:0,outerHeight:0,outerWidth:0};"show"===w&&x.show(),q={height:x.height(),width:x.width(),outerHeight:x.outerHeight(),outerWidth:x.outerWidth()},"toggle"===F.mode&&"show"===w?(x.from=F.to||I,x.to=F.from||q):(x.from=F.from||("show"===w?I:q),x.to=F.to||("hide"===w?I:q)),J={from:{y:x.from.height/q.height,x:x.from.width/q.width},to:{y:x.to.height/q.height,x:x.to.width/q.width}},("box"===D||"both"===D)&&(J.from.y!==J.to.y&&(K=K.concat(k),x.from=a.effects.setTransition(x,k,J.from.y,x.from),x.to=a.effects.setTransition(x,k,J.to.y,x.to)),J.from.x!==J.to.x&&(K=K.concat(G),x.from=a.effects.setTransition(x,G,J.from.x,x.from),x.to=a.effects.setTransition(x,G,J.to.x,x.to))),("content"===D||"both"===D)&&J.from.y!==J.to.y&&(K=K.concat(H).concat(C),x.from=a.effects.setTransition(x,H,J.from.y,x.from),x.to=a.effects.setTransition(x,H,J.to.y,x.to)),a.effects.save(x,K),x.show(),a.effects.createWrapper(x),x.css("overflow","hidden").css(x.from),z&&(y=a.effects.getBaseline(z,q),x.from.top=(q.outerHeight-x.outerHeight())*y.y,x.from.left=(q.outerWidth-x.outerWidth())*y.x,x.to.top=(q.outerHeight-x.to.outerHeight)*y.y,x.to.left=(q.outerWidth-x.to.outerWidth)*y.x),x.css(x.from),("content"===D||"both"===D)&&(k=k.concat(["marginTop","marginBottom"]).concat(H),G=G.concat(["marginLeft","marginRight"]),C=t.concat(k).concat(G),x.find("*[width]").each(function(){var b=a(this),c={height:b.height(),width:b.width(),outerHeight:b.outerHeight(),outerWidth:b.outerWidth()};E&&a.effects.save(b,C),b.from={height:c.height*J.from.y,width:c.width*J.from.x,outerHeight:c.outerHeight*J.from.y,outerWidth:c.outerWidth*J.from.x},b.to={height:c.height*J.to.y,width:c.width*J.to.x,outerHeight:c.height*J.to.y,outerWidth:c.width*J.to.x},J.from.y!==J.to.y&&(b.from=a.effects.setTransition(b,k,J.from.y,b.from),b.to=a.effects.setTransition(b,k,J.to.y,b.to)),J.from.x!==J.to.x&&(b.from=a.effects.setTransition(b,G,J.from.x,b.from),b.to=a.effects.setTransition(b,G,J.to.x,b.to)),b.css(b.from),b.animate(b.to,F.duration,F.easing,function(){E&&a.effects.restore(b,C)})})),x.animate(x.to,{queue:!1,duration:F.duration,easing:F.easing,complete:function(){0===x.to.opacity&&x.css("opacity",x.from.opacity),"hide"===w&&x.hide(),a.effects.restore(x,K),E||("static"===j?x.css({position:"relative",top:x.to.top,left:x.to.left}):a.each(["top","left"],function(b,c){x.css(c,function(g,d){var f=parseInt(d,10),h=b?x.to.left:x.to.top;return"auto"===d?h+"px":f+h+"px"})})),a.effects.removeWrapper(x),B()}})}})(jQuery);(function(a){a.effects.effect.shake=function(E,A){var k,x=a(this),H=["position","top","bottom","left","right","height","width"],w=a.effects.setMode(x,E.mode||"effect"),q=E.direction||"left",z=E.distance||20,B=E.times||3,G=2*B+1,j=Math.round(E.duration/G),F="up"===q||"down"===q?"top":"left",t="up"===q||"left"===q,D={},C={},y={},b=x.queue(),I=b.length;for(a.effects.save(x,H),x.show(),a.effects.createWrapper(x),D[F]=(t?"-=":"+=")+z,C[F]=(t?"+=":"-=")+2*z,y[F]=(t?"-=":"+=")+2*z,x.animate(D,j,E.easing),k=1;B>k;k++){x.animate(C,j,E.easing).animate(y,j,E.easing)}x.animate(C,j,E.easing).animate(D,j/2,E.easing).queue(function(){"hide"===w&&x.hide(),a.effects.restore(x,H),a.effects.removeWrapper(x),A()}),I>1&&b.splice.apply(b,[1,0].concat(b.splice(I,G+1))),x.dequeue()}})(jQuery);(function(a){a.effects.effect.slide=function(m,j){var v,f=a(this),q=["position","top","bottom","left","right","width","height"],d=a.effects.setMode(f,m.mode||"show"),b="show"===d,g=m.direction||"left",k="up"===g||"down"===g?"top":"left",p="up"===g||"left"===g,t={};a.effects.save(f,q),f.show(),v=m.distance||f["top"===k?"outerHeight":"outerWidth"](!0),a.effects.createWrapper(f).css({overflow:"hidden"}),b&&f.css(k,p?isNaN(v)?"-"+v:-v:v),t[k]=(b?p?"+=":"-=":p?"-=":"+=")+v,f.animate(t,{queue:!1,duration:m.duration,easing:m.easing,complete:function(){"hide"===d&&f.hide(),a.effects.restore(f,q),a.effects.removeWrapper(f),j()}})}})(jQuery);(function(a){a.effects.effect.transfer=function(p,k){var x=a(this),g=a(p.to),v="fixed"===g.css("position"),f=a("body"),b=v?f.scrollTop():0,j=v?f.scrollLeft():0,m=g.offset(),t={top:m.top-b,left:m.left-j,height:g.innerHeight(),width:g.innerWidth()},w=x.offset(),q=a("<div class='ui-effects-transfer'></div>").appendTo(document.body).addClass(p.className).css({top:w.top-b,left:w.left-j,height:x.innerHeight(),width:x.innerWidth(),position:v?"fixed":"absolute"}).animate(t,p.duration,p.easing,function(){q.remove(),k()})}})(jQuery);(function(d,f,c){function g(C){var B=Array.prototype.slice.call(arguments,1);if(C.prop){return C.prop.apply(C,B)}return C.attr.apply(C,B)}function x(F,D,E){var C,B;for(C in E){if(E.hasOwnProperty(C)){B=C.replace(/ |$/g,D.eventNamespace);F.bind(B,E[C])}}}function e(D,B,C){x(D,C,{focus:function(){B.addClass(C.focusClass)},blur:function(){B.removeClass(C.focusClass);B.removeClass(C.activeClass)},mouseenter:function(){B.addClass(C.hoverClass)},mouseleave:function(){B.removeClass(C.hoverClass);B.removeClass(C.activeClass)},"mousedown touchbegin":function(){if(!D.is(":disabled")){B.addClass(C.activeClass)}},"mouseup touchend":function(){B.removeClass(C.activeClass)}})}function w(C,B){C.removeClass(B.hoverClass+" "+B.focusClass+" "+B.activeClass)}function u(C,D,B){if(B){C.addClass(D)}else{C.removeClass(D)}}function z(B,D,C){setTimeout(function(){var F="checked",E=D.is(":"+F);if(D.prop){D.prop(F,E)}else{if(E){D.attr(F,F)}else{D.removeAttr(F)}}u(B,C.checkedClass,E)},1)}function o(B,D,C){u(B,C.disabledClass,D.is(":disabled"))}function m(B,C,D){switch(D){case"after":B.after(C);return B.next();case"before":B.before(C);return B.prev();case"wrap":B.wrap(C);return B.parent()}return null}function r(E,D,F){var C,B,G;if(!F){F={}}F=f.extend({bind:{},divClass:null,divWrap:"wrap",spanClass:null,spanHtml:null,spanWrap:"wrap"},F);C=f("<div />");B=f("<span />");if(D.autoHide&&E.is(":hidden")&&E.css("display")==="none"){C.hide()}if(F.divClass){C.addClass(F.divClass)}if(D.wrapperClass){C.addClass(D.wrapperClass)}if(F.spanClass){B.addClass(F.spanClass)}G=g(E,"id");if(D.useID&&G){g(C,"id",D.idPrefix+"-"+G)}if(F.spanHtml){B.html(F.spanHtml)}C=m(E,C,F.divWrap);B=m(E,B,F.spanWrap);o(C,E,D);return{div:C,span:B}}function q(D,C){var B;if(!C.wrapperClass){return null}B=f("<span />").addClass(C.wrapperClass);B=m(D,B,"wrap");return B}function i(){var E,B,D,C;C="rgb(120,2,153)";B=f('<div style="width:0;height:0;color:'+C+'">');f("body").append(B);D=B.get(0);if(d.getComputedStyle){E=d.getComputedStyle(D,"").color}else{E=(D.currentStyle||D.style||{}).color}B.remove();return E.replace(/ /g,"")!==C}function p(B){if(!B){return""}return f("<span />").text(B).html()}function k(){return navigator.cpuClass&&!navigator.product}function l(){if(d.XMLHttpRequest!==undefined){return true}return false}function a(C){var B;if(C[0].multiple){return true}B=g(C,"size");if(!B||B<=1){return false}return true}function h(){return false}function v(B,C){var D="none";x(B,C,{"selectstart dragstart mousedown":h});B.css({MozUserSelect:D,msUserSelect:D,webkitUserSelect:D,userSelect:D})}function y(E,C,D){var B=E.val();if(B===""){B=D.fileDefaultHtml}else{B=B.split(/[\/\\]+/);B=B[(B.length-1)]}C.text(B)}function n(C,E,F){var B,D;B=[];C.each(function(){var G;for(G in E){if(Object.prototype.hasOwnProperty.call(E,G)){B.push({el:this,name:G,old:this.style[G]});this.style[G]=E[G]}}});F();while(B.length){D=B.pop();D.el.style[D.name]=D.old}}function b(C,D){var B;B=C.parents();B.push(C[0]);B=B.not(":visible");n(B,{visibility:"hidden",display:"block",position:"absolute"},D)}function A(C,B){return function(){C.unwrap().unwrap().unbind(B.eventNamespace)}}var j=true,t=false,s=[{match:function(B){return B.is("a, button, :submit, :reset, input[type='button']")},apply:function(E,D){var B,C,F,H,G;C=D.submitDefaultHtml;if(E.is(":reset")){C=D.resetDefaultHtml}if(E.is("a, button")){H=function(){return E.html()||C}}else{H=function(){return p(g(E,"value"))||C}}F=r(E,D,{divClass:D.buttonClass,spanHtml:H()});B=F.div;e(E,B,D);G=false;x(B,D,{"click touchend":function(){var K,J,L,I;if(G){return}if(E.is(":disabled")){return}G=true;if(E[0].dispatchEvent){K=document.createEvent("MouseEvents");K.initEvent("click",true,true);J=E[0].dispatchEvent(K);if(E.is("a")&&J){L=g(E,"target");I=g(E,"href");if(!L||L==="_self"){document.location.href=I}else{d.open(I,L)}}}else{E.click()}G=false}});v(B,D);return{remove:function(){B.after(E);B.remove();E.unbind(D.eventNamespace);return E},update:function(){w(B,D);o(B,E,D);E.detach();F.span.html(H()).append(E)}}}},{match:function(B){return B.is(":checkbox")},apply:function(E,D){var F,C,B;F=r(E,D,{divClass:D.checkboxClass});C=F.div;B=F.span;e(E,C,D);x(E,D,{"click touchend":function(){z(B,E,D)}});z(B,E,D);return{remove:A(E,D),update:function(){w(C,D);B.removeClass(D.checkedClass);z(B,E,D);o(C,E,D)}}}},{match:function(B){return B.is(":file")},apply:function(F,E){var H,D,C,G;H=r(F,E,{divClass:E.fileClass,spanClass:E.fileButtonClass,spanHtml:E.fileButtonHtml,spanWrap:"after"});D=H.div;G=H.span;C=f("<span />").html(E.fileDefaultHtml);C.addClass(E.filenameClass);C=m(F,C,"after");if(!g(F,"size")){g(F,"size",D.width()/10)}function B(){y(F,C,E)}e(F,D,E);B();if(k()){x(F,E,{click:function(){F.trigger("change");setTimeout(B,0)}})}else{x(F,E,{change:B})}v(C,E);v(G,E);return{remove:function(){C.remove();G.remove();return F.unwrap().unbind(E.eventNamespace)},update:function(){w(D,E);y(F,C,E);o(D,F,E)}}}},{match:function(C){if(C.is("input")){var B=(" "+g(C,"type")+" ").toLowerCase(),D=" color date datetime datetime-local email month number password search tel text time url week ";return D.indexOf(B)>=0}return false},apply:function(D,C){var B,E;B=g(D,"type");D.addClass(C.inputClass);E=q(D,C);e(D,D,C);if(C.inputAddTypeAsClass){D.addClass(B)}return{remove:function(){D.removeClass(C.inputClass);if(C.inputAddTypeAsClass){D.removeClass(B)}if(E){D.unwrap()}},update:h}}},{match:function(B){return B.is(":radio")},apply:function(E,D){var F,C,B;F=r(E,D,{divClass:D.radioClass});C=F.div;B=F.span;e(E,C,D);x(E,D,{"click touchend":function(){f.uniform.update(f(':radio[name="'+g(E,"name")+'"]'))}});z(B,E,D);return{remove:A(E,D),update:function(){w(C,D);z(B,E,D);o(C,E,D)}}}},{match:function(B){if(B.is("select")&&!a(B)){return true}return false},apply:function(F,E){var G,C,B,D;if(E.selectAutoWidth){b(F,function(){D=F.width()})}G=r(F,E,{divClass:E.selectClass,spanHtml:(F.find(":selected:first")||F.find("option:first")).html(),spanWrap:"before"});C=G.div;B=G.span;if(E.selectAutoWidth){b(F,function(){n(f([B[0],C[0]]),{display:"block"},function(){var H;H=B.outerWidth()-B.width();C.width(D+H);B.width(D)})})}else{C.addClass("fixedWidth")}e(F,C,E);x(F,E,{change:function(){B.html(F.find(":selected").html());C.removeClass(E.activeClass)},"click touchend":function(){var H=F.find(":selected").html();if(B.html()!==H){F.trigger("change")}},keyup:function(){B.html(F.find(":selected").html())}});v(B,E);return{remove:function(){B.remove();F.unwrap().unbind(E.eventNamespace);return F},update:function(){if(E.selectAutoWidth){f.uniform.restore(F);F.uniform(E)}else{w(C,E);B.html(F.find(":selected").html());o(C,F,E)}}}}},{match:function(B){if(B.is("select")&&a(B)){return true}return false},apply:function(C,B){var D;C.addClass(B.selectMultiClass);D=q(C,B);e(C,C,B);return{remove:function(){C.removeClass(B.selectMultiClass);if(D){C.unwrap()}},update:h}}},{match:function(B){return B.is("textarea")},apply:function(C,B){var D;C.addClass(B.textareaClass);D=q(C,B);e(C,C,B);return{remove:function(){C.removeClass(B.textareaClass);if(D){C.unwrap()}},update:h}}}];if(k()&&!l()){j=false}f.uniform={defaults:{activeClass:"active",autoHide:true,buttonClass:"button",checkboxClass:"checker",checkedClass:"checked",disabledClass:"disabled",eventNamespace:".uniform",fileButtonClass:"action",fileButtonHtml:"Choose File",fileClass:"uploader",fileDefaultHtml:"No file selected",filenameClass:"filename",focusClass:"focus",hoverClass:"hover",idPrefix:"uniform",inputAddTypeAsClass:true,inputClass:"uniform-input",radioClass:"radio",resetDefaultHtml:"Reset",resetSelector:false,selectAutoWidth:true,selectClass:"selector",selectMultiClass:"uniform-multiselect",submitDefaultHtml:"Submit",textareaClass:"uniform",useID:true,wrapperClass:null},elements:[]};f.fn.uniform=function(B){var C=this;B=f.extend({},f.uniform.defaults,B);if(!t){t=true;if(i()){j=false}}if(!j){return this}if(B.resetSelector){f(B.resetSelector).mouseup(function(){d.setTimeout(function(){f.uniform.update(C)},10)})}return this.each(function(){var E=f(this),D,F,G;if(E.data("uniformed")){f.uniform.update(E);return}for(D=0;D<s.length;D=D+1){F=s[D];if(F.match(E,B)){G=F.apply(E,B);E.data("uniformed",G);f.uniform.elements.push(E.get(0));return}}})};f.uniform.restore=f.fn.uniform.restore=function(B){if(B===c){B=f.uniform.elements}f(B).each(function(){var E=f(this),C,D;D=E.data("uniformed");if(!D){return}D.remove();C=f.inArray(this,f.uniform.elements);if(C>=0){f.uniform.elements.splice(C,1)}E.removeData("uniformed")})};f.uniform.update=f.fn.uniform.update=function(B){if(B===c){B=f.uniform.elements}f(B).each(function(){var D=f(this),C;C=D.data("uniformed");if(!C){return}C.update(D,C.options)})}}(this,jQuery));(function(a){a.fn.oldMenu=a.fn.menu;a.fn.menu=function(e,d,c){var b=a(this).oldMenu(e,d,c);a(this).each(function(){if(!a(this).hasClass("sh-menu")){a(this).addClass("sh-menu").children().first().addClass("ui-menu-item-first");a(this).children().last().addClass("ui-menu-item-last");a(this).find(".ui-menu").addClass("sh-menu").each(function(){a(this).children().first().addClass("ui-menu-item-first");a(this).children().last().addClass("ui-menu-item-last")})}});return b};a.fn.oldUniform=a.fn.uniform;a.fn.uniform=function(l,k,j,i,h,g,f,e,c,b){var d=a(this).oldUniform(l,k,j,i,h,g,f,e,c,b);a(this).each(function(){var n=a(this);if(!n.hasClass("sh-uniform")){n.addClass("sh-uniform");if(n.is('input[type="file"]')){var r=n.parent().find(".filename");r.css("width",r.innerWidth())}if(n.is("select")&&!n.attr("multiple")){var s=n.parent(),m=s.height(),q=s.outerWidth(),o=s.find("span").outerWidth();a("<div></div>").addClass("ui-icon").css({"float":"right",marginTop:-parseInt((m/2)+8),marginRight:-parseInt((q-o)/2)-7}).appendTo(s)}}});return d}})(jQuery);(function(a){a.fn.rightClick=function(c){var b="contextmenu rightclick";a(this).each(function(){a(this).unbind(b).bind(b,function(d){d.preventDefault();a.clearSelection();if(a.isFunction(c)){c(this,d)}})});return a(this)}})(jQuery);(function(e){var f={duration:1000,clickHandler:null};function d(j){var h=jQuery(this);settings=jQuery.extend({},f,j.data);if(typeof h.data("events")!="undefined"&&typeof h.data("events").click!="undefined"){for(var k in h.data("events").click){if(h.data("events").click[k].namespace==""){var i=h.data("events").click[k].handler;h.data("taphold_click_handler",i);h.unbind("click",i);break}}}else{if(typeof settings.clickHandler=="function"){h.data("taphold_click_handler",settings.clickHandler)}}h.data("taphold_triggered",false);h.data("taphold_clicked",false);h.data("taphold_cancelled",false);h.data("taphold_timer",setTimeout(function(){if(!h.data("taphold_cancelled")&&!h.data("taphold_clicked")){h.trigger(jQuery.extend(j,jQuery.Event("taphold")));h.data("taphold_triggered",true)}},settings.duration))}function g(i){var h=jQuery(this);if(h.data("taphold_cancelled")){return}clearTimeout(h.data("taphold_timer"));if(!h.data("taphold_triggered")&&!h.data("taphold_clicked")){if(typeof h.data("taphold_click_handler")=="function"){h.data("taphold_click_handler")(jQuery.extend(i,jQuery.Event("click")))}h.data("taphold_clicked",true)}}function c(h){e(this).data("taphold_cancelled",true)}var b=("ontouchstart" in window)||("onmsgesturechange" in window);var a=e.event.special.taphold={setup:function(h){e(this).bind((b?"touchstart":"mousedown"),h,d).bind((b?"touchend":"mouseup"),g).bind((b?"touchmove touchcancel":"mouseleave"),c)},teardown:function(h){e(this).unbind((b?"touchstart":"mousedown"),d).unbind((b?"touchend":"mouseup"),g).unbind((b?"touchmove touchcancel":"mouseleave"),c)}}})(jQuery);(function(e){e.agent={};var c=" "+navigator.userAgent,b=[{expr:/ [a-z]+\/[0-9a-z\.]+/ig,delim:"/"},{expr:/ [a-z]+:[0-9a-z\.]+/ig,delim:":",keys:["rv","version"]},{expr:/ [a-z]+\s+[0-9a-z\.]+/ig,delim:/\s+/,keys:["opera","msie","firefox","android"]},{expr:/[ \/\(]([a-z0-9_]+)[ ;\)\/]/ig,keys:"i386|i486|i586|i686|x86|x64|x86_64|intel|ppc|powerpc|windows|macintosh|darwin|unix|linux|sunos|android|iphone|ipad|ipod|amiga|amigaos|beos|wii|playstation|gentoo|fedora|slackware|ubuntu|archlinux|debian|mint|mageia|mandriva|freebsd|openbsd|netbsd|solaris|opensolaris|x11|mobile|phone".split("|"),sub:"platform"}];e.each(b,function(f,h){var g=c.match(h.expr);if(g===null){return}e.each(g,function(m,l){l=l.replace(/^\s+/,"").toLowerCase();var n=l.replace(h.expr,"$1"),p=true;if(typeof h.delim!="undefined"){l=l.split(h.delim);n=l[0];p=l[1]}if(typeof h.keys!="undefined"){var o=false,i=0;for(;i<h.keys.length;i++){if(h.keys[i]==n){o=true;break}}if(!o){return}}if(typeof h.sub!="undefined"){if(typeof e.agent[h.sub]!="object"){e.agent[h.sub]={}}if(typeof e.agent[h.sub][n]=="undefined"){e.agent[h.sub][n]=p}}else{if(typeof e.agent[n]=="undefined"){e.agent[n]=p}}})});if(!e.agent.platform){e.agent.platform={}}e.mobile=false;var d="mobile|android|iphone|ipad|ipod|iemobile|phone".split("|");a=e.agent;e.each([a,a.platform],function(g,h){for(var f=0;f<d.length;f++){if(h[d[f]]){e.mobile=true;return false}}})})(jQuery);(function(a){a.fn.selection=function(e,c){var d=this.get(0);if(d.createTextRange){var b=d.createTextRange();b.collapse(true);b.moveStart("character",e);b.moveEnd("character",c-e);b.select()}else{if(d.setSelectionRange){d.setSelectionRange(e,c)}else{if(d.selectionStart){d.selectionStart=e;d.selectionEnd=c}}}d.focus()};a.fn.disableTextSelect=function(){return this.each(function(){if(a.agent.firefox){a(this).css("MozUserSelect","none")}else{if(a.agent.msie){a(this).bind("selectstart",function(){return false})}else{a(this).mousedown(function(){return false})}}})};a.fn.outerSpace=function(d,f){var c=this.get(0),e=0,b;if(!f){f="mbp"}if(/m/i.test(f)){b=parseInt(a(c).css("margin-"+d));if(b){e+=b}}if(/b/i.test(f)){b=parseInt(a(c).css("border-"+d+"-width"));if(b){e+=b}}if(/p/i.test(f)){b=parseInt(a(c).css("padding-"+d));if(b){e+=b}}return e};a.fn.outerLeftSpace=function(b){return this.outerSpace("left",b)};a.fn.outerTopSpace=function(b){return this.outerSpace("top",b)};a.fn.outerRightSpace=function(b){return this.outerSpace("right",b)};a.fn.outerBottomSpace=function(b){return this.outerSpace("bottom",b)};a.fn.outerHSpace=function(b){return(this.outerLeftSpace(b)+this.outerRightSpace(b))};a.fn.outerVSpace=function(b){return(this.outerTopSpace(b)+this.outerBottomSpace(b))};a.fn.fullscreen=function(){if(!a(this).get(0)){return}var b=a(this).get(0),d=b.requestFullScreen||b.requestFullscreen||b.webkitRequestFullScreen||b.mozRequestFullScreen||b.msRequestFullscreen;if(d){d.call(b)}else{if(typeof window.ActiveXObject!=="undefined"){var c=new ActiveXObject("WScript.Shell");if(c!==null){c.SendKeys("{F11}")}}}};a.fn.toggleFullscreen=function(b){if(a.isFullscreen(b)){a.exitFullscreen(b)}else{a(this).fullscreen()}};a.exitFullscreen=function(e){var f=e?e:document,c=f.cancelFullScreen||f.cancelFullscreen||f.webkitCancelFullScreen||f.mozCancelFullScreen||f.msExitFullscreen||f.exitFullscreen;if(c){c.call(f)}else{if(typeof window.ActiveXObject!=="undefined"){var b=new ActiveXObject("WScript.Shell");if(b!==null){b.SendKeys("{F11}")}}}};a.isFullscreen=function(b){var c=b?b:document;return(c.fullScreenElement&&(c.fullScreenElement!==null))||(c.fullscreenElement&&(c.fullscreenElement!==null))||(c.msFullscreenElement&&(c.msFullscreenElement!==null))||c.mozFullScreen||c.webkitIsFullScreen};a.clearSelection=function(){if(document.selection){document.selection.empty()}else{if(window.getSelection){window.getSelection().removeAllRanges()}}};a.$={htmlValue:function(b){return b.replace(/\&/g,"&amp;").replace(/\"/g,"&quot;").replace(/\'/g,"&#39;")},htmlData:function(b){return b.toString().replace(/\&/g,"&amp;").replace(/\</g,"&lt;").replace(/\>/g,"&gt;").replace(/\ /g,"&nbsp;").replace(/\"/g,"&quot;").replace(/\'/g,"&#39;")},jsValue:function(b){return b.replace(/\\/g,"\\\\").replace(/\r?\n/,"\\\n").replace(/\"/g,'\\"').replace(/\'/g,"\\'")},basename:function(c){var b=/^.*\/([^\/]+)\/?$/g;return b.test(c)?c.replace(b,"$1"):c},dirname:function(c){var b=/^(.*)\/[^\/]+\/?$/g;return b.test(c)?c.replace(b,"$1"):""},inArray:function(d,b){if(!a.isArray(b)){return false}for(var c=0;c<b.length;c++){if(b[c]==d){return true}}return false},getFileExtension:function(b,d){if(typeof d=="undefined"){d=true}if(/^.*\.[^\.]*$/.test(b)){var c=b.replace(/^.*\.([^\.]*)$/,"$1");return d?c.toLowerCase(c):c}else{return""}},escapeDirs:function(g){var h=/^([a-z]+)\:\/\/([^\/^\:]+)(\:(\d+))?\/(.+)$/,e="";if(h.test(g)){var b=g.replace(h,"$4");e=g.replace(h,"$1://$2");if(b.length){e+=":"+b}e+="/";g=g.replace(h,"$5")}var f=g.split("/"),d="",c=0;for(;c<f.length;c++){d+=encodeURIComponent(f[c])+"/"}return e+d.substr(0,d.length-1)},kuki:{prefix:"",duration:356,domain:"",path:"",secure:false,set:function(c,i,f,g,j,b){c=this.prefix+c;if(f==null){f=this.duration}if(b==null){b=this.secure}if((g==null)&&this.domain){g=this.domain}if((j==null)&&this.path){j=this.path}b=b?true:false;var e=new Date();e.setTime(e.getTime()+(f*86400000));var d=e.toGMTString();var h=c+"="+i+"; expires="+d;if(g!=null){h+="; domain="+g}if(j!=null){h+="; path="+j}if(b){h+="; secure"}return(document.cookie=h)?true:false},get:function(d){d=this.prefix+d;var f=d+"=";var c=document.cookie.split(";");var b;for(var e=0;e<c.length;e++){b=c[e];while(b.charAt(0)==" "){b=b.substring(1,b.length)}if(b.indexOf(f)==0){return b.substring(f.length,b.length)}}return null},del:function(b){return this.set(b,"",-1)},isSet:function(b){return(this.get(b)!=null)}}}})(jQuery);(function(a){a.$.utf8encode=function(d){d=d.replace(/\r\n/g,"\n");var b="";for(var f=0;f<d.length;f++){var e=d.charCodeAt(f);if(e<128){b+=String.fromCharCode(e)}else{if((e>127)&&(e<2048)){b+=String.fromCharCode((e>>6)|192);b+=String.fromCharCode((e&63)|128)}else{b+=String.fromCharCode((e>>12)|224);b+=String.fromCharCode(((e>>6)&63)|128);b+=String.fromCharCode((e&63)|128)}}}return b};a.$.md5=function(r){r=a.$.utf8encode(r);var J=function(c,b){return(c<<b)|(c>>>(32-b))},E=function(x,c){var k=(x&2147483648),F=(c&2147483648),G=(x&1073741824),b=(c&1073741824),d=(x&1073741823)+(c&1073741823);if(G&b){return(d^2147483648^k^F)}if(G|b){return(d&1073741824)?(d^3221225472^k^F):(d^1073741824^k^F)}else{return(d^k^F)}},q=function(b,d,c){return(b&d)|((~b)&c)},p=function(b,d,c){return(b&c)|(d&(~c))},o=function(b,d,c){return(b^d^c)},m=function(b,d,c){return(d^(b|(~c)))},t=function(G,F,Y,X,k,H,I){G=E(G,E(E(q(F,Y,X),k),I));return E(J(G,H),F)},f=function(G,F,Y,X,k,H,I){G=E(G,E(E(p(F,Y,X),k),I));return E(J(G,H),F)},C=function(G,F,Y,X,k,H,I){G=E(G,E(E(o(F,Y,X),k),I));return E(J(G,H),F)},s=function(G,F,Y,X,k,H,I){G=E(G,E(E(m(F,Y,X),k),I));return E(J(G,H),F)},e=function(x){var H,k=x.length,d=k+8,c=(d-(d%64))/64,G=(c+1)*16,I=[G-1],b=0,F=0;while(F<k){H=(F-(F%4))/4;b=(F%4)*8;I[H]=(I[H]|(x.charCodeAt(F)<<b));F++}H=(F-(F%4))/4;b=(F%4)*8;I[H]=I[H]|(128<<b);I[G-2]=k<<3;I[G-1]=k>>>29;return I},A=function(d){var x,c=0,b="",k="";for(;c<=3;c++){x=(d>>>(c*8))&255;k="0"+x.toString(16);b=b+k.substr(k.length-2,2)}return b},h,D,u,g,N=0,B=e(r),W=1732584193,V=4023233417,U=2562383102,T=271733878,Q=7,O=12,L=17,K=22,z=5,y=9,w=14,v=20,n=4,l=11,j=16,i=23,S=6,R=10,P=15,M=21;for(;N<B.length;N+=16){h=W;D=V;u=U;g=T;W=t(W,V,U,T,B[N+0],Q,3614090360);T=t(T,W,V,U,B[N+1],O,3905402710);U=t(U,T,W,V,B[N+2],L,606105819);V=t(V,U,T,W,B[N+3],K,3250441966);W=t(W,V,U,T,B[N+4],Q,4118548399);T=t(T,W,V,U,B[N+5],O,1200080426);U=t(U,T,W,V,B[N+6],L,2821735955);V=t(V,U,T,W,B[N+7],K,4249261313);W=t(W,V,U,T,B[N+8],Q,1770035416);T=t(T,W,V,U,B[N+9],O,2336552879);U=t(U,T,W,V,B[N+10],L,4294925233);V=t(V,U,T,W,B[N+11],K,2304563134);W=t(W,V,U,T,B[N+12],Q,1804603682);T=t(T,W,V,U,B[N+13],O,4254626195);U=t(U,T,W,V,B[N+14],L,2792965006);V=t(V,U,T,W,B[N+15],K,1236535329);W=f(W,V,U,T,B[N+1],z,4129170786);T=f(T,W,V,U,B[N+6],y,3225465664);U=f(U,T,W,V,B[N+11],w,643717713);V=f(V,U,T,W,B[N+0],v,3921069994);W=f(W,V,U,T,B[N+5],z,3593408605);T=f(T,W,V,U,B[N+10],y,38016083);U=f(U,T,W,V,B[N+15],w,3634488961);V=f(V,U,T,W,B[N+4],v,3889429448);W=f(W,V,U,T,B[N+9],z,568446438);T=f(T,W,V,U,B[N+14],y,3275163606);U=f(U,T,W,V,B[N+3],w,4107603335);V=f(V,U,T,W,B[N+8],v,1163531501);W=f(W,V,U,T,B[N+13],z,2850285829);T=f(T,W,V,U,B[N+2],y,4243563512);U=f(U,T,W,V,B[N+7],w,1735328473);V=f(V,U,T,W,B[N+12],v,2368359562);W=C(W,V,U,T,B[N+5],n,4294588738);T=C(T,W,V,U,B[N+8],l,2272392833);U=C(U,T,W,V,B[N+11],j,1839030562);V=C(V,U,T,W,B[N+14],i,4259657740);W=C(W,V,U,T,B[N+1],n,2763975236);T=C(T,W,V,U,B[N+4],l,1272893353);U=C(U,T,W,V,B[N+7],j,4139469664);V=C(V,U,T,W,B[N+10],i,3200236656);W=C(W,V,U,T,B[N+13],n,681279174);T=C(T,W,V,U,B[N+0],l,3936430074);U=C(U,T,W,V,B[N+3],j,3572445317);V=C(V,U,T,W,B[N+6],i,76029189);W=C(W,V,U,T,B[N+9],n,3654602809);T=C(T,W,V,U,B[N+12],l,3873151461);U=C(U,T,W,V,B[N+15],j,530742520);V=C(V,U,T,W,B[N+2],i,3299628645);W=s(W,V,U,T,B[N+0],S,4096336452);T=s(T,W,V,U,B[N+7],R,1126891415);U=s(U,T,W,V,B[N+14],P,2878612391);V=s(V,U,T,W,B[N+5],M,4237533241);W=s(W,V,U,T,B[N+12],S,1700485571);T=s(T,W,V,U,B[N+3],R,2399980690);U=s(U,T,W,V,B[N+10],P,4293915773);V=s(V,U,T,W,B[N+1],M,2240044497);W=s(W,V,U,T,B[N+8],S,1873313359);T=s(T,W,V,U,B[N+15],R,4264355552);U=s(U,T,W,V,B[N+6],P,2734768916);V=s(V,U,T,W,B[N+13],M,1309151649);W=s(W,V,U,T,B[N+4],S,4149444226);T=s(T,W,V,U,B[N+11],R,3174756917);U=s(U,T,W,V,B[N+2],P,718787259);V=s(V,U,T,W,B[N+9],M,3951481745);W=E(W,h);V=E(V,D);U=E(U,u);T=E(T,g)}return(A(W)+A(V)+A(U)+A(T)).toLowerCase()}})(jQuery);var _={opener:{},support:{},files:[],clipboard:[],labels:[],shows:[],orders:[],cms:"",scrollbarWidth:20};_.alert=function(e,b,a){var d=!b?function(){}:($.isFunction(b)?b:function(){setTimeout(function(){b.focus()},1)}),c={close:function(){d();if($(this).hasClass("ui-dialog-content")){$(this).dialog("destroy").detach()}}};$.extend(c,a);return _.dialog(_.label("Warning"),e.replace("\n","<br />\n"),c)};_.confirm=function(c,d,a){var b={buttons:[{text:_.label("Yes"),icons:{primary:"ui-icon-check"},click:function(){d();$(this).dialog("destroy").detach()}},{text:_.label("No"),icons:{primary:"ui-icon-closethick"},click:function(){$(this).dialog("destroy").detach()}}]};$.extend(b,a);return _.dialog(_.label("Confirmation"),c,b)};_.dialog=function(e,b,a){if(!a){a={}}var d=$("<div></div>");d.hide().attr("title",e).html(b).appendTo("body");if(d.find("form").get(0)&&!d.find('form [type="submit"]').get(0)){d.find("form").append('<button type="submit" style="width:0;height:0;padding:0;margin:0;border:0;visibility:hidden">Submit</button>')}var c={resizable:false,minHeight:false,modal:true,width:351,buttons:[{text:_.label("OK"),icons:{primary:"ui-icon-check"},click:function(){if(typeof a.close!="undefined"){a.close()}if($(this).hasClass("ui-dialog-content")){$(this).dialog("destroy").detach()}}}],close:function(){if($(this).hasClass("ui-dialog-content")){$(this).dialog("destroy").detach()}},closeText:false,zindex:1000000,alone:false,blur:false,legend:false,nopadding:false,show:{effect:"fade",duration:250},hide:{effect:"fade",duration:250}};$.extend(c,a);if(c.alone){$(".ui-dialog .ui-dialog-content").dialog("destroy").detach()}d.dialog(c);if(c.nopadding){d.css({padding:0})}if(c.blur){d.parent().find(".ui-dialog-buttonpane button").first().get(0).blur()}if(c.legend){d.parent().find(".ui-dialog-buttonpane").prepend('<div style="float:left;padding:10px 0 0 10px">'+c.legend+"</div>")}if($.agent&&$.agent.firefox){d.css("overflow-x","hidden")}return d};_.fileNameDialog=function(k,g,d,a,f,b,c){var e='<form method="post" action="javascript:;"><input name="'+g+'" type="text" /></form>',h=function(){var l=i.find('[type="text"]').get(0);l.value=$.trim(l.value);if(l.value==""){_.alert(_.label(f.errEmpty),function(){l.focus()});return false}else{if(/[\/\\]/g.test(l.value)){_.alert(_.label(f.errSlash),function(){l.focus()});return false}else{if(l.value.substr(0,1)=="."){_.alert(_.label(f.errDot),function(){l.focus()});return false}}}k[g]=l.value;$.ajax({type:"post",dataType:"json",url:a,data:k,async:false,success:function(m){if(_.check4errors(m,false)){return}if(b){b(m)}i.dialog("destroy").detach()},error:function(){_.alert(_.label("Unknown error."))}});return false},i=_.dialog(_.label(f.title),e,{width:351,buttons:[{text:_.label("OK"),icons:{primary:"ui-icon-check"},click:function(){h()}},{text:_.label("Cancel"),icons:{primary:"ui-icon-closethick"},click:function(){$(this).dialog("destroy").detach()}}]}),j=i.find('[type="text"]');j.uniform().attr("value",d).css("width",310);i.find("form").submit(h);if(!c&&/^(.+)\.[^\.]+$/.test(d)){j.selection(0,d.replace(/^(.+)\.[^\.]+$/,"$1").length)}else{j.get(0).focus();j.get(0).select()}};_.init=function(){if(!_.checkAgent()){return}$("body").click(function(){_.menu.hide()}).rightClick();$("#menu").unbind().click(function(){return false});_.initOpeners();_.initSettings();_.initContent();_.initToolbar();_.initResizer();_.initDropUpload();var a=$("<div></div>").css({width:100,height:100,overflow:"auto",position:"absolute",top:-1000,left:-1000}).prependTo("body").append("<div></div>").find("div").css({width:"100%",height:200});_.scrollbarWidth=100-a.width();a.parent().remove();$.each($.agent,function(b){if(b!="platform"){$("body").addClass(b)}});if($.agent.platform){$.each($.agent.platform,function(b){$("body").addClass(b)})}if($.mobile){$("body").addClass("mobile")}};_.checkAgent=function(){if(($.agent.msie&&!$.agent.opera&&!$.agent.chromeframe&&(parseInt($.agent.msie)<9))||($.agent.opera&&(parseInt($.agent.version)<10))||($.agent.firefox&&(parseFloat($.agent.firefox)<1.8))){var a='<div style="padding:10px">Your browser is not capable to display KCFinder. Please update your browser or install another one: <a href="http://www.mozilla.com/firefox/" target="_blank">Mozilla Firefox</a>, <a href="http://www.apple.com/safari" target="_blank">Apple Safari</a>, <a href="http://www.google.com/chrome" target="_blank">Google Chrome</a>, <a href="http://www.opera.com/browser" target="_blank">Opera</a>.';if($.agent.msie&&!$.agent.opera){a+=' You may also install <a href="http://www.google.com/chromeframe" target="_blank">Google Chrome Frame ActiveX plugin</a> to get Internet Explorer 6, 7, 8 working.'}a+="</div>";$("body").html(a);return false}return true};_.initOpeners=function(){try{if(_.opener.name=="tinymce"){if(typeof tinyMCEPopup=="undefined"){_.opener.name=null}else{_.opener.callBack=true}}else{if(_.opener.name=="tinymce4"){_.opener.callBack=true}else{if(_.opener.name=="ckeditor"){if(window.parent&&window.parent.CKEDITOR){_.opener.CKEditor.object=window.parent.CKEDITOR}else{if(window.opener&&window.opener.CKEDITOR){_.opener.CKEditor.object=window.opener.CKEDITOR;_.opener.callBack=true}else{_.opener.CKEditor=null}}}else{if((!_.opener.name||(_.opener.name=="fckeditor"))&&window.opener&&window.opener.SetUrl){_.opener.name="fckeditor";_.opener.callBack=true}}}}if(!_.opener.callBack){if((window.opener&&window.opener.KCFinder&&window.opener.KCFinder.callBack)||(window.parent&&window.parent.KCFinder&&window.parent.KCFinder.callBack)){_.opener.callBack=window.opener?window.opener.KCFinder.callBack:window.parent.KCFinder.callBack}if((window.opener&&window.opener.KCFinder&&window.opener.KCFinder.callBackMultiple)||(window.parent&&window.parent.KCFinder&&window.parent.KCFinder.callBackMultiple)){_.opener.callBackMultiple=window.opener?window.opener.KCFinder.callBackMultiple:window.parent.KCFinder.callBackMultiple}}}catch(a){}};_.initContent=function(){$("div#folders").html(_.label("Loading folders..."));$("div#files").html(_.label("Loading files..."));$.ajax({type:"get",dataType:"json",url:_.getURL("init"),async:false,success:function(a){if(_.check4errors(a)){return}_.dirWritable=a.dirWritable;$("#folders").html(_.buildTree(a.tree));_.setTreeData(a.tree);_.setTitle("KCFinder: /"+_.dir);_.initFolders();_.files=a.files?a.files:[];_.orderFiles()},error:function(){$("div#folders").html(_.label("Unknown error."));$("div#files").html(_.label("Unknown error."))}})};_.initResizer=function(){var a=($.agent.opera)?"move":"col-resize";$("#resizer").css("cursor",a).draggable({axis:"x",start:function(){$(this).css({opacity:"0.4",filter:"alpha(opacity=40)"});$("#all").css("cursor",a)},stop:function(){$(this).css({opacity:"0",filter:"alpha(opacity=0)"});$("#all").css("cursor","");var c=$("#left"),e=$("#right"),h=$("#files"),g=$("#folders"),i=parseInt($(this).css("left"))+parseInt($(this).css("width")),b=0,f;$("#toolbar a").each(function(){if($(this).css("display")!="none"){b+=$(this).outerWidth(true)}});f=$(window).width()-b;if(i<100){i=100}if(i>f){i=f}var d=$(window).width()-i;c.css("width",i);e.css("width",d);h.css("width",e.innerWidth()-h.outerHSpace());$("#resizer").css({left:c.outerWidth()-g.outerRightSpace("m"),width:g.outerRightSpace("m")+h.outerLeftSpace("m")});_.fixFilesHeight()}})};_.resize=function(){var c=$("#left"),e=$("#right"),b=$("#status"),f=$("#folders"),g=$("#files"),a=$("#resizer"),h=$(window);c.css({width:"25%",height:h.height()-b.outerHeight()});e.css({width:"75%",height:h.height()-b.outerHeight()});$("#toolbar").css("height",$("#toolbar a").outerHeight());a.css("height",$(window).height());f.css("height",c.outerHeight()-f.outerVSpace());_.fixFilesHeight();var d=c.outerWidth()+e.outerWidth();b.css("width",d);while(b.outerWidth()>d){b.css("width",parseInt(b.css("width"))-1)}while(b.outerWidth()<d){b.css("width",parseInt(b.css("width"))+1)}g.css("width",e.innerWidth()-g.outerHSpace());a.css({left:c.outerWidth()-f.outerRightSpace("m"),width:f.outerRightSpace("m")+g.outerLeftSpace("m")})};_.setTitle=function(b){document.title=b;if(_.opener.name=="tinymce"){tinyMCEPopup.editor.windowManager.setTitle(window,b)}else{if(_.opener.name=="tinymce4"){var c=$('iframe[src*="browse.php?opener=tinymce4&"]',window.parent.document),a=c.attr("src").split("browse.php?")[0];c.parent().parent().find("div.mce-title").html('<span style="padding:0 0 0 28px;margin:-2px 0 -3px -6px;display:block;font-size:1em;font-weight:bold;background:url('+a+'themes/default/img/kcf_logo.png) left center no-repeat">'+b+"</span>")}}};_.fixFilesHeight=function(){var b=$("#files"),a=$("#settings");b.css("height",$("#left").outerHeight()-$("#toolbar").outerHeight()-b.outerVSpace()-((a.css("display")!="none")?a.outerHeight():0))};_.initToolbar=function(){$("#toolbar").disableTextSelect();$("#toolbar a").click(function(){_.menu.hide()});if(!$.$.kuki.isSet("displaySettings")){$.$.kuki.set("displaySettings","off")}if($.$.kuki.get("displaySettings")=="on"){$('#toolbar a[href="kcact:settings"]').addClass("selected");$("#settings").show();_.resize()}$('#toolbar a[href="kcact:settings"]').click(function(){var a=$("#settings");if(a.css("display")=="none"){$(this).addClass("selected");$.$.kuki.set("displaySettings","on");a.show();_.fixFilesHeight()}else{$(this).removeClass("selected");$.$.kuki.set("displaySettings","off");a.hide();_.fixFilesHeight()}return false});$('#toolbar a[href="kcact:refresh"]').click(function(){_.refresh();return false});$('#toolbar a[href="kcact:maximize"]').click(function(){_.maximize(this);return false});$('#toolbar a[href="kcact:about"]').click(function(){var a='<div class="box about"><div class="head"><a href="http://kcfinder.sunhater.com" target="_blank">KCFinder</a> '+_.version+"</div>";if(_.support.check4Update){a+='<div id="checkver"><span class="loading"><span>'+_.label("Checking for new version...")+"</span></span></div>"}a+="<div>"+_.label("Licenses:")+' <a href="http://opensource.org/licenses/GPL-3.0" target="_blank">GPLv3</a> & <a href="http://opensource.org/licenses/LGPL-3.0" target="_blank">LGPLv3</a></div><div>Copyright &copy;2010-2014 Pavel Tzonkov</div></div>';var b=_.dialog(_.label("About"),a,{width:301});setTimeout(function(){$.ajax({dataType:"json",url:_.getURL("check4Update"),async:true,success:function(d){if(!b.html().length){return}var c=$("#checkver");c.removeClass("loading");if(!d.version){c.html(_.label("Unable to connect!"));return}if(_.version<d.version){c.html('<a href="http://kcfinder.sunhater.com/download" target="_blank">'+_.label("Download version {version} now!",{version:d.version})+"</a>")}else{c.html(_.label("KCFinder is up to date!"))}},error:function(){if(!b.html().length){return}$("#checkver").removeClass("loading").html(_.label("Unable to connect!"))}})},1000);return false});_.initUploadButton()};_.initUploadButton=function(){var c=$('#toolbar a[href="kcact:upload"]');if(!_.access.files.upload){c.hide();return}var e=c.get(0).offsetTop,d=c.outerWidth(),a=c.outerHeight(),b=$("#upload input");$("#toolbar").prepend('<div id="upload" style="top:'+e+"px;width:"+d+"px;height:"+a+'px"><form enctype="multipart/form-data" method="post" target="uploadResponse" action="'+_.getURL("upload")+'"><input type="file" name="upload[]" onchange="_.uploadFile(this.form)" style="height:'+a+'px" multiple="multiple" /><input type="hidden" name="dir" value="" /></form></div>');b.css("margin-left","-"+(b.outerWidth()-d));$("#upload").mouseover(function(){$('#toolbar a[href="kcact:upload"]').addClass("hover")}).mouseout(function(){$('#toolbar a[href="kcact:upload"]').removeClass("hover")})};_.uploadFile=function(a){if(!_.dirWritable){_.alert(_.label("Cannot write to upload folder."));$("#upload").detach();_.initUploadButton();return}a.elements[1].value=_.dir;$('<iframe id="uploadResponse" name="uploadResponse" src="javascript:;"></iframe>').prependTo(document.body);$("#loading").html(_.label("Uploading file...")).show();a.submit();$("#uploadResponse").load(function(){var b=$(this).contents().find("body").text();$("#loading").hide();b=b.split("\n");var c=[],d=[];$.each(b,function(e,f){if(f.substr(0,1)=="/"){c[c.length]=f.substr(1,f.length-1)}else{d[d.length]=f}});if(d.length){d=d.join("\n");if(d.replace(/^\s+/g,"").replace(/\s+$/g,"").length){_.alert(d)}}if(!c.length){c=null}_.refresh(c);$("#upload").detach();setTimeout(function(){$("#uploadResponse").detach()},1);_.initUploadButton()})};_.maximize=function(b){if(_.opener.name=="tinymce"){var e=window.parent.document,h=$('iframe[src*="browse.php?opener=tinymce&"]',e),g=parseInt(h.attr("id").replace(/^mce_(\d+)_ifr$/,"$1")),f=$("#mce_"+g,e);if($(b).hasClass("selected")){$(b).removeClass("selected");f.css({left:_.maximizeMCE.left,top:_.maximizeMCE.top,width:_.maximizeMCE.width,height:_.maximizeMCE.height});h.css({width:_.maximizeMCE.width-_.maximizeMCE.Hspace,height:_.maximizeMCE.height-_.maximizeMCE.Vspace})}else{$(b).addClass("selected");_.maximizeMCE={width:parseInt(f.css("width")),height:parseInt(f.css("height")),left:f.position().left,top:f.position().top,Hspace:parseInt(f.css("width"))-parseInt(h.css("width")),Vspace:parseInt(f.css("height"))-parseInt(h.css("height"))};var d=$(window.top).width(),a=$(window.top).height();f.css({left:$(window.parent).scrollLeft(),top:$(window.parent).scrollTop(),width:d,height:a});h.css({width:d-_.maximizeMCE.Hspace,height:a-_.maximizeMCE.Vspace})}}else{if(_.opener.name=="tinymce4"){var e=window.parent.document,h=$('iframe[src*="browse.php?opener=tinymce4&"]',e).parent(),f=h.parent();if($(b).hasClass("selected")){$(b).removeClass("selected");f.css({left:_.maximizeMCE4.left,top:_.maximizeMCE4.top,width:_.maximizeMCE4.width,height:_.maximizeMCE4.height});h.css({width:_.maximizeMCE4.width,height:_.maximizeMCE4.height-_.maximizeMCE4.Vspace})}else{$(b).addClass("selected");_.maximizeMCE4={width:parseInt(f.css("width")),height:parseInt(f.css("height")),left:f.position().left,top:f.position().top,Vspace:f.outerHeight(true)-h.outerHeight(true)-1};var d=$(window.top).width(),a=$(window.top).height();f.css({left:0,top:0,width:d,height:a});h.css({width:d,height:a-_.maximizeMCE4.Vspace})}}else{if(window.opener){window.moveTo(0,0);d=screen.availWidth;a=screen.availHeight;if($.agent.opera){a-=50}window.resizeTo(d,a)}else{if(window.parent){var c=null;$(window.parent.document).find("iframe").each(function(){if(this.src.replace("/?","?")==window.location.href.replace("/?","?")){c=this;return false}});if(c!==null){$(c).toggleFullscreen(window.parent.document)}else{$("body").toggleFullscreen()}}else{$("body").toggleFullscreen()}}}}};_.refresh=function(a){_.fadeFiles();$.ajax({type:"post",dataType:"json",url:_.getURL("chDir"),data:{dir:_.dir},async:false,success:function(b){if(_.check4errors(b)){$("#files > div").css({opacity:"",filter:""});return}_.dirWritable=b.dirWritable;_.files=b.files?b.files:[];_.orderFiles(null,a);_.statusDir()},error:function(){$("#files > div").css({opacity:"",filter:""});$("#files").html(_.label("Unknown error."))}})};_.initSettings=function(){$("#settings").disableTextSelect();$("#settings fieldset, #settings input, #settings label").uniform();if(!_.shows.length){$('#show input[type="checkbox"]').each(function(c){_.shows[c]=this.name})}var a=_.shows;if(!$.$.kuki.isSet("showname")){$.$.kuki.set("showname","on");$.each(a,function(c,d){if(d!="name"){$.$.kuki.set("show"+d,"off")}})}$('#show input[type="checkbox"]').click(function(){$.$.kuki.set("show"+this.name,this.checked?"on":"off");$("#files .file div."+this.name).css("display",this.checked?"block":"none")});$.each(a,function(c,d){$('#show input[name="'+d+'"]').get(0).checked=($.$.kuki.get("show"+d)=="on")?"checked":""});if(!_.orders.length){$('#order input[type="radio"]').each(function(c){_.orders[c]=this.value})}var b=_.orders;if(!$.$.kuki.isSet("order")){$.$.kuki.set("order","name")}if(!$.$.kuki.isSet("orderDesc")){$.$.kuki.set("orderDesc","off")}$('#order input[value="'+$.$.kuki.get("order")+'"]').get(0).checked=true;$('#order input[name="desc"]').get(0).checked=($.$.kuki.get("orderDesc")=="on");$('#order input[type="radio"]').click(function(){$.$.kuki.set("order",this.value);_.orderFiles()});$('#order input[name="desc"]').click(function(){$.$.kuki.set("orderDesc",this.checked?"on":"off");_.orderFiles()});if(!$.$.kuki.isSet("view")){$.$.kuki.set("view","thumbs")}if($.$.kuki.get("view")=="list"){$("#show").parent().hide()}$('#view input[value="'+$.$.kuki.get("view")+'"]').get(0).checked=true;$("#view input").click(function(){var c=this.value;if($.$.kuki.get("view")!=c){$.$.kuki.set("view",c);if(c=="list"){$("#show").parent().hide()}else{$("#show").parent().show()}}_.fixFilesHeight();_.refresh()})};_.initFiles=function(){$(document).unbind("keydown").keydown(function(a){return !_.selectAll(a)});$("#files").unbind().scroll(function(){_.menu.hide()}).disableTextSelect();$(".file").unbind().click(function(a){_.selectFile($(this),a)}).rightClick(function(a,b){_.menuFile($(a),b)}).dblclick(function(){_.returnFile($(this))});if($.mobile){$(".file").on("taphold",function(){_.menuFile($(this),{pageX:$(this).offset().left,pageY:$(this).offset().top+$(this).outerHeight()})})}$.each(_.shows,function(a,b){$("#files .file div."+b).css("display",($.$.kuki.get("show"+b)=="off")?"none":"block")});_.statusDir()};_.showFiles=function(b,a){_.fadeFiles();setTimeout(function(){var d=$("<div></div>");$.each(_.files,function(g,e){var j,h,c=e.size+"|"+e.mtime;if($.$.kuki.get("view")=="list"){if(!g){d.html("<table></table>")}h=$.$.getFileExtension(e.name);if(e.thumb){h=".image"}else{if(!h.length||!e.smallIcon){h="."}}h="themes/"+_.theme+"/img/files/small/"+h+".png";j=$('<tr class="file"><td class="name thumb"></td><td class="time"></td><td class="size"></td></tr>');j.appendTo(d.find("table"))}else{if(e.thumb){h=_.getURL("thumb")+"&file="+encodeURIComponent(e.name)+"&dir="+encodeURIComponent(_.dir)+"&stamp="+c}else{if(e.smallThumb){h=_.uploadURL+"/"+_.dir+"/"+encodeURIComponent(e.name);h=$.$.escapeDirs(h).replace(/\'/g,"%27")}else{h=e.bigIcon?$.$.getFileExtension(e.name):".";if(!h.length){h="."}h="themes/"+_.theme+"/img/files/big/"+h+".png"}}j=$('<div class="file"><div class="thumb"></div><div class="name"></div><div class="time"></div><div class="size"></div></div>');j.appendTo(d)}j.find(".thumb").css({backgroundImage:'url("'+h+'")'});j.find(".name").html($.$.htmlData(e.name));j.find(".time").html(e.date);j.find(".size").html(_.humanSize(e.size));j.data(e);if((e.name===a)||$.$.inArray(e.name,a)){j.addClass("selected")}});d.css({opacity:"",filter:""});$("#files").html(d);if(b){b()}_.initFiles()},200)};_.selectFile=function(b,h){if(h.ctrlKey||h.metaKey||h.shiftKey){if(h.shiftKey&&!b.hasClass("selected")){var g=b.prev();while(g.get(0)&&!g.hasClass("selected")){g.addClass("selected");g=g.prev()}}b.toggleClass("selected");var c=$(".file.selected").get(),a=0,d;if(!c.length){_.statusDir()}else{$.each(c,function(f,e){a+=$(e).data("size")});a=_.humanSize(a);if(c.length>1){$("#fileinfo").html(c.length+" "+_.label("selected files")+" ("+a+")")}else{d=$(c[0]).data();$("#fileinfo").html($.$.htmlData(d.name)+" ("+_.humanSize(d.size)+", "+d.date+")")}}}else{d=b.data();$(".file").removeClass("selected");b.addClass("selected");$("#fileinfo").html($.$.htmlData(d.name)+" ("+_.humanSize(d.size)+", "+d.date+")")}};_.selectAll=function(c){if((!c.ctrlKey&&!c.metaKey)||((c.keyCode!=65)&&(c.keyCode!=97))){return false}var b=$(".file"),a=0;if(b.length){b.addClass("selected").each(function(){a+=$(this).data("size")});$("#fileinfo").html(b.length+" "+_.label("selected files")+" ("+_.humanSize(a)+")")}return true};_.returnFile=function(c){var b,d,a=c.substr?c:_.uploadURL+"/"+_.dir+"/"+c.data("name");a=$.$.escapeDirs(a);if(_.opener.name=="ckeditor"){_.opener.CKEditor.object.tools.callFunction(_.opener.CKEditor.funcNum,a,"");window.close()}else{if(_.opener.name=="fckeditor"){window.opener.SetUrl(a);window.close()}else{if(_.opener.name=="tinymce"){d=tinyMCEPopup.getWindowArg("window");d.document.getElementById(tinyMCEPopup.getWindowArg("input")).value=a;if(d.getImageData){d.getImageData()}if(typeof(d.ImageDialog)!="undefined"){if(d.ImageDialog.getImageData){d.ImageDialog.getImageData()}if(d.ImageDialog.showPreviewImage){d.ImageDialog.showPreviewImage(a)}}tinyMCEPopup.close()}else{if(_.opener.name=="tinymce4"){d=(window.opener?window.opener:window.parent);$(d.document).find("#"+_.opener.TinyMCE.field).val(a);d.tinyMCE.activeEditor.windowManager.close()}else{if(_.opener.callBack){if(window.opener&&window.opener.KCFinder){_.opener.callBack(a);window.close()}if(window.parent&&window.parent.KCFinder){b=$('#toolbar a[href="kcact:maximize"]');if(b.hasClass("selected")){_.maximize(b)}_.opener.callBack(a)}}else{if(_.opener.callBackMultiple){if(window.opener&&window.opener.KCFinder){_.opener.callBackMultiple([a]);window.close()}if(window.parent&&window.parent.KCFinder){b=$('#toolbar a[href="kcact:maximize"]');if(b.hasClass("selected")){_.maximize(b)}_.opener.callBackMultiple([a])}}}}}}}};_.returnFiles=function(b){if(_.opener.callBackMultiple&&b.length){var a=[];$.each(b,function(d,c){a[d]=_.uploadURL+"/"+_.dir+"/"+$(c).data("name");a[d]=$.$.escapeDirs(a[d])});_.opener.callBackMultiple(a);if(window.opener){window.close()}}};_.returnThumbnails=function(c){if(_.opener.callBackMultiple){var b=[],a=0;$.each(c,function(e,d){if($(d).data("thumb")){b[a]=_.thumbsURL+"/"+_.dir+"/"+$(d).data("name");b[a]=$.$.escapeDirs(b[a++])}});_.opener.callBackMultiple(b);if(window.opener){window.close()}}};_.initFolders=function(){$("#folders").scroll(function(){_.menu.hide()}).disableTextSelect();$("div.folder > a").unbind().click(function(){_.menu.hide();return false});$("div.folder > a > span.brace").unbind().click(function(){if($(this).hasClass("opened")||$(this).hasClass("closed")){_.expandDir($(this).parent())}});$("div.folder > a > span.folder").unbind().click(function(){_.changeDir($(this).parent())}).rightClick(function(a,b){_.menuDir($(a).parent(),b)});if($.mobile){$("div.folder > a > span.folder").on("taphold",function(){_.menuDir($(this).parent(),{pageX:$(this).offset().left+1,pageY:$(this).offset().top+$(this).outerHeight()})})}};_.setTreeData=function(b,c){if(!c){c=""}else{if(c.length&&(c.substr(c.length-1,1)!="/")){c+="/"}}c+=b.name;var a='#folders a[href="kcdir:/'+$.$.escapeDirs(c)+'"]';$(a).data({name:b.name,path:c,readable:b.readable,writable:b.writable,removable:b.removable,hasDirs:b.hasDirs});$(a+" span.folder").addClass(b.current?"current":"regular");if(b.dirs&&b.dirs.length){$(a+" span.brace").addClass("opened");$.each(b.dirs,function(e,d){_.setTreeData(d,c+"/")})}else{if(b.hasDirs){$(a+" span.brace").addClass("closed")}}};_.buildTree=function(a,e){if(!e){e=""}e+=a.name;var b,d='<div class="folder"><a href="kcdir:/'+$.$.escapeDirs(e)+'"><span class="brace">&nbsp;</span><span class="folder">'+$.$.htmlData(a.name)+"</span></a>";if(a.dirs){d+='<div class="folders">';for(var c=0;c<a.dirs.length;c++){b=a.dirs[c];d+=_.buildTree(b,e+"/")}d+="</div>"}d+="</div>";return d};_.expandDir=function(a){var b=a.data("path");if(a.children(".brace").hasClass("opened")){a.parent().children(".folders").hide(500,function(){if(b==_.dir.substr(0,b.length)){_.changeDir(a)}});a.children(".brace").removeClass("opened").addClass("closed")}else{if(a.parent().children(".folders").get(0)){a.parent().children(".folders").show(500);a.children(".brace").removeClass("closed").addClass("opened")}else{if(!$("#loadingDirs").get(0)){a.parent().append('<div id="loadingDirs">'+_.label("Loading folders...")+"</div>");$("#loadingDirs").hide().show(200,function(){$.ajax({type:"post",dataType:"json",url:_.getURL("expand"),data:{dir:b},async:false,success:function(e){$("#loadingDirs").hide(200,function(){$("#loadingDirs").detach()});if(_.check4errors(e)){return}var d="";$.each(e.dirs,function(g,f){d+='<div class="folder"><a href="kcdir:/'+$.$.escapeDirs(b+"/"+f.name)+'"><span class="brace">&nbsp;</span><span class="folder">'+$.$.htmlData(f.name)+"</span></a></div>"});if(d.length){a.parent().append('<div class="folders">'+d+"</div>");var c=$(a.parent().children(".folders").first());c.hide();$(c).show(500);$.each(e.dirs,function(g,f){_.setTreeData(f,b)})}if(e.dirs.length){a.children(".brace").removeClass("closed").addClass("opened")}else{a.children(".brace").removeClass("opened closed")}_.initFolders();_.initDropUpload()},error:function(){$("#loadingDirs").detach();_.alert(_.label("Unknown error."))}})})}}}};_.changeDir=function(a){if(a.children("span.folder").hasClass("regular")){$("div.folder > a > span.folder").removeClass("current regular").addClass("regular");a.children("span.folder").removeClass("regular").addClass("current");$("#files").html(_.label("Loading files..."));$.ajax({type:"post",dataType:"json",url:_.getURL("chDir"),data:{dir:a.data("path")},async:false,success:function(b){if(_.check4errors(b)){return}_.files=b.files;_.orderFiles();_.dir=a.data("path");_.dirWritable=b.dirWritable;_.setTitle("KCFinder: /"+_.dir);_.statusDir()},error:function(){$("#files").html(_.label("Unknown error."))}})}};_.statusDir=function(){var b=0,a=0;for(;b<_.files.length;b++){a+=_.files[b].size}a=_.humanSize(a);$("#fileinfo").html(_.files.length+" "+_.label("files")+" ("+a+")")};_.refreshDir=function(a){var b=a.data("path");if(a.children(".brace").hasClass("opened")||a.children(".brace").hasClass("closed")){a.children(".brace").removeClass("opened").addClass("closed")}a.parent().children(".folders").first().detach();if(b==_.dir.substr(0,b.length)){_.changeDir(a)}_.expandDir(a);return true};_.menu={init:function(){$("#menu").html("<ul></ul>").css("display","none")},addItem:function(b,c,d,a){if(typeof a=="undefined"){a=false}$("#menu ul").append('<li><a href="'+b+'"'+(a?' class="denied"':"")+"><span>"+c+"</span></a></li>");if(!a&&$.isFunction(d)){$('#menu a[href="'+b+'"]').click(function(){_.menu.hide();return d()})}},addDivider:function(){if($("#menu ul").html().length){$("#menu ul").append("<li>-</li>")}},show:function(f){var g=$("#menu"),a=$("#menu ul");if(a.html().length){g.find("ul").first().menu();if(typeof f!="undefined"){var d=f.pageX,c=f.pageY,b=$(window);if((g.outerWidth()+d)>b.width()){d=b.width()-g.outerWidth()}if((g.outerHeight()+c)>b.height()){c=b.height()-g.outerHeight()}g.hide().css({left:d,top:c,width:""}).fadeIn("fast")}else{g.fadeIn("fast")}}else{a.detach()}},hide:function(){$("#clipboard").removeClass("selected");$("div.folder > a > span.folder").removeClass("context");$("#menu").hide().css("width","").html("").data("title",null).unbind().click(function(){return false});$(document).unbind("keydown").keydown(function(a){return !_.selectAll(a)})}};_.menuFile=function(b,g){_.menu.init();var f=b.data(),c=$(".file.selected").get();if(b.hasClass("selected")&&c.length&&(c.length>1)){var a=false,h=0,d;$.each(c,function(j,e){d=$(e).data();if(d.thumb){a=true}if(!f.writable){h++}});if(_.opener.callBackMultiple){_.menu.addItem("kcact:pick",_.label("Select"),function(){_.returnFiles(c);return false});if(a){_.menu.addItem("kcact:pick_thumb",_.label("Select Thumbnails"),function(){_.returnThumbnails(c);return false})}}if(f.thumb||f.smallThumb||_.support.zip){_.menu.addDivider();if(f.thumb||f.smallThumb){_.menu.addItem("kcact:view",_.label("View"),function(){_.viewImage(f)})}if(_.support.zip){_.menu.addItem("kcact:download",_.label("Download"),function(){var e=[];$.each(c,function(k,j){e[k]=$(j).data("name")});_.post(_.getURL("downloadSelected"),{dir:_.dir,files:e});return false})}}if(_.access.files.copy||_.access.files.move){_.menu.addDivider();_.menu.addItem("kcact:clpbrdadd",_.label("Add to Clipboard"),function(){var e="";$.each(c,function(l,k){var m=$(k).data(),j=false;for(l=0;l<_.clipboard.length;l++){if((_.clipboard[l].name==m.name)&&(_.clipboard[l].dir==_.dir)){j=true;e+=m.name+": "+_.label("This file is already added to the Clipboard.")+"\n";break}}if(!j){m.dir=_.dir;_.clipboard[_.clipboard.length]=m}});_.initClipboard();if(e.length){_.alert(e.substr(0,e.length-1))}return false})}if(_.access.files["delete"]){_.menu.addDivider();_.menu.addItem("kcact:rm",_.label("Delete"),function(){if($(this).hasClass("denied")){return false}var e=0,k=[];$.each(c,function(m,l){var n=$(l).data();if(!n.writable){e++}else{k[k.length]=_.dir+"/"+n.name}});if(e==c.length){_.alert(_.label("The selected files are not removable."));return false}var j=function(l){_.fadeFiles();$.ajax({type:"post",dataType:"json",url:_.getURL("rm_cbd"),data:{files:k},async:false,success:function(m){if(l){l()}_.check4errors(m);_.refresh()},error:function(){if(l){l()}$("#files > div").css({opacity:"",filter:""});_.alert(_.label("Unknown error."))}})};if(e){_.confirm(_.label("{count} selected files are not removable. Do you want to delete the rest?",{count:e}),j)}else{_.confirm(_.label("Are you sure you want to delete all selected files?"),j)}return false},(h==c.length))}_.menu.show(g)}else{$(".file").removeClass("selected");b.addClass("selected");$("#fileinfo").html($.$.htmlData(f.name)+" ("+_.humanSize(f.size)+", "+f.date+")");if(_.opener.callBack||_.opener.callBackMultiple){_.menu.addItem("kcact:pick",_.label("Select"),function(){_.returnFile(b);return false});if(f.thumb){_.menu.addItem("kcact:pick_thumb",_.label("Select Thumbnail"),function(){_.returnFile(_.thumbsURL+"/"+_.dir+"/"+f.name);return false})}_.menu.addDivider()}if(f.thumb||f.smallThumb){_.menu.addItem("kcact:view",_.label("View"),function(){_.viewImage(f)})}_.menu.addItem("kcact:download",_.label("Download"),function(){$("#menu").html('<form id="downloadForm" method="post" action="'+_.getURL("download")+'"><input type="hidden" name="dir" /><input type="hidden" name="file" /></form>');$("#downloadForm input").get(0).value=_.dir;$("#downloadForm input").get(1).value=f.name;$("#downloadForm").submit();return false});if(_.access.files.copy||_.access.files.move){_.menu.addDivider();_.menu.addItem("kcact:clpbrdadd",_.label("Add to Clipboard"),function(){for(i=0;i<_.clipboard.length;i++){if((_.clipboard[i].name==f.name)&&(_.clipboard[i].dir==_.dir)){_.alert(_.label("This file is already added to the Clipboard."));return false}}var e=f;e.dir=_.dir;_.clipboard[_.clipboard.length]=e;_.initClipboard();return false})}if(_.access.files.rename||_.access.files["delete"]){_.menu.addDivider()}if(_.access.files.rename){_.menu.addItem("kcact:mv",_.label("Rename..."),function(){if(!f.writable){return false}_.fileNameDialog({dir:_.dir,file:f.name},"newName",f.name,_.getURL("rename"),{title:"New file name:",errEmpty:"Please enter new file name.",errSlash:"Unallowable characters in file name.",errDot:"File name shouldn't begins with '.'"},_.refresh);return false},!f.writable)}if(_.access.files["delete"]){_.menu.addItem("kcact:rm",_.label("Delete"),function(){if(!f.writable){return false}_.confirm(_.label("Are you sure you want to delete this file?"),function(e){$.ajax({type:"post",dataType:"json",url:_.getURL("delete"),data:{dir:_.dir,file:f.name},async:false,success:function(j){if(e){e()}_.clearClipboard();if(_.check4errors(j)){return}_.refresh()},error:function(){if(e){e()}_.alert(_.label("Unknown error."))}})});return false},!f.writable)}_.menu.show(g)}};_.menuDir=function(a,d){_.menu.init();var c=a.data(),b="<ul>";if(_.clipboard&&_.clipboard.length){if(_.access.files.copy){_.menu.addItem("kcact:cpcbd",_.label("Copy {count} files",{count:_.clipboard.length}),function(){_.copyClipboard(c.path);return false},!c.writable)}if(_.access.files.move){_.menu.addItem("kcact:mvcbd",_.label("Move {count} files",{count:_.clipboard.length}),function(){_.moveClipboard(c.path);return false},!c.writable)}if(_.access.files.copy||_.access.files.move){_.menu.addDivider()}}_.menu.addItem("kcact:refresh",_.label("Refresh"),function(){_.refreshDir(a);return false});if(_.support.zip){_.menu.addDivider();_.menu.addItem("kcact:download",_.label("Download"),function(){_.post(_.getURL("downloadDir"),{dir:c.path});return false})}if(_.access.dirs.create||_.access.dirs.rename||_.access.dirs["delete"]){_.menu.addDivider()}if(_.access.dirs.create){_.menu.addItem("kcact:mkdir",_.label("New Subfolder..."),function(f){if(!c.writable){return false}_.fileNameDialog({dir:c.path},"newDir","",_.getURL("newDir"),{title:"New folder name:",errEmpty:"Please enter new folder name.",errSlash:"Unallowable characters in folder name.",errDot:"Folder name shouldn't begins with '.'"},function(){_.refreshDir(a);_.initDropUpload();if(!c.hasDirs){a.data("hasDirs",true);a.children("span.brace").addClass("closed")}});return false},!c.writable)}if(_.access.dirs.rename){_.menu.addItem("kcact:mvdir",_.label("Rename..."),function(f){if(!c.removable){return false}_.fileNameDialog({dir:c.path},"newName",c.name,_.getURL("renameDir"),{title:"New folder name:",errEmpty:"Please enter new folder name.",errSlash:"Unallowable characters in folder name.",errDot:"Folder name shouldn't begins with '.'"},function(e){if(!e.name){_.alert(_.label("Unknown error."));return}var g=(c.path==_.dir);a.children("span.folder").html($.$.htmlData(e.name));a.data("name",e.name);a.data("path",$.$.dirname(c.path)+"/"+e.name);if(g){_.dir=a.data("path")}_.initDropUpload()},true);return false},!c.removable)}if(_.access.dirs["delete"]){_.menu.addItem("kcact:rmdir",_.label("Delete"),function(){if(!c.removable){return false}_.confirm(_.label("Are you sure you want to delete this folder and all its content?"),function(e){$.ajax({type:"post",dataType:"json",url:_.getURL("deleteDir"),data:{dir:c.path},async:false,success:function(f){if(e){e()}if(_.check4errors(f)){return}a.parent().hide(500,function(){var h=a.parent().parent();var g=h.parent().children("a").first();a.parent().detach();if(!h.children("div.folder").get(0)){g.children("span.brace").first().removeClass("opened closed");g.parent().children(".folders").detach();g.data("hasDirs",false)}if(g.data("path")==_.dir.substr(0,g.data("path").length)){_.changeDir(g)}_.initDropUpload()})},error:function(){if(e){e()}_.alert(_.label("Unknown error."))}})});return false},!c.removable)}_.menu.show(d);$("div.folder > a > span.folder").removeClass("context");if(a.children("span.folder").hasClass("regular")){a.children("span.folder").addClass("context")}};_.openClipboard=function(){if(!_.clipboard||!_.clipboard.length){return}if($('#menu a[href="kcact:clrcbd"]').html()){$("#clipboard").removeClass("selected");_.menu.hide();return}setTimeout(function(){_.menu.init();var k=$("#menu"),e=$("#status"),f='<li class="list"><div>';$.each(_.clipboard,function(a,l){var b=$.$.getFileExtension(l.name);if(l.thumb){b=".image"}else{if(!l.smallIcon||!b.length){b="."}}b="themes/"+_.theme+"/img/files/small/"+b+".png";f+='<a title="'+_.label("Click to remove from the Clipboard")+'" onclick="_.removeFromClipboard('+a+')"'+((a==0)?' class="first"':"")+'><span style="background-image:url('+$.$.escapeDirs(b)+')">'+$.$.htmlData($.$.basename(l.name))+"</span></a>"});f+='</div></li><li class="div-files">-</li>';$("#menu ul").append(f);if(_.support.zip){_.menu.addItem("kcact:download",_.label("Download files"),function(){_.downloadClipboard();return false})}if(_.access.files.copy||_.access.files.move||_.access.files["delete"]){_.menu.addDivider()}if(_.access.files.copy){_.menu.addItem("kcact:cpcbd",_.label("Copy files here"),function(){if(!_.dirWritable){return false}_.copyClipboard(_.dir);return false},!_.dirWritable)}if(_.access.files.move){_.menu.addItem("kcact:mvcbd",_.label("Move files here"),function(){if(!_.dirWritable){return false}_.moveClipboard(_.dir);return false},!_.dirWritable)}if(_.access.files["delete"]){_.menu.addItem("kcact:rmcbd",_.label("Delete files"),function(){_.confirm(_.label("Are you sure you want to delete all files in the Clipboard?"),function(a){if(a){a()}_.deleteClipboard()});return false})}_.menu.addDivider();_.menu.addItem("kcact:clrcbd",_.label("Clear the Clipboard"),function(){_.clearClipboard();return false});$("#clipboard").addClass("selected");_.menu.show();var h=$(window).width()-k.css({width:""}).outerWidth(),g=$(window).height()-k.outerHeight()-e.outerHeight(),j=g+k.outerTopSpace();k.find(".list").css({"max-height":j,"overflow-y":"auto","overflow-x":"hidden",width:""});g=$(window).height()-k.outerHeight(true)-e.outerHeight(true);k.css({left:h-5,top:g}).fadeIn("fast");var d=k.find(".list").outerHeight(),c=k.find(".list div").outerHeight();if(c-d>10){k.css({left:parseInt(k.css("left"))-_.scrollbarWidth}).width(k.width()+_.scrollbarWidth)}},1)};_.viewImage=function(d){var c=new Date().getTime(),e=false,a=[],b=function(k){_.lock=true;$("#loading").html(_.label("Loading image...")).show();var h=$.$.escapeDirs(_.uploadURL+"/"+_.dir+"/"+k.name)+"?ts="+c,g=new Image(),j=$(g),f=$(window),l=$(document);onImgLoad=function(){_.lock=false;$("#files .file").each(function(){if($(this).data("name")==k.name){_.ssImage=this;return false}});j.hide().appendTo("body");var w=j.width(),s=j.height(),u=w,o=s,n=function(y){if(!_.lock){var t=a[y];_.currImg=y;b(t)}},p=function(){n((_.currImg>=a.length-1)?0:(_.currImg+1))},i=function(){n((_.currImg?_.currImg:a.length)-1)},x=$("<div></div>");j.detach().appendTo(x);x.addClass("img");if(!e){var q=f.width()-60,v=function(){l.unbind("keydown").keydown(function(t){return !_.selectAll(t)});e.dialog("destroy").detach()};if((q%2)){q++}e=_.dialog($.$.htmlData(k.name),x.get(0),{width:q,height:f.height()-36,position:[30,30],draggable:false,nopadding:true,close:v,show:false,hide:false,buttons:[{text:_.label("Previous"),icons:{primary:"ui-icon-triangle-1-w"},click:i},{text:_.label("Next"),icons:{secondary:"ui-icon-triangle-1-e"},click:p},{text:_.label("Select"),icons:{primary:"ui-icon-check"},click:function(t){l.unbind("keydown").keydown(function(y){return !_.selectAll(y)});if(_.ssImage){_.selectFile($(_.ssImage),t)}e.dialog("destroy").detach()}},{text:_.label("Close"),icons:{primary:"ui-icon-closethick"},click:v}]});e.addClass("kcfImageViewer").css("overflow","hidden").parent().find(".ui-dialog-buttonpane button").get(2).focus()}else{e.prev().find(".ui-dialog-title").html($.$.htmlData(k.name));e.html(x.get(0))}e.unbind("click").click(p).disableTextSelect();var r=e.innerWidth(),m=e.innerHeight();if((w>r)||(s>m)){u=r;o=m;if((r/m)>(w/s)){u=parseInt((w*m)/s)}else{if((r/m)<(w/s)){o=parseInt((s*r)/w)}}}j.css({width:u,height:o}).show().parent().css({display:"block",margin:"0 auto",width:u,height:o,marginTop:parseInt((m-o)/2)});$("#loading").hide();l.unbind("keydown").keydown(function(y){if(!_.lock){var t=y.keyCode;if((t==37)){i()}if((t==39)){p()}}})};g.src=h;if(g.complete){onImgLoad()}else{g.onload=onImgLoad;g.onerror=function(){_.lock=false;$("#loading").hide();_.alert(_.label("Unknown error."));l.unbind("keydown").keydown(function(i){return !_.selectAll(i)});_.refresh()}}};$.each(_.files,function(g,f){var g=a.length;if(f.thumb||f.smallThumb){a[g]=f}if(f.name==d.name){_.currImg=g}});b(d);return false};_.initClipboard=function(){if(!_.clipboard||!_.clipboard.length){return}var b=0,c=$("#clipboard");$.each(_.clipboard,function(d,e){b+=e.size});b=_.humanSize(b);c.disableTextSelect().html('<div title="'+_.label("Clipboard")+" ("+_.clipboard.length+" "+_.label("files")+", "+b+')" onclick="_.openClipboard()"></div>');var a=function(){c.css({left:$(window).width()-c.outerWidth(),top:$(window).height()-c.outerHeight()})};a();c.show();$(window).unbind().resize(function(){_.resize();a()})};_.removeFromClipboard=function(a){if(!_.clipboard||!_.clipboard[a]){return false}if(_.clipboard.length==1){_.clearClipboard();_.menu.hide();return}if(a<_.clipboard.length-1){var b=_.clipboard.slice(a+1);_.clipboard=_.clipboard.slice(0,a);_.clipboard=_.clipboard.concat(b)}else{_.clipboard.pop()}_.initClipboard();_.menu.hide();_.openClipboard();return true};_.copyClipboard=function(b){if(!_.clipboard||!_.clipboard.length){return}var d=[],a=0;for(i=0;i<_.clipboard.length;i++){if(_.clipboard[i].readable){d[i]=_.clipboard[i].dir+"/"+_.clipboard[i].name}else{a++}}if(_.clipboard.length==a){_.alert(_.label("The files in the Clipboard are not readable."));return}var c=function(e){if(b==_.dir){_.fadeFiles()}$.ajax({type:"post",dataType:"json",url:_.getURL("cp_cbd"),data:{dir:b,files:d},async:false,success:function(f){if(e){e()}_.check4errors(f);_.clearClipboard();if(b==_.dir){_.refresh()}},error:function(){if(e){e()}$("#files > div").css({opacity:"",filter:""});_.alert(_.label("Unknown error."))}})};if(a){_.confirm(_.label("{count} files in the Clipboard are not readable. Do you want to copy the rest?",{count:a}),c)}else{c()}};_.moveClipboard=function(b){if(!_.clipboard||!_.clipboard.length){return}var d=[],a=0;for(i=0;i<_.clipboard.length;i++){if(_.clipboard[i].readable&&_.clipboard[i].writable){d[i]=_.clipboard[i].dir+"/"+_.clipboard[i].name}else{a++}}if(_.clipboard.length==a){_.alert(_.label("The files in the Clipboard are not movable."));return}var c=function(e){_.fadeFiles();$.ajax({type:"post",dataType:"json",url:_.getURL("mv_cbd"),data:{dir:b,files:d},async:false,success:function(f){if(e){e()}_.check4errors(f);_.clearClipboard();_.refresh()},error:function(){if(e){e()}$("#files > div").css({opacity:"",filter:""});_.alert(_.label("Unknown error."))}})};if(a){_.confirm(_.label("{count} files in the Clipboard are not movable. Do you want to move the rest?",{count:a}),c)}else{c()}};_.deleteClipboard=function(){if(!_.clipboard||!_.clipboard.length){return}var c=[],a=0;for(i=0;i<_.clipboard.length;i++){if(_.clipboard[i].readable&&_.clipboard[i].writable){c[i]=_.clipboard[i].dir+"/"+_.clipboard[i].name}else{a++}}if(_.clipboard.length==a){_.alert(_.label("The files in the Clipboard are not removable."));return}var b=function(d){_.fadeFiles();$.ajax({type:"post",dataType:"json",url:_.getURL("rm_cbd"),data:{files:c},async:false,success:function(e){if(d){d()}_.check4errors(e);_.clearClipboard();_.refresh()},error:function(){if(d){d()}$("#files > div").css({opacity:"",filter:""});_.alert(_.label("Unknown error."))}})};if(a){_.confirm(_.label("{count} files in the Clipboard are not removable. Do you want to delete the rest?",{count:a}),b)}else{b()}};_.downloadClipboard=function(){if(!_.clipboard||!_.clipboard.length){return}var a=[];for(i=0;i<_.clipboard.length;i++){if(_.clipboard[i].readable){a[i]=_.clipboard[i].dir+"/"+_.clipboard[i].name}}if(a.length){_.post(_.getURL("downloadClipboard"),{files:a})}};_.clearClipboard=function(){$("#clipboard").html("");_.clipboard=[]};_.initDropUpload=function(){if((typeof XMLHttpRequest=="undefined")||(typeof document.addEventListener=="undefined")||(typeof File=="undefined")||(typeof FileReader=="undefined")){return}if(!XMLHttpRequest.prototype.sendAsBinary){XMLHttpRequest.prototype.sendAsBinary=function(r){var s=Array.prototype.map.call(r,function(t){return t.charCodeAt(0)&255}),q=new Uint8Array(s);this.send(q.buffer)}}var n=[],a=false,l=0,o=[],b=$("#files"),f=$("div.folder > a"),e="------multipartdropuploadboundary"+(new Date).getTime(),d,k=function(q){if(q.preventDefault){q.preventDefault()}$("#files").addClass("drag");return false},p=function(q){if(q.preventDefault){q.preventDefault()}return false},h=function(q){if(q.preventDefault){q.preventDefault()}$("#files").removeClass("drag");return false},j=function(s){if(s.preventDefault){s.preventDefault()}if(s.stopPropagation){s.stopPropagation()}$("#files").removeClass("drag");if(!$("#folders span.current").first().parent().data("writable")){_.alert("Cannot write to upload folder.");return false}l+=s.dataTransfer.files.length;for(var r=0;r<s.dataTransfer.files.length;r++){var q=s.dataTransfer.files[r];q.thisTargetDir=_.dir;n.push(q)}g();return false},m=function(q){if(q.preventDefault){q.preventDefault()}return false},i=function(t,q){if(t.preventDefault){t.preventDefault()}if(t.stopPropagation){t.stopPropagation()}if(!$(q).data("writable")){_.alert(_.label("Cannot write to upload folder."));return false}l+=t.dataTransfer.files.length;for(var s=0;s<t.dataTransfer.files.length;s++){var r=t.dataTransfer.files[s];r.thisTargetDir=$(q).data("path");n.push(r)}g();return false};b.get(0).removeEventListener("dragover",k,false);b.get(0).removeEventListener("dragenter",p,false);b.get(0).removeEventListener("dragleave",h,false);b.get(0).removeEventListener("drop",j,false);b.get(0).addEventListener("dragover",k,false);b.get(0).addEventListener("dragenter",p,false);b.get(0).addEventListener("dragleave",h,false);b.get(0).addEventListener("drop",j,false);f.each(function(){var s=this,t=function(u){$(s).children("span.folder").addClass("context");return m(u)},r=function(u){$(s).children("span.folder").removeClass("context");return m(u)},q=function(u){$(s).children("span.folder").removeClass("context");return i(u,s)};this.removeEventListener("dragover",t,false);this.removeEventListener("dragenter",m,false);this.removeEventListener("dragleave",r,false);this.removeEventListener("drop",q,false);this.addEventListener("dragover",t,false);this.addEventListener("dragenter",m,false);this.addEventListener("dragleave",r,false);this.addEventListener("drop",q,false)});function c(q){var r=q.lengthComputable?Math.round((q.loaded*100)/q.total)+"%":Math.round(q.loaded/1024)+" KB";$("#loading").html(_.label("Uploading file {number} of {count}... {progress}",{number:l-n.length,count:l,progress:r}))}function g(){if(a){return false}if(n&&n.length){var s=n.shift();d=s;$("#loading").html(_.label("Uploading file {number} of {count}... {progress}",{number:l-n.length,count:l,progress:""})).show();var q=new FileReader();q.thisFileName=s.name;q.thisFileType=s.type;q.thisFileSize=s.size;q.thisTargetDir=s.thisTargetDir;q.onload=function(t){a=true;var u="--"+e+'\r\nContent-Disposition: form-data; name="upload[]"';if(t.target.thisFileName){u+='; filename="'+$.$.utf8encode(t.target.thisFileName)+'"'}u+="\r\n";if(t.target.thisFileSize){u+="Content-Length: "+t.target.thisFileSize+"\r\n"}u+="Content-Type: "+t.target.thisFileType+"\r\n\r\n"+t.target.result+"\r\n--"+e+'\r\nContent-Disposition: form-data; name="dir"\r\n\r\n'+$.$.utf8encode(t.target.thisTargetDir)+"\r\n--"+e+"\r\n--"+e+"--\r\n";var v=new XMLHttpRequest();v.thisFileName=t.target.thisFileName;if(v.upload){v.upload.thisFileName=t.target.thisFileName;v.upload.addEventListener("progress",c,false)}v.open("post",_.getURL("upload"),true);v.setRequestHeader("Content-Type","multipart/form-data; boundary="+e);v.onload=function(w){$("#loading").hide();if(_.dir==q.thisTargetDir){_.fadeFiles()}a=false;g();if(v.responseText.substr(0,1)!="/"){o[o.length]=v.responseText}};v.sendAsBinary(u)};q.onerror=function(t){$("#loading").hide();a=false;g();o[o.length]=_.label("Failed to upload {filename}!",{filename:t.target.thisFileName})};q.readAsBinaryString(s)}else{l=0;var r=setInterval(function(){if(a){return}e="------multipartdropuploadboundary"+(new Date).getTime();n=[];clearInterval(r);if(d.thisTargetDir==_.dir){_.refresh()}if(o.length){o=o.join("\n");if(o.replace(/^\s+/g,"").replace(/\s+$/g,"").length){_.alert(o)}o=[]}},333)}}};_.orderFiles=function(f,e){var b=$.$.kuki.get("order"),g=($.$.kuki.get("orderDesc")=="on"),c,d,a;if(!_.files||!_.files.sort){_.files=[]}_.files=_.files.sort(function(i,h){if(!b){b="name"}if(b=="date"){c=i.mtime;d=h.mtime}else{if(b=="type"){c=$.$.getFileExtension(i.name);d=$.$.getFileExtension(h.name)}else{if(b=="size"){c=i.size;d=h.size}else{c=i[b].toLowerCase();d=h[b].toLowerCase()}}}if((b=="size")||(b=="date")){if(c<d){return g?1:-1}if(c>d){return g?-1:1}}if(c==d){c=i.name.toLowerCase();d=h.name.toLowerCase();a=[c,d];a=a.sort();return(a[0]==c)?-1:1}a=[c,d];a=a.sort();if(a[0]==c){return g?1:-1}return g?-1:1});_.showFiles(f,e);_.initFiles()};_.humanSize=function(a){if(a<1024){a=a.toString()+" B"}else{if(a<1048576){a/=1024;a=parseInt(a).toString()+" KB"}else{if(a<1073741824){a/=1048576;a=parseInt(a).toString()+" MB"}else{if(a<1099511627776){a/=1073741824;a=parseInt(a).toString()+" GB"}else{a/=1099511627776;a=parseInt(a).toString()+" TB"}}}}return a};_.getURL=function(a){var b="browse.php?type="+encodeURIComponent(_.type)+"&lng="+encodeURIComponent(_.lang);if(_.opener.name){b+="&opener="+encodeURIComponent(_.opener.name)}if(a){b+="&act="+encodeURIComponent(a)}if(_.cms){b+="&cms="+encodeURIComponent(_.cms)}return b};_.label=function(b,c){var a=_.labels[b]?_.labels[b]:b;if(c){$.each(c,function(d,e){a=a.replace("{"+d+"}",e)})}return a};_.check4errors=function(a){if(!a.error){return false}var b=a.error.join?a.error.join("\n"):a.error;_.alert(b);return true};_.post=function(a,c){var b='<form id="postForm" method="post" action="'+a+'">';$.each(c,function(d,e){if($.isArray(e)){$.each(e,function(g,f){b+='<input type="hidden" name="'+$.$.htmlValue(d)+'[]" value="'+$.$.htmlValue(f)+'" />'})}else{b+='<input type="hidden" name="'+$.$.htmlValue(d)+'" value="'+$.$.htmlValue(e)+'" />'}});b+="</form>";$("#menu").html(b).show();$("#postForm").get(0).submit()};_.fadeFiles=function(){$("#files > div").css({opacity:"0.4",filter:"alpha(opacity=40)"})};
src/svg-icons/image/timer-10.js
kasra-co/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageTimer10 = (props) => ( <SvgIcon {...props}> <path d="M0 7.72V9.4l3-1V18h2V6h-.25L0 7.72zm23.78 6.65c-.14-.28-.35-.53-.63-.74-.28-.21-.61-.39-1.01-.53s-.85-.27-1.35-.38c-.35-.07-.64-.15-.87-.23-.23-.08-.41-.16-.55-.25-.14-.09-.23-.19-.28-.3-.05-.11-.08-.24-.08-.39 0-.14.03-.28.09-.41.06-.13.15-.25.27-.34.12-.1.27-.18.45-.24s.4-.09.64-.09c.25 0 .47.04.66.11.19.07.35.17.48.29.13.12.22.26.29.42.06.16.1.32.1.49h1.95c0-.39-.08-.75-.24-1.09-.16-.34-.39-.63-.69-.88-.3-.25-.66-.44-1.09-.59C21.49 9.07 21 9 20.46 9c-.51 0-.98.07-1.39.21-.41.14-.77.33-1.06.57-.29.24-.51.52-.67.84-.16.32-.23.65-.23 1.01s.08.69.23.96c.15.28.36.52.64.73.27.21.6.38.98.53.38.14.81.26 1.27.36.39.08.71.17.95.26s.43.19.57.29c.13.1.22.22.27.34.05.12.07.25.07.39 0 .32-.13.57-.4.77-.27.2-.66.29-1.17.29-.22 0-.43-.02-.64-.08-.21-.05-.4-.13-.56-.24-.17-.11-.3-.26-.41-.44-.11-.18-.17-.41-.18-.67h-1.89c0 .36.08.71.24 1.05.16.34.39.65.7.93.31.27.69.49 1.15.66.46.17.98.25 1.58.25.53 0 1.01-.06 1.44-.19.43-.13.8-.31 1.11-.54.31-.23.54-.51.71-.83.17-.32.25-.67.25-1.06-.02-.4-.09-.74-.24-1.02zm-9.96-7.32c-.34-.4-.75-.7-1.23-.88-.47-.18-1.01-.27-1.59-.27-.58 0-1.11.09-1.59.27-.48.18-.89.47-1.23.88-.34.41-.6.93-.79 1.59-.18.65-.28 1.45-.28 2.39v1.92c0 .94.09 1.74.28 2.39.19.66.45 1.19.8 1.6.34.41.75.71 1.23.89.48.18 1.01.28 1.59.28.59 0 1.12-.09 1.59-.28.48-.18.88-.48 1.22-.89.34-.41.6-.94.78-1.6.18-.65.28-1.45.28-2.39v-1.92c0-.94-.09-1.74-.28-2.39-.18-.66-.44-1.19-.78-1.59zm-.92 6.17c0 .6-.04 1.11-.12 1.53-.08.42-.2.76-.36 1.02-.16.26-.36.45-.59.57-.23.12-.51.18-.82.18-.3 0-.58-.06-.82-.18s-.44-.31-.6-.57c-.16-.26-.29-.6-.38-1.02-.09-.42-.13-.93-.13-1.53v-2.5c0-.6.04-1.11.13-1.52.09-.41.21-.74.38-1 .16-.25.36-.43.6-.55.24-.11.51-.17.81-.17.31 0 .58.06.81.17.24.11.44.29.6.55.16.25.29.58.37.99.08.41.13.92.13 1.52v2.51z"/> </SvgIcon> ); ImageTimer10 = pure(ImageTimer10); ImageTimer10.displayName = 'ImageTimer10'; ImageTimer10.muiName = 'SvgIcon'; export default ImageTimer10;
ajax/libs/foundation/4.2.3/js/vendor/jquery.js
iamso/cdnjs
/*! * jQuery JavaScript Library v1.10.1 * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2005, 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2013-05-30T21:49Z */ (function( window, undefined ) { // 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+ //"use strict"; var // The deferred used on DOM ready readyList, // A central reference to the root jQuery(document) rootjQuery, // Support: IE<10 // For `typeof xmlNode.method` instead of `xmlNode.method !== undefined` core_strundefined = typeof undefined, // Use the correct document accordingly with window argument (sandbox) location = window.location, document = window.document, docElem = document.documentElement, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // [[Class]] -> type pairs class2type = {}, // List of deleted data cache ids, so we can reuse them core_deletedIds = [], core_version = "1.10.1", // Save a reference to some core methods core_concat = core_deletedIds.concat, core_push = core_deletedIds.push, core_slice = core_deletedIds.slice, core_indexOf = core_deletedIds.indexOf, core_toString = class2type.toString, core_hasOwn = class2type.hasOwnProperty, core_trim = core_version.trim, // 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 splitting on whitespace core_rnotwhite = /\S+/g, // 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) // Strict HTML recognition (#11290: must start with <) rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, // JSON RegExp rvalidchars = /^[\],:{}\s]*$/, rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g, rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return letter.toUpperCase(); }, // The ready event handler completed = function( event ) { // readyState === "complete" is good enough for us to call the dom ready in oldIE if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) { detach(); jQuery.ready(); } }, // Clean-up method for dom ready events detach = function() { if ( document.addEventListener ) { document.removeEventListener( "DOMContentLoaded", completed, false ); window.removeEventListener( "load", completed, false ); } else { document.detachEvent( "onreadystatechange", completed ); window.detachEvent( "onload", completed ); } }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: core_version, constructor: jQuery, init: function( selector, context, rootjQuery ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle HTML strings if ( typeof selector === "string" ) { if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; // scripts is true for back-compat jQuery.merge( this, jQuery.parseHTML( match[1], context && context.nodeType ? context.ownerDocument || context : document, true ) ); // HANDLE: $(html, props) if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( jQuery.isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes } else { this.attr( match, context[ match ] ); } } } return this; // HANDLE: $(#id) } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id !== match[2] ) { return rootjQuery.find( selector ); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(DOMElement) } else if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }, // Start with an empty selector selector: "", // The default length of a jQuery object is 0 length: 0, 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 ) { // 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 ); }, ready: function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }, slice: function() { return this.pushStack( core_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] ] : [] ); }, 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 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; 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({ // Unique for each copy of jQuery on the page // Non-digits removed to match rinlinejQuery expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ), noConflict: function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }, // 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.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 ) { /* jshint eqeqeq: false */ return obj != null && obj == obj.window; }, isNumeric: function( obj ) { return !isNaN( parseFloat(obj) ) && isFinite( obj ); }, type: function( obj ) { if ( obj == null ) { return String( obj ); } return typeof obj === "object" || typeof obj === "function" ? class2type[ core_toString.call(obj) ] || "object" : typeof obj; }, 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 && !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; } // Support: IE<9 // Handle iteration over inherited properties before own properties. if ( jQuery.support.ownLast ) { for ( key in obj ) { return core_hasOwn.call( obj, key ); } } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. 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 // keepScripts (optional): If true, will include scripts passed in the html string parseHTML: function( data, context, keepScripts ) { if ( !data || typeof data !== "string" ) { return null; } if ( typeof context === "boolean" ) { keepScripts = context; context = false; } context = context || document; var parsed = rsingleTag.exec( data ), scripts = !keepScripts && []; // Single tag if ( parsed ) { return [ context.createElement( parsed[1] ) ]; } parsed = jQuery.buildFragment( [ data ], context, scripts ); if ( scripts ) { jQuery( scripts ).remove(); } return jQuery.merge( [], parsed.childNodes ); }, parseJSON: function( data ) { // Attempt to parse using the native JSON parser first if ( window.JSON && window.JSON.parse ) { return window.JSON.parse( data ); } if ( data === null ) { return data; } if ( typeof data === "string" ) { // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); if ( data ) { // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if ( rvalidchars.test( data.replace( rvalidescape, "@" ) .replace( rvalidtokens, "]" ) .replace( rvalidbraces, "")) ) { 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 && 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; }, // Use native String.trim function wherever possible trim: core_trim && !core_trim.call("\uFEFF\xA0") ? function( text ) { return text == null ? "" : core_trim.call( text ); } : // Otherwise use our own trimming functionality function( text ) { return text == null ? "" : ( text + "" ).replace( rtrim, "" ); }, // 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 { core_push.call( 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, i = 0, length = elems.length, isArray = isArraylike( elems ), ret = []; // 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 ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } } // Flatten any nested arrays return core_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 = core_slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, 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 || 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, raw ) { var i = 0, length = elems.length, bulk = key == null; // Sets many values if ( jQuery.type( key ) === "object" ) { chainable = true; for ( i in key ) { jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( !jQuery.isFunction( value ) ) { raw = true; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn.call( elems, value ); fn = null; // ...except when executing function values } else { bulk = fn; fn = function( elem, key, value ) { return bulk.call( jQuery( elem ), value ); }; } } if ( fn ) { for ( ; i < length; i++ ) { fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); } } } return chainable ? elems : // Gets bulk ? fn.call( elems ) : length ? fn( elems[0], key ) : emptyGet; }, now: function() { return ( new Date() ).getTime(); }, // A method for quickly swapping in/out CSS properties to get correct calculations. // Note: this method belongs to the css module but it's needed here for the support module. // If support gets modularized, this method should be moved back to the css module. swap: function( elem, options, callback, args ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.apply( elem, args || [] ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; } }); jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser event has already occurred. // we once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready ); // Standards-based browsers support DOMContentLoaded } else if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed, false ); // If IE event model is used } else { // Ensure firing before onload, maybe late but safe also for iframes document.attachEvent( "onreadystatechange", completed ); // A fallback to window.onload, that will always work window.attachEvent( "onload", completed ); // If IE and not a frame // continually check to see if the document is ready var top = false; try { top = window.frameElement == null && document.documentElement; } catch(e) {} if ( top && top.doScroll ) { (function doScrollCheck() { if ( !jQuery.isReady ) { try { // Use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ top.doScroll("left"); } catch(e) { return setTimeout( doScrollCheck, 50 ); } // detach all dom ready events detach(); // 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 Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); function isArraylike( obj ) { var length = obj.length, type = jQuery.type( obj ); if ( jQuery.isWindow( obj ) ) { return false; } if ( obj.nodeType === 1 && length ) { return true; } return type === "array" || type !== "function" && ( length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj ); } // All jQuery objects should point back to these rootjQuery = jQuery(document); /*! * Sizzle CSS Selector Engine v1.9.4-pre * http://sizzlejs.com/ * * Copyright 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2013-05-27 */ (function( window, undefined ) { var i, support, cachedruns, Expr, getText, isXML, compile, outermostContext, sortInput, // Local document vars setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data expando = "sizzle" + -(new Date()), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), hasDuplicate = false, sortOrder = function() { return 0; }, // General-purpose constants strundefined = typeof undefined, 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 if we can't use a native one indexOf = arr.indexOf || function( elem ) { var i = 0, len = this.length; for ( ; i < len; i++ ) { if ( this[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#" ), // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + "*(?:([*^$|!~]?=)" + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", // Prefer arguments quoted, // then not containing pseudos/brackets, // then attribute selectors/non-parenthetical expressions, // then anything else // These preferences are here to reduce the number of selectors // needing tokenize in the PSEUDO preFilter pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)", // 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 + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rsibling = new RegExp( 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" ) }, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, 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 // Workaround erroneous numeric interpretation of +"0x" return high !== high || escapedWhitespace ? escaped : // BMP codepoint high < 0 ? String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }; // 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 || []; if ( !selector || typeof selector !== "string" ) { return results; } if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { return []; } if ( documentIsHTML && !seed ) { // Shortcuts if ( (match = rquickExpr.exec( selector )) ) { // Speed-up: Sizzle("#ID") if ( (m = match[1]) ) { if ( nodeType === 9 ) { elem = context.getElementById( m ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE, Opera, and Webkit return items // by name instead of ID if ( elem.id === m ) { results.push( elem ); 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 && context.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // QSA path if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { nid = old = expando; newContext = context; newSelector = nodeType === 9 && selector; // 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 ) && 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 ); } /** * For feature detection * @param {Function} fn The function to test for native support */ function isNative( fn ) { return rnative.test( fn + "" ); } /** * 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 if the test fails * @param {Boolean} test The result of a test. If true, null will be set as the handler in leiu of the specified handler */ function addHandle( attrs, handler, test ) { attrs = attrs.split("|"); var current, i = attrs.length, setHandle = test ? null : handler; while ( i-- ) { // Don't override a user's handler if ( !(current = Expr.attrHandle[ attrs[i] ]) || current === handler ) { Expr.attrHandle[ attrs[i] ] = setHandle; } } } /** * Fetches boolean attributes by node * @param {Element} elem * @param {String} name */ function boolHandler( elem, name ) { // XML does not need to be checked as this will not be assigned for XML documents var val = elem.getAttributeNode( name ); return val && val.specified ? val.value : elem[ name ] === true ? name.toLowerCase() : null; } /** * Fetches attributes without interpolation * http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx * @param {Element} elem * @param {String} name */ function interpolationHandler( elem, name ) { // XML does not need to be checked as this will not be assigned for XML documents return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); } /** * Uses defaultValue to retrieve value in IE6/7 * @param {Element} elem * @param {String} name */ function valueHandler( elem ) { // Ignore the value *property* on inputs by using defaultValue // Fallback to Sizzle.attr by returning undefined where appropriate // XML does not need to be checked as this will not be assigned for XML documents if ( elem.nodeName.toLowerCase() === "input" ) { return elem.defaultValue; } } /** * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns Returns -1 if a precedes b, 1 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]); } } }); }); } /** * Detect xml * @param {Element|Object} elem An element or a document */ 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; }; // Expose support vars for convenience support = Sizzle.support = {}; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var doc = node ? node.ownerDocument || node : preferredDoc, parent = doc.parentWindow; // 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; // Support tests documentIsHTML = !isXML( doc ); // Support: IE>8 // If iframe document is assigned to "document" variable and if iframe has been reloaded, // IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936 if ( parent && parent.frameElement ) { parent.attachEvent( "onbeforeunload", function() { setDocument(); }); } /* Attributes ---------------------------------------------------------------------- */ // Support: IE<8 // Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans) support.attributes = assert(function( div ) { // Support: IE<8 // Prevent attribute/property "interpolation" div.innerHTML = "<a href='#'></a>"; addHandle( "type|href|height|width", interpolationHandler, div.firstChild.getAttribute("href") === "#" ); // Support: IE<9 // Use getAttributeNode to fetch booleans when getAttribute lies addHandle( booleans, boolHandler, div.getAttribute("disabled") == null ); div.className = "i"; return !div.getAttribute("className"); }); // Support: IE<9 // Retrieving value should defer to defaultValue support.input = assert(function( div ) { div.innerHTML = "<input>"; div.firstChild.setAttribute( "value", "" ); return div.firstChild.getAttribute( "value" ) === ""; }); // IE6/7 still return empty string for value, // but are actually retrieving the property addHandle( "value", valueHandler, support.attributes && support.input ); /* getElement(s)By* ---------------------------------------------------------------------- */ // Check if getElementsByTagName("*") returns only elements support.getElementsByTagName = assert(function( div ) { div.appendChild( doc.createComment("") ); return !div.getElementsByTagName("*").length; }); // Check if getElementsByClassName can be trusted support.getElementsByClassName = assert(function( div ) { div.innerHTML = "<div class='a'></div><div class='a i'></div>"; // Support: Safari<4 // Catch class over-caching div.firstChild.className = "i"; // Support: Opera<10 // Catch gEBCN failure to find non-leading classes return div.getElementsByClassName("i").length === 2; }); // Support: IE<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 !== strundefined && 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 !== strundefined && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; } // Tag Expr.find["TAG"] = support.getElementsByTagName ? function( tag, context ) { if ( typeof context.getElementsByTagName !== strundefined ) { return context.getElementsByTagName( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, 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 ( typeof context.getElementsByClassName !== strundefined && 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 = isNative(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 div.innerHTML = "<select><option selected=''></option></select>"; // Support: IE8 // Boolean attributes and "value" are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } // 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"); } }); assert(function( div ) { // Support: Opera 10-12/IE8 // ^= $= *= and empty values // Should not select anything // Support: Windows 8 Native Apps // The type attribute is restricted during .innerHTML assignment var input = doc.createElement("input"); input.setAttribute( "type", "hidden" ); div.appendChild( input ).setAttribute( "t", "" ); if ( div.querySelectorAll("[t^='']").length ) { rbuggyQSA.push( "[*^$]=" + 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 = isNative( (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 ---------------------------------------------------------------------- */ // Element contains another // Purposefully does not implement inclusive descendent // As in, an element does not contain itself contains = isNative(docElem.contains) || docElem.compareDocumentPosition ? 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 ---------------------------------------------------------------------- */ // 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( doc.createElement("div") ) & 1; }); // Document order sorting sortOrder = docElem.compareDocumentPosition ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } var compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b ); if ( compare ) { // 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 || contains(preferredDoc, a) ) { return -1; } if ( b === doc || contains(preferredDoc, b) ) { return 1; } // Maintain original order return sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } // Not directly comparable, sort on existence of method return a.compareDocumentPosition ? -1 : 1; } : function( a, b ) { var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; // Parentless nodes are either documents or disconnected } else if ( !aup || !bup ) { return a === doc ? -1 : b === doc ? 1 : aup ? -1 : bup ? 1 : sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( 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 ? support.attributes || !documentIsHTML ? elem.getAttribute( name ) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null : val; }; 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 ); } } 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 for ( ; (node = elem[i]); i++ ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (see #11153) 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[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[5] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is if ( match[3] && match[4] !== undefined ) { match[2] = match[4]; // 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 !== strundefined && 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 + " " ).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.call( 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 ); return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { 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 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 "?") for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) { 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; // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) // use getAttribute instead to test this case return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type ); }, // 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; }) } }; // 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 ); } function tokenize( 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 data, cache, outerCache, dirkey = 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 ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) { if ( (data = cache[1]) === true || data === cachedruns ) { return data === true; } } else { cache = outerCache[ dir ] = [ dirkey ]; cache[1] = matcher( elem, context, xml ) || cachedruns; if ( cache[1] === true ) { 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 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.call( 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.call( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); } ]; 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 ) { // A counter to specify which element is currently being matched var matcherCachedRuns = 0, bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, expandContext ) { var elem, j, matcher, setMatched = [], matchedCount = 0, i = "0", unmatched = seed && [], outermost = expandContext != null, contextBackup = outermostContext, // We must always have either seed elements or context elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1); if ( outermost ) { outermostContext = context !== document && context; cachedruns = matcherCachedRuns; } // Add elements passing elementMatchers directly to results // Keep `i` a string if there are no elements so `matchedCount` will be "00" below for ( ; (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { j = 0; while ( (matcher = elementMatchers[j++]) ) { if ( matcher( elem, context, xml ) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; cachedruns = ++matcherCachedRuns; } } // 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, group /* 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 ( !group ) { group = tokenize( selector ); } i = group.length; while ( i-- ) { cached = matcherFromTokens( group[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); } return cached; }; function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function select( selector, context, results, seed ) { var i, tokens, token, type, find, match = tokenize( selector ); if ( !seed ) { // Try to minimize operations if there is 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; } 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 ) && 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 // Provide `match` to avoid retokenization if we modified the selector above compile( selector, match )( seed, context, !documentIsHTML, results, rsibling.test( selector ) ); return results; } // Deprecated Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Easy API for creating new setFilters function setFilters() {} setFilters.prototype = Expr.filters = Expr.pseudos; Expr.setFilters = new setFilters(); // One-time assignments // Sort stability support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; // Initialize against the default document setDocument(); // Support: Chrome<<14 // Always assume duplicates if they aren't passed to the comparison function [0, 0].sort( sortOrder ); support.detectDuplicates = hasDuplicate; 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 ); // String to Object options format cache var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache function createOptions( options ) { var object = optionsCache[ options ] = {}; jQuery.each( options.match( core_rnotwhite ) || [], function( _, flag ) { object[ flag ] = true; }); return object; } /* * 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 ) { 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 = jQuery.isFunction( fns[ i ] ) && fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ](function() { var returned = fn && fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .done( newDefer.resolve ) .fail( newDefer.reject ) .progress( newDefer.notify ); } else { newDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); } }); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // 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 = 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( support ) { var all, a, input, select, fragment, opt, eventName, isSupported, i, div = document.createElement("div"); // Setup div.setAttribute( "className", "t" ); div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; // Finish early in limited (non-browser) environments all = div.getElementsByTagName("*") || []; a = div.getElementsByTagName("a")[ 0 ]; if ( !a || !a.style || !all.length ) { return support; } // First batch of tests select = document.createElement("select"); opt = select.appendChild( document.createElement("option") ); input = div.getElementsByTagName("input")[ 0 ]; a.style.cssText = "top:1px;float:left;opacity:.5"; // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) support.getSetAttribute = div.className !== "t"; // 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; // 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"; // Make sure that element opacity exists // (IE uses filter instead) // Use a regex to work around a WebKit issue. See #5145 support.opacity = /^0.5/.test( a.style.opacity ); // Verify style float existence // (IE uses styleFloat instead of cssFloat) support.cssFloat = !!a.style.cssFloat; // 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; // 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>"; // Will be defined later support.inlineBlockNeedsLayout = false; support.shrinkWrapBlocks = false; support.pixelPosition = false; support.deleteExpando = true; support.noCloneEvent = true; support.reliableMarginRight = true; support.boxSizingReliable = true; // 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; // Support: IE<9 try { delete div.test; } catch( e ) { support.deleteExpando = false; } // 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"; // #11217 - WebKit loses check when the name is after the checked attribute input.setAttribute( "checked", "t" ); input.setAttribute( "name", "t" ); fragment = document.createDocumentFragment(); fragment.appendChild( input ); // Check if a disconnected checkbox will retain its checked // value of true after appended to the DOM (IE6/7) support.appendChecked = input.checked; // WebKit doesn't clone checked state correctly in fragments support.checkClone = fragment.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() if ( div.attachEvent ) { div.attachEvent( "onclick", function() { support.noCloneEvent = false; }); div.cloneNode( true ).click(); } // Support: IE<9 (lack submit/change bubble), Firefox 17+ (lack focusin event) // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP) for ( i in { submit: true, change: true, focusin: true }) { div.setAttribute( eventName = "on" + i, "t" ); support[ i + "Bubbles" ] = eventName in window || div.attributes[ eventName ].expando === false; } div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; // Support: IE<9 // Iteration over object's inherited properties before its own. for ( i in jQuery( support ) ) { break; } support.ownLast = i !== "0"; // Run tests that need a body at doc ready jQuery(function() { var container, marginDiv, tds, divReset = "padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;", body = document.getElementsByTagName("body")[0]; if ( !body ) { // Return for frameset docs that don't have a body return; } container = document.createElement("div"); container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px"; body.appendChild( container ).appendChild( div ); // 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>"; 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"; // Support: IE8 // Check if empty table cells still have offsetWidth/Height 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%;"; // Workaround failing boxSizing test due to offsetWidth returning wrong value // with some non-1 values of body zoom, ticket #13543 jQuery.swap( body, body.style.zoom != null ? { zoom: 1 } : {}, function() { support.boxSizing = div.offsetWidth === 4; }); // Use window.getComputedStyle because jsdom on node.js will break without it. if ( window.getComputedStyle ) { support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. (#3333) // Fails in WebKit before Feb 2011 nightlies // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right marginDiv = div.appendChild( document.createElement("div") ); marginDiv.style.cssText = div.style.cssText = divReset; marginDiv.style.marginRight = marginDiv.style.width = "0"; div.style.width = "1px"; support.reliableMarginRight = !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); } if ( typeof div.style.zoom !== core_strundefined ) { // Support: IE<8 // Check if natively block-level elements act like inline-block // elements when setting their display to 'inline' and giving // them layout div.innerHTML = ""; div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1"; support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 ); // Support: IE6 // Check if elements with layout shrink-wrap their children div.style.display = "block"; div.innerHTML = "<div></div>"; div.firstChild.style.width = "5px"; support.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); if ( support.inlineBlockNeedsLayout ) { // Prevent IE 6 from affecting layout for positioned elements #11048 // Prevent IE from shrinking the body in IE 7 mode #12869 // Support: IE<8 body.style.zoom = 1; } } body.removeChild( container ); // Null elements to avoid leaks in IE container = div = tds = marginDiv = null; }); // Null elements to avoid leaks in IE all = select = fragment = opt = a = input = null; return support; })({}); var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, rmultiDash = /([A-Z])/g; 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 ] = core_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 ( jQuery.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 throw uncatchable exceptions if you // attempt to add expando properties to them. noData: { "applet": true, "embed": true, // Ban all objects except for Flash (which handle expandos) "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" }, 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 ); }, // A method for determining if a DOM node can handle the data expando acceptData: function( elem ) { // Do not set data on non-element because it will not be cleared (#8335). if ( elem.nodeType && elem.nodeType !== 1 && elem.nodeType !== 9 ) { return false; } 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 attrs, name, data = null, i = 0, elem = this[0]; // 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" ) ) { attrs = elem.attributes; for ( ; i < attrs.length; 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 ) ) : null; }, 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" ); 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 ); }); }, // 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, rclass = /[\t\r\n\f]/g, rreturn = /\r/g, rfocusable = /^(?:input|select|textarea|button|object)$/i, rclickable = /^(?:a|area)$/i, ruseDefault = /^(?:checked|selected)$/i, getSetAttribute = jQuery.support.getSetAttribute, getSetInput = jQuery.support.input; jQuery.fn.extend({ attr: function( name, value ) { return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); }, 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 classes, elem, cur, clazz, j, 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( core_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 + " "; } } elem.className = jQuery.trim( cur ); } } } return this; }, removeClass: function( value ) { var classes, elem, cur, clazz, j, 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( core_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 + " ", " " ); } } elem.className = value ? jQuery.trim( cur ) : ""; } } } 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.match( core_rnotwhite ) || []; while ( (className = classNames[ i++ ]) ) { // check each className given, space separated list state = isBool ? state : !self.hasClass( className ); self[ state ? "addClass" : "removeClass" ]( className ); } // Toggle whole class name } else if ( type === core_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; }, val: function( value ) { var ret, hooks, 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 ) { // Use proper attribute retrieval(#6932, #12072) var val = jQuery.find.attr( elem, "value" ); return val != null ? val : elem.text; } }, select: { get: function( elem ) { var value, option, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one" || index < 0, values = one ? null : [], max = one ? index + 1 : options.length, i = index < 0 ? max : one ? index : 0; // 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 ( 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; }, set: function( elem, value ) { var optionSet, option, options = elem.options, values = jQuery.makeArray( value ), i = options.length; while ( i-- ) { option = options[ i ]; if ( (option.selected = jQuery.inArray( jQuery(option).val(), values ) >= 0) ) { optionSet = true; } } // force browsers to behave consistently when non-matching value is set if ( !optionSet ) { elem.selectedIndex = -1; } return values; } } }, 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 === core_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( core_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 ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to default in case type is set after value during creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } } }, 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; } } } }); // Hooks for boolean attributes boolHook = { set: function( elem, value, name ) { if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) { // IE<8 needs the *property* name elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name ); // Use defaultChecked and defaultSelected for oldIE } else { elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true; } return name; } }; jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { var getter = jQuery.expr.attrHandle[ name ] || jQuery.find.attr; jQuery.expr.attrHandle[ name ] = getSetInput && getSetAttribute || !ruseDefault.test( name ) ? function( elem, name, isXML ) { var fn = jQuery.expr.attrHandle[ name ], ret = isXML ? undefined : /* jshint eqeqeq: false */ (jQuery.expr.attrHandle[ name ] = undefined) != getter( elem, name, isXML ) ? name.toLowerCase() : null; jQuery.expr.attrHandle[ name ] = fn; return ret; } : function( elem, name, isXML ) { return isXML ? undefined : elem[ jQuery.camelCase( "default-" + name ) ] ? name.toLowerCase() : null; }; }); // 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) return name === "value" || value === elem.getAttribute( name ) ? value : undefined; } }; jQuery.expr.attrHandle.id = jQuery.expr.attrHandle.name = jQuery.expr.attrHandle.coords = // Some attributes are constructed with empty-string values when not defined function( elem, name, isXML ) { var ret; return isXML ? undefined : (ret = elem.getAttributeNode( name )) && ret.value !== "" ? ret.value : null; }; jQuery.valHooks.button = { get: function( elem, name ) { var ret = elem.getAttributeNode( name ); return ret && ret.specified ? ret.value : undefined; }, set: nodeHook.set }; // 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; } } }; }); } // Some attributes require a special call on IE // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !jQuery.support.hrefNormalized ) { // href/src property should get the full normalized URL (#10299/#12915) jQuery.each([ "href", "src" ], function( i, name ) { jQuery.propHooks[ name ] = { get: function( elem ) { return elem.getAttribute( name, 4 ); } }; }); } if ( !jQuery.support.style ) { jQuery.attrHooks.style = { get: function( elem ) { // Return undefined in the case of empty string // Note: IE uppercases css property names, but if we were to .toLowerCase() // .cssText, that would destroy case senstitivity in URL's, like in "background" return elem.style.cssText || undefined; }, set: function( elem, value ) { return ( elem.style.cssText = value + "" ); } }; } // Safari mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( !jQuery.support.optSelected ) { jQuery.propHooks.selected = { get: function( elem ) { var parent = elem.parentNode; 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 ( !jQuery.support.enctype ) { jQuery.propFix.enctype = "encoding"; } // Radios and checkboxes getter/setter jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }; if ( !jQuery.support.checkOn ) { jQuery.valHooks[ this ].get = function( elem ) { // Support: Webkit // "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; }; } }); var rformElems = /^(?:input|select|textarea)$/i, rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; function returnTrue() { return true; } function returnFalse() { return false; } 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 !== core_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( core_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( core_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 = core_hasOwn.call( event, "type" ) ? event.type : event, namespaces = core_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 && jQuery.acceptData( cur ) && handle.apply && 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( 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 = core_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 ) { // Even when returnValue equals to undefined Firefox will still show alert if ( event.result !== undefined ) { 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 ] === core_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.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; }; // 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() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); } }; // 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; // 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, "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 ( !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, "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 ( !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 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 ); } } }); var isSimple = /^.[^:#\[\.,]*$/, rparentsprev = /^(?:parents|prev(?:Until|All))/, rneedsContext = jQuery.expr.match.needsContext, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend({ find: function( selector ) { var i, ret = [], self = this, len = self.length; 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; }, 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 || [], true) ); }, filter: function( selector ) { return this.pushStack( winnow(this, selector || [], false) ); }, 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; }, 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++ ) { 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)) ) { cur = ret.push( cur ); break; } } } return this.pushStack( ret.length > 1 ? jQuery.unique( ret ) : ret ); }, // 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 ) { var set = typeof selector === "string" ? jQuery( selector, context ) : jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), all = jQuery.merge( this.get(), set ); return this.pushStack( jQuery.unique(all) ); }, 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 ); }; }); jQuery.extend({ 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; })); }, 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, 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 ( isSimple.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; }); } 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, manipulation_rcheckableType = /^(?:checkbox|radio)$/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: jQuery.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; 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 ); }, 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 ); } }); }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { var elem, elems = selector ? jQuery.filter( selector, this ) : this, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem ) ); } if ( elem.parentNode ) { if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { setGlobalEval( getAll( elem, "script" ) ); } elem.parentNode.removeChild( elem ); } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { // Remove element nodes and prevent memory leaks 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 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( 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 // Snapshot the DOM in case .domManip sweeps something relevant into its fragment args = jQuery.map( this, function( elem ) { return [ elem.nextSibling, elem.parentNode ]; }), i = 0; // Make the changes, replacing each context element with the new content this.domManip( arguments, function( elem ) { var next = args[ i++ ], parent = args[ i++ ]; if ( parent ) { // Don't use the snapshot next if it has moved (#13810) if ( next && next.parentNode !== parent ) { next = this.nextSibling; } jQuery( this ).remove(); parent.insertBefore( elem, next ); } // Allow new content to include elements from the context set }, true ); // Force removal if there was no new content (e.g., from empty arguments) return i ? this : this.remove(); }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, callback, allowIntersection ) { // Flatten any nested arrays args = core_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" || jQuery.support.checkClone || !rchecked.test( value ) ) ) { return this.each(function( index ) { var self = set.eq( index ); if ( isFunction ) { args[0] = value.call( this, index, self.html() ); } self.domManip( args, callback, allowIntersection ); }); } if ( l ) { fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, !allowIntersection && 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 ) { // Hope ajax is available... 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; } }); // Support: IE<8 // Manipulating tables requires a tbody function manipulationTarget( elem, content ) { return jQuery.nodeName( elem, "table" ) && jQuery.nodeName( content.nodeType === 1 ? 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 ( !jQuery.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 ( jQuery.support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) { dest.innerHTML = src.innerHTML; } } else if ( nodeName === "input" && manipulation_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.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() core_push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; }); function getAll( context, tag ) { var elems, elem, i = 0, found = typeof context.getElementsByTagName !== core_strundefined ? context.getElementsByTagName( tag || "*" ) : typeof context.querySelectorAll !== core_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 ( manipulation_rcheckableType.test( elem.type ) ) { elem.defaultChecked = elem.checked; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var destElements, node, clone, i, srcElements, inPage = jQuery.contains( elem.ownerDocument, elem ); 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) ) { // 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 ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) ); } // Remove IE's autoinserted <tbody> from table fragments if ( !jQuery.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 ( !jQuery.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 = 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 ( typeof elem.removeAttribute !== core_strundefined ) { elem.removeAttribute( internalKey ); } else { elem[ internalKey ] = null; } core_deletedIds.push( id ); } } } } }, _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(); } }); var iframe, getStyles, curCSS, ralpha = /alpha\([^)]*\)/i, ropacity = /opacity\s*=\s*([^)]*)/, 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 = { BODY: "block" }, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: 0, fontWeight: 400 }, cssExpand = [ "Top", "Right", "Bottom", "Left" ], 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 isHidden( 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 ); } 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", css_defaultDisplay(elem.nodeName) ); } } else { if ( !values[ index ] ) { 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; } jQuery.fn.extend({ css: function( name, value ) { return jQuery.access( this, function( elem, name, value ) { var len, styles, 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 ) { var bool = typeof state === "boolean"; 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; } } } }, // Don't automatically add "px" to these possibly-unitless properties cssNumber: { "columnCount": true, "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"; } // 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 ( !jQuery.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 ) { // 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, 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; } }); // NOTE: we've included the "window" in window.getComputedStyle // because jsdom on node.js will break without it. if ( window.getComputedStyle ) { getStyles = function( elem ) { return window.getComputedStyle( elem, null ); }; curCSS = function( elem, name, _computed ) { var width, minWidth, maxWidth, computed = _computed || getStyles( elem ), // getPropertyValue is only needed for .css('filter') in IE9, see #12537 ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined, style = elem.style; 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; } } return ret; }; } else if ( document.documentElement.currentStyle ) { getStyles = function( elem ) { return elem.currentStyle; }; curCSS = function( elem, name, _computed ) { var left, rs, rsLeft, computed = _computed || getStyles( elem ), ret = computed ? computed[ name ] : undefined, 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; 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; } } return ret === "" ? "auto" : ret; }; } 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 = jQuery.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 && ( 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, styles ) ) + "px"; } // Try to determine the default display value of an element function css_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'/>") .css( "cssText", "display:block !important" ) ).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; doc.write("<!doctype html><html><body>"); doc.close(); display = actualDisplay( nodeName, doc ); iframe.detach(); } // Store the correct default display elemdisplay[ nodeName ] = display; } return display; } // Called ONLY from within css_defaultDisplay function actualDisplay( name, doc ) { var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), display = jQuery.css( elem[0], "display" ); elem.remove(); 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 return elem.offsetWidth === 0 && rdisplayswap.test( jQuery.css( elem, "display" ) ) ? 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, jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box", styles ) : 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 === "", 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; } }; } // 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 ) { 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" ] ); } } }; } // 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 ) { computed = curCSS( elem, prop ); // if curCSS returns percentage, fallback to offset return rnumnonpx.test( computed ) ? jQuery( elem ).position()[ prop ] + "px" : computed; } } }; }); } }); if ( jQuery.expr && jQuery.expr.filters ) { 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 || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none"); }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; } // These hooks are used by animate to expand properties jQuery.each({ margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i = 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; } }); var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; 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 || !manipulation_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(); } }); //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 { // 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 ); } } 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 // Document location ajaxLocParts, ajaxLocation, ajax_nonce = jQuery.now(), ajax_rquery = /\?/, 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+)|)|)/, // 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 = "*/".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( core_rnotwhite ) || []; if ( jQuery.isFunction( func ) ) { // For each dataType in the dataTypeExpression while ( (dataType = dataTypes[i++]) ) { // Prepend if requested if ( dataType[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; } 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 = 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.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( core_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 fireGlobals = 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 += ( ajax_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_=" + ajax_nonce++ ) : // Otherwise add one to the end cacheURL + ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ajax_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 }); }; }); /* 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 }; } // 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 + "_" + ( ajax_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 += ( ajax_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"; } }); var xhrCallbacks, xhrSupported, xhrId = 0, // #5280: Internet Explorer will keep connections alive if we don't abort on unload xhrOnUnloadAbort = window.ActiveXObject && function() { // Abort all pending requests var key; for ( key in xhrCallbacks ) { xhrCallbacks[ key ]( 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 ) {} } // 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 xhrSupported = jQuery.ajaxSettings.xhr(); jQuery.support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); xhrSupported = jQuery.support.ajax = !!xhrSupported; // Create transport if the browser can provide an xhr if ( xhrSupported ) { 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( err ) {} // 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, responseHeaders, statusText, responses; // 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 { responses = {}; status = xhr.status; responseHeaders = xhr.getAllResponseHeaders(); // When requesting binary data, IE6-9 will throw an exception // on any attempt to access responseText (#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 && 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 ); } 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( undefined, true ); } } }; } }); } var fxNow, timerId, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = new RegExp( "^(?:([+-])=|)(" + core_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() ); } 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 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 ); } 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 ) { /* jshint validthis: true */ var prop, value, toggle, tween, hooks, oldfire, 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 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.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" ) ) { continue; } orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop ); } } 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; } } } } } 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.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 ); }; }); 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; }); } }); // 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; 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 ) { if ( timer() && jQuery.timers.push( timer ) ) { jQuery.fx.start(); } }; 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 }; // 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; }; } jQuery.fn.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 !== core_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 ) }; }; jQuery.offset = { 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 offsetParent, offset, parentOffset = { top: 0, left: 0 }, elem = this[ 0 ]; // fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is it's 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 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, extra ) : // Set width or height on the element jQuery.style( elem, type, value, extra ); }, type, chainable ? margin : undefined, chainable, null ); }; }); }); // Limit scope pollution from any deprecated API // (function() { // The number of elements contained in the matched element set jQuery.fn.size = function() { return this.length; }; jQuery.fn.andSelf = jQuery.fn.addBack; // })(); if ( typeof module === "object" && module && typeof module.exports === "object" ) { // Expose jQuery as module.exports in loaders that implement the Node // module pattern (including browserify). Do not create the global, since // the user will be storing it themselves locally, and globals are frowned // upon in the Node module world. module.exports = jQuery; } else { // Otherwise expose jQuery to the global object as usual window.jQuery = window.$ = jQuery; // 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. if ( typeof define === "function" && define.amd ) { define( "jquery", [], function () { return jQuery; } ); } } })( window );
ajax/libs/styled-components/4.0.0-beta.4/styled-components.js
cdnjs/cdnjs
var styled = (function (React) { 'use strict'; var React__default = 'default' in React ? React['default'] : React; function unwrapExports (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } var stylis_min = createCommonjsModule(function (module, exports) { !function(e){module.exports=e(null);}(function e(a){var c=/^\0+/g,r=/[\0\r\f]/g,s=/: */g,t=/zoo|gra/,i=/([,: ])(transform)/g,f=/,+\s*(?![^(]*[)])/g,n=/ +\s*(?![^(]*[)])/g,l=/ *[\0] */g,o=/,\r+?/g,h=/([\t\r\n ])*\f?&/g,u=/:global\(((?:[^\(\)\[\]]*|\[.*\]|\([^\(\)]*\))*)\)/g,d=/\W+/g,b=/@(k\w+)\s*(\S*)\s*/,k=/::(place)/g,p=/:(read-only)/g,g=/\s+(?=[{\];=:>])/g,A=/([[}=:>])\s+/g,C=/(\{[^{]+?);(?=\})/g,w=/\s{2,}/g,v=/([^\(])(:+) */g,m=/[svh]\w+-[tblr]{2}/,x=/\(\s*(.*)\s*\)/g,$=/([\s\S]*?);/g,y=/-self|flex-/g,O=/[^]*?(:[rp][el]a[\w-]+)[^]*/,j=/stretch|:\s*\w+\-(?:conte|avail)/,z=/([^-])(image-set\()/,F="-webkit-",N="-moz-",S="-ms-",B=59,W=125,q=123,D=40,E=41,G=91,H=93,I=10,J=13,K=9,L=64,M=32,P=38,Q=45,R=95,T=42,U=44,V=58,X=39,Y=34,Z=47,_=62,ee=43,ae=126,ce=0,re=12,se=11,te=107,ie=109,fe=115,ne=112,le=111,oe=105,he=99,ue=100,de=112,be=1,ke=1,pe=0,ge=1,Ae=1,Ce=1,we=0,ve=0,me=0,xe=[],$e=[],ye=0,Oe=null,je=-2,ze=-1,Fe=0,Ne=1,Se=2,Be=3,We=0,qe=1,De="",Ee="",Ge="";function He(e,a,s,t,i){for(var f,n,o=0,h=0,u=0,d=0,g=0,A=0,C=0,w=0,m=0,$=0,y=0,O=0,j=0,z=0,R=0,we=0,$e=0,Oe=0,je=0,ze=s.length,Je=ze-1,Re="",Te="",Ue="",Ve="",Xe="",Ye="";R<ze;){if(C=s.charCodeAt(R),R===Je)if(h+d+u+o!==0){if(0!==h)C=h===Z?I:Z;d=u=o=0,ze++,Je++;}if(h+d+u+o===0){if(R===Je){if(we>0)Te=Te.replace(r,"");if(Te.trim().length>0){switch(C){case M:case K:case B:case J:case I:break;default:Te+=s.charAt(R);}C=B;}}if(1===$e)switch(C){case q:case W:case B:case Y:case X:case D:case E:case U:$e=0;case K:case J:case I:case M:break;default:for($e=0,je=R,g=C,R--,C=B;je<ze;)switch(s.charCodeAt(je++)){case I:case J:case B:++R,C=g,je=ze;break;case V:if(we>0)++R,C=g;case q:je=ze;}}switch(C){case q:for(g=(Te=Te.trim()).charCodeAt(0),y=1,je=++R;R<ze;){switch(C=s.charCodeAt(R)){case q:y++;break;case W:y--;break;case Z:switch(A=s.charCodeAt(R+1)){case T:case Z:R=Qe(A,R,Je,s);}break;case G:C++;case D:C++;case Y:case X:for(;R++<Je&&s.charCodeAt(R)!==C;);}if(0===y)break;R++;}if(Ue=s.substring(je,R),g===ce)g=(Te=Te.replace(c,"").trim()).charCodeAt(0);switch(g){case L:if(we>0)Te=Te.replace(r,"");switch(A=Te.charCodeAt(1)){case ue:case ie:case fe:case Q:f=a;break;default:f=xe;}if(je=(Ue=He(a,f,Ue,A,i+1)).length,me>0&&0===je)je=Te.length;if(ye>0)if(f=Ie(xe,Te,Oe),n=Pe(Be,Ue,f,a,ke,be,je,A,i,t),Te=f.join(""),void 0!==n)if(0===(je=(Ue=n.trim()).length))A=0,Ue="";if(je>0)switch(A){case fe:Te=Te.replace(x,Me);case ue:case ie:case Q:Ue=Te+"{"+Ue+"}";break;case te:if(Ue=(Te=Te.replace(b,"$1 $2"+(qe>0?De:"")))+"{"+Ue+"}",1===Ae||2===Ae&&Le("@"+Ue,3))Ue="@"+F+Ue+"@"+Ue;else Ue="@"+Ue;break;default:if(Ue=Te+Ue,t===de)Ve+=Ue,Ue="";}else Ue="";break;default:Ue=He(a,Ie(a,Te,Oe),Ue,t,i+1);}Xe+=Ue,O=0,$e=0,z=0,we=0,Oe=0,j=0,Te="",Ue="",C=s.charCodeAt(++R);break;case W:case B:if((je=(Te=(we>0?Te.replace(r,""):Te).trim()).length)>1){if(0===z)if((g=Te.charCodeAt(0))===Q||g>96&&g<123)je=(Te=Te.replace(" ",":")).length;if(ye>0)if(void 0!==(n=Pe(Ne,Te,a,e,ke,be,Ve.length,t,i,t)))if(0===(je=(Te=n.trim()).length))Te="\0\0";switch(g=Te.charCodeAt(0),A=Te.charCodeAt(1),g){case ce:break;case L:if(A===oe||A===he){Ye+=Te+s.charAt(R);break}default:if(Te.charCodeAt(je-1)===V)break;Ve+=Ke(Te,g,A,Te.charCodeAt(2));}}O=0,$e=0,z=0,we=0,Oe=0,Te="",C=s.charCodeAt(++R);}}switch(C){case J:case I:if(h+d+u+o+ve===0)switch($){case E:case X:case Y:case L:case ae:case _:case T:case ee:case Z:case Q:case V:case U:case B:case q:case W:break;default:if(z>0)$e=1;}if(h===Z)h=0;else if(ge+O===0&&t!==te&&Te.length>0)we=1,Te+="\0";if(ye*We>0)Pe(Fe,Te,a,e,ke,be,Ve.length,t,i,t);be=1,ke++;break;case B:case W:if(h+d+u+o===0){be++;break}default:switch(be++,Re=s.charAt(R),C){case K:case M:if(d+o+h===0)switch(w){case U:case V:case K:case M:Re="";break;default:if(C!==M)Re=" ";}break;case ce:Re="\\0";break;case re:Re="\\f";break;case se:Re="\\v";break;case P:if(d+h+o===0&&ge>0)Oe=1,we=1,Re="\f"+Re;break;case 108:if(d+h+o+pe===0&&z>0)switch(R-z){case 2:if(w===ne&&s.charCodeAt(R-3)===V)pe=w;case 8:if(m===le)pe=m;}break;case V:if(d+h+o===0)z=R;break;case U:if(h+u+d+o===0)we=1,Re+="\r";break;case Y:case X:if(0===h)d=d===C?0:0===d?C:d;break;case G:if(d+h+u===0)o++;break;case H:if(d+h+u===0)o--;break;case E:if(d+h+o===0)u--;break;case D:if(d+h+o===0){if(0===O)switch(2*w+3*m){case 533:break;default:y=0,O=1;}u++;}break;case L:if(h+u+d+o+z+j===0)j=1;break;case T:case Z:if(d+o+u>0)break;switch(h){case 0:switch(2*C+3*s.charCodeAt(R+1)){case 235:h=Z;break;case 220:je=R,h=T;}break;case T:if(C===Z&&w===T&&je+2!==R){if(33===s.charCodeAt(je+2))Ve+=s.substring(je,R+1);Re="",h=0;}}}if(0===h){if(ge+d+o+j===0&&t!==te&&C!==B)switch(C){case U:case ae:case _:case ee:case E:case D:if(0===O){switch(w){case K:case M:case I:case J:Re+="\0";break;default:Re="\0"+Re+(C===U?"":"\0");}we=1;}else switch(C){case D:if(z+7===R&&108===w)z=0;O=++y;break;case E:if(0==(O=--y))we=1,Re+="\0";}break;case K:case M:switch(w){case ce:case q:case W:case B:case U:case re:case K:case M:case I:case J:break;default:if(0===O)we=1,Re+="\0";}}if(Te+=Re,C!==M&&C!==K)$=C;}}m=w,w=C,R++;}if(je=Ve.length,me>0)if(0===je&&0===Xe.length&&0===a[0].length==false)if(t!==ie||1===a.length&&(ge>0?Ee:Ge)===a[0])je=a.join(",").length+2;if(je>0){if(f=0===ge&&t!==te?function(e){for(var a,c,s=0,t=e.length,i=Array(t);s<t;++s){for(var f=e[s].split(l),n="",o=0,h=0,u=0,d=0,b=f.length;o<b;++o){if(0===(h=(c=f[o]).length)&&b>1)continue;if(u=n.charCodeAt(n.length-1),d=c.charCodeAt(0),a="",0!==o)switch(u){case T:case ae:case _:case ee:case M:case D:break;default:a=" ";}switch(d){case P:c=a+Ee;case ae:case _:case ee:case M:case E:case D:break;case G:c=a+c+Ee;break;case V:switch(2*c.charCodeAt(1)+3*c.charCodeAt(2)){case 530:if(Ce>0){c=a+c.substring(8,h-1);break}default:if(o<1||f[o-1].length<1)c=a+Ee+c;}break;case U:a="";default:if(h>1&&c.indexOf(":")>0)c=a+c.replace(v,"$1"+Ee+"$2");else c=a+c+Ee;}n+=c;}i[s]=n.replace(r,"").trim();}return i}(a):a,ye>0)if(void 0!==(n=Pe(Se,Ve,f,e,ke,be,je,t,i,t))&&0===(Ve=n).length)return Ye+Ve+Xe;if(Ve=f.join(",")+"{"+Ve+"}",Ae*pe!=0){if(2===Ae&&!Le(Ve,2))pe=0;switch(pe){case le:Ve=Ve.replace(p,":"+N+"$1")+Ve;break;case ne:Ve=Ve.replace(k,"::"+F+"input-$1")+Ve.replace(k,"::"+N+"$1")+Ve.replace(k,":"+S+"input-$1")+Ve;}pe=0;}}return Ye+Ve+Xe}function Ie(e,a,c){var r=a.trim().split(o),s=r,t=r.length,i=e.length;switch(i){case 0:case 1:for(var f=0,n=0===i?"":e[0]+" ";f<t;++f)s[f]=Je(n,s[f],c,i).trim();break;default:f=0;var l=0;for(s=[];f<t;++f)for(var h=0;h<i;++h)s[l++]=Je(e[h]+" ",r[f],c,i).trim();}return s}function Je(e,a,c,r){var s=a,t=s.charCodeAt(0);if(t<33)t=(s=s.trim()).charCodeAt(0);switch(t){case P:switch(ge+r){case 0:case 1:if(0===e.trim().length)break;default:return s.replace(h,"$1"+e.trim())}break;case V:switch(s.charCodeAt(1)){case 103:if(Ce>0&&ge>0)return s.replace(u,"$1").replace(h,"$1"+Ge);break;default:return e.trim()+s.replace(h,"$1"+e.trim())}default:if(c*ge>0&&s.indexOf("\f")>0)return s.replace(h,(e.charCodeAt(0)===V?"":"$1")+e.trim())}return e+s}function Ke(e,a,c,r){var l,o=0,h=e+";",u=2*a+3*c+4*r;if(944===u)return function(e){var a=e.length,c=e.indexOf(":",9)+1,r=e.substring(0,c).trim(),s=e.substring(c,a-1).trim();switch(e.charCodeAt(9)*qe){case 0:break;case Q:if(110!==e.charCodeAt(10))break;default:for(var t=s.split((s="",f)),i=0,c=0,a=t.length;i<a;c=0,++i){for(var l=t[i],o=l.split(n);l=o[c];){var h=l.charCodeAt(0);if(1===qe&&(h>L&&h<90||h>96&&h<123||h===R||h===Q&&l.charCodeAt(1)!==Q))switch(isNaN(parseFloat(l))+(-1!==l.indexOf("("))){case 1:switch(l){case"infinite":case"alternate":case"backwards":case"running":case"normal":case"forwards":case"both":case"none":case"linear":case"ease":case"ease-in":case"ease-out":case"ease-in-out":case"paused":case"reverse":case"alternate-reverse":case"inherit":case"initial":case"unset":case"step-start":case"step-end":break;default:l+=De;}}o[c++]=l;}s+=(0===i?"":",")+o.join(" ");}}if(s=r+s+";",1===Ae||2===Ae&&Le(s,1))return F+s+s;return s}(h);else if(0===Ae||2===Ae&&!Le(h,1))return h;switch(u){case 1015:return 97===h.charCodeAt(10)?F+h+h:h;case 951:return 116===h.charCodeAt(3)?F+h+h:h;case 963:return 110===h.charCodeAt(5)?F+h+h:h;case 1009:if(100!==h.charCodeAt(4))break;case 969:case 942:return F+h+h;case 978:return F+h+N+h+h;case 1019:case 983:return F+h+N+h+S+h+h;case 883:if(h.charCodeAt(8)===Q)return F+h+h;if(h.indexOf("image-set(",11)>0)return h.replace(z,"$1"+F+"$2")+h;return h;case 932:if(h.charCodeAt(4)===Q)switch(h.charCodeAt(5)){case 103:return F+"box-"+h.replace("-grow","")+F+h+S+h.replace("grow","positive")+h;case 115:return F+h+S+h.replace("shrink","negative")+h;case 98:return F+h+S+h.replace("basis","preferred-size")+h}return F+h+S+h+h;case 964:return F+h+S+"flex-"+h+h;case 1023:if(99!==h.charCodeAt(8))break;return l=h.substring(h.indexOf(":",15)).replace("flex-","").replace("space-between","justify"),F+"box-pack"+l+F+h+S+"flex-pack"+l+h;case 1005:return t.test(h)?h.replace(s,":"+F)+h.replace(s,":"+N)+h:h;case 1e3:switch(o=(l=h.substring(13).trim()).indexOf("-")+1,l.charCodeAt(0)+l.charCodeAt(o)){case 226:l=h.replace(m,"tb");break;case 232:l=h.replace(m,"tb-rl");break;case 220:l=h.replace(m,"lr");break;default:return h}return F+h+S+l+h;case 1017:if(-1===h.indexOf("sticky",9))return h;case 975:switch(o=(h=e).length-10,u=(l=(33===h.charCodeAt(o)?h.substring(0,o):h).substring(e.indexOf(":",7)+1).trim()).charCodeAt(0)+(0|l.charCodeAt(7))){case 203:if(l.charCodeAt(8)<111)break;case 115:h=h.replace(l,F+l)+";"+h;break;case 207:case 102:h=h.replace(l,F+(u>102?"inline-":"")+"box")+";"+h.replace(l,F+l)+";"+h.replace(l,S+l+"box")+";"+h;}return h+";";case 938:if(h.charCodeAt(5)===Q)switch(h.charCodeAt(6)){case 105:return l=h.replace("-items",""),F+h+F+"box-"+l+S+"flex-"+l+h;case 115:return F+h+S+"flex-item-"+h.replace(y,"")+h;default:return F+h+S+"flex-line-pack"+h.replace("align-content","").replace(y,"")+h}break;case 973:case 989:if(h.charCodeAt(3)!==Q||122===h.charCodeAt(4))break;case 931:case 953:if(true===j.test(e))if(115===(l=e.substring(e.indexOf(":")+1)).charCodeAt(0))return Ke(e.replace("stretch","fill-available"),a,c,r).replace(":fill-available",":stretch");else return h.replace(l,F+l)+h.replace(l,N+l.replace("fill-",""))+h;break;case 962:if(h=F+h+(102===h.charCodeAt(5)?S+h:"")+h,c+r===211&&105===h.charCodeAt(13)&&h.indexOf("transform",10)>0)return h.substring(0,h.indexOf(";",27)+1).replace(i,"$1"+F+"$2")+h}return h}function Le(e,a){var c=e.indexOf(1===a?":":"{"),r=e.substring(0,3!==a?c:10),s=e.substring(c+1,e.length-1);return Oe(2!==a?r:r.replace(O,"$1"),s,a)}function Me(e,a){var c=Ke(a,a.charCodeAt(0),a.charCodeAt(1),a.charCodeAt(2));return c!==a+";"?c.replace($," or ($1)").substring(4):"("+a+")"}function Pe(e,a,c,r,s,t,i,f,n,l){for(var o,h=0,u=a;h<ye;++h)switch(o=$e[h].call(Te,e,u,c,r,s,t,i,f,n,l)){case void 0:case false:case true:case null:break;default:u=o;}switch(u){case void 0:case false:case true:case null:case a:break;default:return u}}function Qe(e,a,c,r){for(var s=a+1;s<c;++s)switch(r.charCodeAt(s)){case Z:if(e===T)if(r.charCodeAt(s-1)===T&&a+2!==s)return s+1;break;case I:if(e===Z)return s+1}return s}function Re(e){for(var a in e){var c=e[a];switch(a){case"keyframe":qe=0|c;break;case"global":Ce=0|c;break;case"cascade":ge=0|c;break;case"compress":we=0|c;break;case"semicolon":ve=0|c;break;case"preserve":me=0|c;break;case"prefix":if(Oe=null,!c)Ae=0;else if("function"!=typeof c)Ae=1;else Ae=2,Oe=c;}}return Re}function Te(a,c){if(void 0!==this&&this.constructor===Te)return e(a);var s=a,t=s.charCodeAt(0);if(t<33)t=(s=s.trim()).charCodeAt(0);if(qe>0)De=s.replace(d,t===G?"":"-");if(t=1,1===ge)Ge=s;else Ee=s;var i,f=[Ge];if(ye>0)if(void 0!==(i=Pe(ze,c,f,f,ke,be,0,0,0,0))&&"string"==typeof i)c=i;var n=He(xe,f,c,0,0);if(ye>0)if(void 0!==(i=Pe(je,n,f,f,ke,be,n.length,0,0,0))&&"string"!=typeof(n=i))t=0;return De="",Ge="",Ee="",pe=0,ke=1,be=1,we*t==0?n:n.replace(r,"").replace(g,"").replace(A,"$1").replace(C,"$1").replace(w," ")}if(Te.use=function e(a){switch(a){case void 0:case null:ye=$e.length=0;break;default:switch(a.constructor){case Array:for(var c=0,r=a.length;c<r;++c)e(a[c]);break;case Function:$e[ye++]=a;break;case Boolean:We=0|!!a;}}return e},Te.set=Re,void 0!==a)Re(a);return Te}); }); var stylisRuleSheet = createCommonjsModule(function (module, exports) { (function (factory) { module['exports'] = factory(); }(function () { return function (insertRule) { var delimiter = '/*|*/'; var needle = delimiter+'}'; function toSheet (block) { if (block) try { insertRule(block + '}'); } catch (e) {} } return function ruleSheet (context, content, selectors, parents, line, column, length, ns, depth, at) { switch (context) { // property case 1: // @import if (depth === 0 && content.charCodeAt(0) === 64) return insertRule(content+';'), '' break // selector case 2: if (ns === 0) return content + delimiter break // at-rule case 3: switch (ns) { // @font-face, @page case 102: case 112: return insertRule(selectors[0]+content), '' default: return content + (at === 0 ? delimiter : '') } case -2: content.split(needle).forEach(toSheet); } } } })); }); // var COMMENT_REGEX = /^\s*\/\/.*$/gm; // NOTE: This stylis instance is only used to split rules from SSR'd style tags var stylisSplitter = new stylis_min({ global: false, cascade: true, keyframe: false, prefix: false, compress: false, semicolon: true }); var stylis = new stylis_min({ global: false, cascade: true, keyframe: false, prefix: true, compress: false, semicolon: false // NOTE: This means "autocomplete missing semicolons" }); // Wrap `insertRulePlugin to build a list of rules, // and then make our own plugin to return the rules. This // makes it easier to hook into the existing SSR architecture var parsingRules = []; // eslint-disable-next-line consistent-return var returnRulesPlugin = function returnRulesPlugin(context) { if (context === -2) { var parsedRules = parsingRules; parsingRules = []; return parsedRules; } }; var parseRulesPlugin = stylisRuleSheet(function (rule) { parsingRules.push(rule); }); stylis.use([parseRulesPlugin, returnRulesPlugin]); stylisSplitter.use([parseRulesPlugin, returnRulesPlugin]); var stringifyRules = function stringifyRules(rules, selector, prefix) { var flatCSS = rules.join('').replace(COMMENT_REGEX, ''); // replace JS comments var cssStr = selector && prefix ? prefix + ' ' + selector + ' { ' + flatCSS + ' }' : flatCSS; return stylis(prefix || !selector ? '' : selector, cssStr); }; var splitByRules = function splitByRules(css) { return stylisSplitter('', css); }; // function isStyledComponent(target) { return target && typeof target.styledComponentId === 'string'; } // /* eslint-disable no-bitwise */ /* This is the "capacity" of our alphabet i.e. 2x26 for all letters plus their capitalised * counterparts */ var charsLength = 52; /* start at 75 for 'a' until 'z' (25) and then start at 65 for capitalised letters */ var getAlphabeticChar = function getAlphabeticChar(code) { return String.fromCharCode(code + (code > 25 ? 39 : 97)); }; /* input a number, usually a hash and convert it to base-52 */ function generateAlphabeticName(code) { var name = ''; var x = void 0; /* get a char and divide by alphabet-length */ for (x = code; x > charsLength; x = Math.floor(x / charsLength)) { name = getAlphabeticChar(x % charsLength) + name; } return getAlphabeticChar(x % charsLength) + name; } // var interleave = (function (strings, interpolations) { var result = [strings[0]]; for (var i = 0, len = interpolations.length; i < len; i += 1) { result.push(interpolations[i], strings[i + 1]); } return result; }); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; var createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; var objectWithoutProperties = function (obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }; var possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; // var isPlainObject = (function (x) { return (typeof x === 'undefined' ? 'undefined' : _typeof(x)) === 'object' && x.constructor === Object; }); // var EMPTY_ARRAY = Object.freeze([]); var EMPTY_OBJECT = Object.freeze({}); // function isFunction(test) { return typeof test === 'function'; } // /** * inlined version of * https://github.com/facebook/fbjs/blob/master/packages/fbjs/src/core/hyphenateStyleName.js */ var uppercasePattern = /([A-Z])/g; var msPattern = /^ms-/; /** * Hyphenates a camelcased CSS property name, for example: * * > hyphenateStyleName('backgroundColor') * < "background-color" * > hyphenateStyleName('MozTransition') * < "-moz-transition" * > hyphenateStyleName('msTransition') * < "-ms-transition" * * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix * is converted to `-ms-`. * * @param {string} string * @return {string} */ function hyphenateStyleName(string) { return string.replace(uppercasePattern, '-$1').toLowerCase().replace(msPattern, '-ms-'); } // var SC_ATTR = typeof process !== 'undefined' && process.env.SC_ATTR || 'data-styled'; var SC_VERSION_ATTR = 'data-styled-version'; var SC_STREAM_ATTR = 'data-styled-streamed'; var IS_BROWSER = typeof window !== 'undefined' && 'HTMLElement' in window; // Shared empty execution context when generating static styles var STATIC_EXECUTION_CONTEXT = {}; // /** * Parse errors.md and turn it into a simple hash of code: message */ var ERRORS = { "1": "Cannot create styled-component for component: %s.\n\n", "2": "Can't collect styles once you've consumed a `ServerStyleSheet`'s styles! `ServerStyleSheet` is a one off instance for each server-side render cycle.\n\n- Are you trying to reuse it across renders?\n- Are you accidentally calling collectStyles twice?\n\n", "3": "Streaming SSR is only supported in a Node.js environment; Please do not try to call this method in the browser.\n\n", "4": "The `StyleSheetManager` expects a valid target or sheet prop!\n\n- Does this error occur on the client and is your target falsy?\n- Does this error occur on the server and is the sheet falsy?\n\n", "5": "The clone method cannot be used on the client!\n\n- Are you running in a client-like environment on the server?\n- Are you trying to run SSR on the client?\n\n", "6": "Trying to insert a new style tag, but the given Node is unmounted!\n\n- Are you using a custom target that isn't mounted?\n- Does your document not have a valid head element?\n- Have you accidentally removed a style tag manually?\n\n", "7": "ThemeProvider: Please return an object from your \"theme\" prop function, e.g.\n\n```js\ntheme={() => ({})}\n```\n\n", "8": "ThemeProvider: Please make your \"theme\" prop an object.\n\n", "9": "Missing document `<head>`\n\n", "10": "Cannot find sheet for given tag\n\n", "11": "[createGlobalStyle] received children which will not be rendered. Please use the component without passing children elements.\n" }; /** * super basic version of sprintf */ function format() { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var a = args[0]; var b = []; var c = void 0; for (c = 1; c < args.length; c += 1) { b.push(args[c]); } b.forEach(function (d) { a = a.replace(/%[a-z]/, d); }); return a; } /** * Create an error file out of errors.md for development and a simple web link to the full errors * in production mode. */ var StyledComponentsError = function (_Error) { inherits(StyledComponentsError, _Error); function StyledComponentsError(code) { classCallCheck(this, StyledComponentsError); for (var _len2 = arguments.length, interpolations = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { interpolations[_key2 - 1] = arguments[_key2]; } if (false) { var _this; } else { var _this = possibleConstructorReturn(this, _Error.call(this, format.apply(undefined, [ERRORS[code]].concat(interpolations)).trim())); } return possibleConstructorReturn(_this); } return StyledComponentsError; }(Error); // var SC_COMPONENT_ID = /^[^\S\n]*?\/\* sc-component-id:\s*(\S+)\s+\*\//gm; var extractComps = (function (maybeCSS) { var css = '' + (maybeCSS || ''); // Definitely a string, and a clone var existingComponents = []; css.replace(SC_COMPONENT_ID, function (match, componentId, matchIndex) { existingComponents.push({ componentId: componentId, matchIndex: matchIndex }); return match; }); return existingComponents.map(function (_ref, i) { var componentId = _ref.componentId, matchIndex = _ref.matchIndex; var nextComp = existingComponents[i + 1]; var cssFromDOM = nextComp ? css.slice(matchIndex, nextComp.matchIndex) : css.slice(matchIndex); return { componentId: componentId, cssFromDOM: cssFromDOM }; }); }); // /* eslint-disable camelcase, no-undef */ var getNonce = (function () { return typeof __webpack_nonce__ !== 'undefined' ? __webpack_nonce__ : null; }); // // Helper to call a given function, only once var once = (function (cb) { var called = false; return function () { if (!called) { called = true; cb(); } }; }); // /* These are helpers for the StyleTags to keep track of the injected * rule names for each (component) ID that they're keeping track of. * They're crucial for detecting whether a name has already been * injected. * (This excludes rehydrated names) */ /* adds a new ID:name pairing to a names dictionary */ var addNameForId = function addNameForId(names, id, name) { if (name) { // eslint-disable-next-line no-param-reassign var namesForId = names[id] || (names[id] = Object.create(null)); namesForId[name] = true; } }; /* resets an ID entirely by overwriting it in the dictionary */ var resetIdNames = function resetIdNames(names, id) { // eslint-disable-next-line no-param-reassign names[id] = Object.create(null); }; /* factory for a names dictionary checking the existance of an ID:name pairing */ var hasNameForId = function hasNameForId(names) { return function (id, name) { return names[id] !== undefined && names[id][name]; }; }; /* stringifies names for the html/element output */ var stringifyNames = function stringifyNames(names) { var str = ''; // eslint-disable-next-line guard-for-in for (var id in names) { str += Object.keys(names[id]).join(' ') + ' '; } return str.trim(); }; /* clones the nested names dictionary */ var cloneNames = function cloneNames(names) { var clone = Object.create(null); // eslint-disable-next-line guard-for-in for (var id in names) { clone[id] = _extends({}, names[id]); } return clone; }; // // /* this marker separates component styles and is important for rehydration */ var makeTextMarker = function makeTextMarker(id) { return '\n/* sc-component-id: ' + id + ' */\n'; }; /* create a new style tag after lastEl */ var makeStyleTag = function makeStyleTag(target, tagEl, insertBefore) { var el = document.createElement('style'); el.setAttribute(SC_ATTR, ''); el.setAttribute(SC_VERSION_ATTR, "4.0.0-beta.4"); var nonce = getNonce(); if (nonce) { el.setAttribute('nonce', nonce); } /* Work around insertRule quirk in EdgeHTML */ el.appendChild(document.createTextNode('')); if (target && !tagEl) { /* Append to target when no previous element was passed */ target.appendChild(el); } else { if (!tagEl || !target || !tagEl.parentNode) { throw new StyledComponentsError(6); } /* Insert new style tag after the previous one */ tagEl.parentNode.insertBefore(el, insertBefore ? tagEl : tagEl.nextSibling); } return el; }; /* takes a css factory function and outputs an html styled tag factory */ var wrapAsHtmlTag = function wrapAsHtmlTag(css, names) { return function (additionalAttrs) { var nonce = getNonce(); var attrs = [nonce && 'nonce="' + nonce + '"', SC_ATTR + '="' + stringifyNames(names) + '"', SC_VERSION_ATTR + '="' + "4.0.0-beta.4" + '"', additionalAttrs]; var htmlAttr = attrs.filter(Boolean).join(' '); return '<style ' + htmlAttr + '>' + css() + '</style>'; }; }; /* takes a css factory function and outputs an element factory */ var wrapAsElement = function wrapAsElement(css, names) { return function () { var _props; var props = (_props = {}, _props[SC_ATTR] = stringifyNames(names), _props[SC_VERSION_ATTR] = "4.0.0-beta.4", _props); var nonce = getNonce(); if (nonce) { // $FlowFixMe props.nonce = nonce; } // eslint-disable-next-line react/no-danger return React__default.createElement('style', _extends({}, props, { dangerouslySetInnerHTML: { __html: css() } })); }; }; var getIdsFromMarkersFactory = function getIdsFromMarkersFactory(markers) { return function () { return Object.keys(markers); }; }; var makeTextNode = function makeTextNode(id) { return document.createTextNode(makeTextMarker(id)); }; var makeBrowserTag = function makeBrowserTag(el, getImportRuleTag) { var names = Object.create(null); var markers = Object.create(null); var extractImport = getImportRuleTag !== undefined; /* indicates whther getImportRuleTag was called */ var usedImportRuleTag = false; var insertMarker = function insertMarker(id) { var prev = markers[id]; if (prev !== undefined) { return prev; } markers[id] = makeTextNode(id); el.appendChild(markers[id]); names[id] = Object.create(null); return markers[id]; }; var insertRules = function insertRules(id, cssRules, name) { var marker = insertMarker(id); var importRules = []; var cssRulesSize = cssRules.length; for (var i = 0; i < cssRulesSize; i += 1) { var rule = cssRules[i]; var mayHaveImport = extractImport; if (mayHaveImport && rule.indexOf('@import') !== -1) { importRules.push(rule); } else { mayHaveImport = false; var separator = i === cssRulesSize - 1 ? '' : ' '; marker.appendData('' + rule + separator); } } addNameForId(names, id, name); if (extractImport && importRules.length > 0) { usedImportRuleTag = true; // $FlowFixMe getImportRuleTag().insertRules(id + '-import', importRules); } }; var removeRules = function removeRules(id) { var marker = markers[id]; if (marker === undefined) return; /* create new empty text node and replace the current one */ var newMarker = makeTextNode(id); el.replaceChild(newMarker, marker); markers[id] = newMarker; resetIdNames(names, id); if (extractImport && usedImportRuleTag) { // $FlowFixMe getImportRuleTag().removeRules(id + '-import'); } }; var css = function css() { var str = ''; // eslint-disable-next-line guard-for-in for (var id in markers) { str += markers[id].data; } return str; }; return { clone: function clone() { throw new StyledComponentsError(5); }, css: css, getIds: getIdsFromMarkersFactory(markers), hasNameForId: hasNameForId(names), insertMarker: insertMarker, insertRules: insertRules, removeRules: removeRules, sealed: false, styleTag: el, toElement: wrapAsElement(css, names), toHTML: wrapAsHtmlTag(css, names) }; }; var makeServerTag = function makeServerTag(namesArg, markersArg) { var names = namesArg === undefined ? Object.create(null) : namesArg; var markers = markersArg === undefined ? Object.create(null) : markersArg; var insertMarker = function insertMarker(id) { var prev = markers[id]; if (prev !== undefined) { return prev; } return markers[id] = ['']; }; var insertRules = function insertRules(id, cssRules, name) { var marker = insertMarker(id); marker[0] += cssRules.join(' '); addNameForId(names, id, name); }; var removeRules = function removeRules(id) { var marker = markers[id]; if (marker === undefined) return; marker[0] = ''; resetIdNames(names, id); }; var css = function css() { var str = ''; // eslint-disable-next-line guard-for-in for (var id in markers) { var cssForId = markers[id][0]; if (cssForId) { str += makeTextMarker(id) + cssForId; } } return str; }; var clone = function clone() { var namesClone = cloneNames(names); var markersClone = Object.create(null); // eslint-disable-next-line guard-for-in for (var id in markers) { markersClone[id] = [markers[id][0]]; } return makeServerTag(namesClone, markersClone); }; var tag = { clone: clone, css: css, getIds: getIdsFromMarkersFactory(markers), hasNameForId: hasNameForId(names), insertMarker: insertMarker, insertRules: insertRules, removeRules: removeRules, sealed: false, styleTag: null, toElement: wrapAsElement(css, names), toHTML: wrapAsHtmlTag(css, names) }; return tag; }; var makeTag = function makeTag(target, tagEl, forceServer, insertBefore, getImportRuleTag) { if (IS_BROWSER && !forceServer) { var el = makeStyleTag(target, tagEl, insertBefore); { return makeBrowserTag(el, getImportRuleTag); } } return makeServerTag(); }; /* wraps a given tag so that rehydration is performed once when necessary */ var makeRehydrationTag = function makeRehydrationTag(tag, els, extracted, immediateRehydration) { /* rehydration function that adds all rules to the new tag */ var rehydrate = once(function () { /* add all extracted components to the new tag */ for (var i = 0, len = extracted.length; i < len; i += 1) { var _extracted$i = extracted[i], componentId = _extracted$i.componentId, cssFromDOM = _extracted$i.cssFromDOM; var cssRules = splitByRules(cssFromDOM); tag.insertRules(componentId, cssRules); } /* remove old HTMLStyleElements, since they have been rehydrated */ for (var _i = 0, _len = els.length; _i < _len; _i += 1) { var el = els[_i]; if (el.parentNode) { el.parentNode.removeChild(el); } } }); if (immediateRehydration) rehydrate(); return _extends({}, tag, { /* add rehydration hook to methods */ insertMarker: function insertMarker(id) { rehydrate(); return tag.insertMarker(id); }, insertRules: function insertRules(id, cssRules, name) { rehydrate(); return tag.insertRules(id, cssRules, name); }, removeRules: function removeRules(id) { rehydrate(); return tag.removeRules(id); } }); }; // var SPLIT_REGEX = /\s+/; /* determine the maximum number of components before tags are sharded */ var MAX_SIZE = void 0; if (IS_BROWSER) { /* in speedy mode we can keep a lot more rules in a sheet before a slowdown can be expected */ MAX_SIZE = 40; } else { /* for servers we do not need to shard at all */ MAX_SIZE = -1; } var sheetRunningId = 0; var master = void 0; var StyleSheet = function () { /* a map from ids to tags */ /* deferred rules for a given id */ /* this is used for not reinjecting rules via hasNameForId() */ /* when rules for an id are removed using remove() we have to ignore rehydratedNames for it */ /* a list of tags belonging to this StyleSheet */ /* a tag for import rules */ /* current capacity until a new tag must be created */ /* children (aka clones) of this StyleSheet inheriting all and future injections */ function StyleSheet() { var _this = this; var target = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : IS_BROWSER ? document.head : null; var forceServer = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; classCallCheck(this, StyleSheet); this.getImportRuleTag = function () { var importRuleTag = _this.importRuleTag; if (importRuleTag !== undefined) { return importRuleTag; } var firstTag = _this.tags[0]; var insertBefore = true; return _this.importRuleTag = makeTag(_this.target, firstTag ? firstTag.styleTag : null, _this.forceServer, insertBefore); }; sheetRunningId += 1; this.id = sheetRunningId; this.forceServer = forceServer; this.target = forceServer ? null : target; this.tagMap = {}; this.deferred = {}; this.rehydratedNames = {}; this.ignoreRehydratedNames = {}; this.tags = []; this.capacity = 1; this.clones = []; } /* rehydrate all SSR'd style tags */ StyleSheet.prototype.rehydrate = function rehydrate() { if (!IS_BROWSER || this.forceServer) { return this; } var els = []; var extracted = []; var isStreamed = false; /* retrieve all of our SSR style elements from the DOM */ var nodes = document.querySelectorAll('style[' + SC_ATTR + '][' + SC_VERSION_ATTR + '="' + "4.0.0-beta.4" + '"]'); var nodesSize = nodes.length; /* abort rehydration if no previous style tags were found */ if (nodesSize === 0) { return this; } for (var i = 0; i < nodesSize; i += 1) { // $FlowFixMe: We can trust that all elements in this query are style elements var el = nodes[i]; /* check if style tag is a streamed tag */ if (!isStreamed) isStreamed = !!el.getAttribute(SC_STREAM_ATTR); /* retrieve all component names */ var elNames = (el.getAttribute(SC_ATTR) || '').trim().split(SPLIT_REGEX); var elNamesSize = elNames.length; for (var j = 0; j < elNamesSize; j += 1) { var name = elNames[j]; /* add rehydrated name to sheet to avoid readding styles */ this.rehydratedNames[name] = true; } /* extract all components and their CSS */ extracted.push.apply(extracted, extractComps(el.textContent)); /* store original HTMLStyleElement */ els.push(el); } /* abort rehydration if nothing was extracted */ var extractedSize = extracted.length; if (extractedSize === 0) { return this; } /* create a tag to be used for rehydration */ var tag = this.makeTag(null); var rehydrationTag = makeRehydrationTag(tag, els, extracted, isStreamed); /* reset capacity and adjust MAX_SIZE by the initial size of the rehydration */ this.capacity = Math.max(1, MAX_SIZE - extractedSize); this.tags.push(rehydrationTag); /* retrieve all component ids */ for (var _j = 0; _j < extractedSize; _j += 1) { this.tagMap[extracted[_j].componentId] = rehydrationTag; } return this; }; /* retrieve a "master" instance of StyleSheet which is typically used when no other is available * The master StyleSheet is targeted by createGlobalStyle, keyframes, and components outside of any * StyleSheetManager's context */ /* reset the internal "master" instance */ StyleSheet.reset = function reset() { var forceServer = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; master = new StyleSheet(undefined, forceServer).rehydrate(); }; /* adds "children" to the StyleSheet that inherit all of the parents' rules * while their own rules do not affect the parent */ StyleSheet.prototype.clone = function clone() { var sheet = new StyleSheet(this.target, this.forceServer); /* add to clone array */ this.clones.push(sheet); /* clone all tags */ sheet.tags = this.tags.map(function (tag) { var ids = tag.getIds(); var newTag = tag.clone(); /* reconstruct tagMap */ for (var i = 0; i < ids.length; i += 1) { sheet.tagMap[ids[i]] = newTag; } return newTag; }); /* clone other maps */ sheet.rehydratedNames = _extends({}, this.rehydratedNames); sheet.deferred = _extends({}, this.deferred); return sheet; }; /* force StyleSheet to create a new tag on the next injection */ StyleSheet.prototype.sealAllTags = function sealAllTags() { this.capacity = 1; this.tags.forEach(function (tag) { // eslint-disable-next-line no-param-reassign tag.sealed = true; }); }; StyleSheet.prototype.makeTag = function makeTag$$1(tag) { var lastEl = tag ? tag.styleTag : null; var insertBefore = false; return makeTag(this.target, lastEl, this.forceServer, insertBefore, this.getImportRuleTag); }; /* get a tag for a given componentId, assign the componentId to one, or shard */ StyleSheet.prototype.getTagForId = function getTagForId(id) { /* simply return a tag, when the componentId was already assigned one */ var prev = this.tagMap[id]; if (prev !== undefined && !prev.sealed) { return prev; } var tag = this.tags[this.tags.length - 1]; /* shard (create a new tag) if the tag is exhausted (See MAX_SIZE) */ this.capacity -= 1; if (this.capacity === 0) { this.capacity = MAX_SIZE; tag = this.makeTag(tag); this.tags.push(tag); } return this.tagMap[id] = tag; }; /* mainly for createGlobalStyle to check for its id */ StyleSheet.prototype.hasId = function hasId(id) { return this.tagMap[id] !== undefined; }; /* caching layer checking id+name to already have a corresponding tag and injected rules */ StyleSheet.prototype.hasNameForId = function hasNameForId(id, name) { /* exception for rehydrated names which are checked separately */ if (this.ignoreRehydratedNames[id] === undefined && this.rehydratedNames[name]) { return true; } var tag = this.tagMap[id]; return tag !== undefined && tag.hasNameForId(id, name); }; /* registers a componentId and registers it on its tag */ StyleSheet.prototype.deferredInject = function deferredInject(id, cssRules) { /* don't inject when the id is already registered */ if (this.tagMap[id] !== undefined) return; var clones = this.clones; for (var i = 0; i < clones.length; i += 1) { clones[i].deferredInject(id, cssRules); } this.getTagForId(id).insertMarker(id); this.deferred[id] = cssRules; }; /* injects rules for a given id with a name that will need to be cached */ StyleSheet.prototype.inject = function inject(id, cssRules, name) { var clones = this.clones; for (var i = 0; i < clones.length; i += 1) { clones[i].inject(id, cssRules, name); } var tag = this.getTagForId(id); /* add deferred rules for component */ if (this.deferred[id] !== undefined) { // Combine passed cssRules with previously deferred CSS rules // NOTE: We cannot mutate the deferred array itself as all clones // do the same (see clones[i].inject) var rules = this.deferred[id].concat(cssRules); tag.insertRules(id, rules, name); this.deferred[id] = undefined; } else { tag.insertRules(id, cssRules, name); } }; /* removes all rules for a given id, which doesn't remove its marker but resets it */ StyleSheet.prototype.remove = function remove(id) { var tag = this.tagMap[id]; if (tag === undefined) return; var clones = this.clones; for (var i = 0; i < clones.length; i += 1) { clones[i].remove(id); } /* remove all rules from the tag */ tag.removeRules(id); /* ignore possible rehydrated names */ this.ignoreRehydratedNames[id] = true; /* delete possible deferred rules */ this.deferred[id] = undefined; }; StyleSheet.prototype.toHTML = function toHTML() { return this.tags.map(function (tag) { return tag.toHTML(); }).join(''); }; StyleSheet.prototype.toReactElements = function toReactElements() { var id = this.id; return this.tags.map(function (tag, i) { var key = 'sc-' + id + '-' + i; return React.cloneElement(tag.toElement(), { key: key }); }); }; createClass(StyleSheet, null, [{ key: 'master', get: function get$$1() { return master || (master = new StyleSheet().rehydrate()); } /* NOTE: This is just for backwards-compatibility with jest-styled-components */ }, { key: 'instance', get: function get$$1() { return StyleSheet.master; } }]); return StyleSheet; }(); // var Keyframes = function () { function Keyframes(name, rules) { var _this = this; classCallCheck(this, Keyframes); this.inject = function (styleSheet) { if (!styleSheet.hasNameForId(_this.id, _this.name)) { styleSheet.inject(_this.id, _this.rules, _this.name); } }; this.name = name; this.rules = rules; this.id = 'sc-keyframes-' + name; } Keyframes.prototype.getName = function getName() { return this.name; }; return Keyframes; }(); // var objToCss = function objToCss(obj, prevKey) { var css = Object.keys(obj).filter(function (key) { var chunk = obj[key]; return chunk !== undefined && chunk !== null && chunk !== false && chunk !== ''; }).map(function (key) { if (isPlainObject(obj[key])) return objToCss(obj[key], key); return hyphenateStyleName(key) + ': ' + obj[key] + ';'; }).join(' '); return prevKey ? prevKey + ' {\n ' + css + '\n}' : css; }; var flatten = function flatten(chunks, executionContext, styleSheet) { return chunks.reduce(function (ruleSet, chunk) { /* Remove falsey values */ if (chunk === undefined || chunk === null || chunk === false || chunk === '') { return ruleSet; } /* Flatten ruleSet */ if (Array.isArray(chunk)) { ruleSet.push.apply(ruleSet, flatten(chunk, executionContext, styleSheet)); return ruleSet; } /* Handle other components */ if (isStyledComponent(chunk)) { // $FlowFixMe not sure how to make this pass ruleSet.push('.' + chunk.styledComponentId); return ruleSet; } /* Either execute or defer the function */ if (isFunction(chunk)) { if (executionContext) { ruleSet.push.apply(ruleSet, flatten([chunk(executionContext)], executionContext, styleSheet)); } else ruleSet.push(chunk); return ruleSet; } if (chunk instanceof Keyframes) { if (styleSheet) { chunk.inject(styleSheet); ruleSet.push(chunk.getName()); } else ruleSet.push(chunk); return ruleSet; } /* Handle objects */ ruleSet.push( // $FlowFixMe have to add %checks somehow to isPlainObject isPlainObject(chunk) ? objToCss(chunk) : chunk.toString()); return ruleSet; }, []); }; // function css(styles) { for (var _len = arguments.length, interpolations = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { interpolations[_key - 1] = arguments[_key]; } if (isFunction(styles) || isPlainObject(styles)) { // $FlowFixMe return flatten(interleave(EMPTY_ARRAY, [styles].concat(interpolations))); } // $FlowFixMe return flatten(interleave(styles, interpolations)); } // function isStaticRules(rules, attrs) { for (var i = 0; i < rules.length; i += 1) { var rule = rules[i]; // recursive case if (Array.isArray(rule) && !isStaticRules(rule)) { return false; } else if (isFunction(rule) && !isStyledComponent(rule)) { // functions are allowed to be static if they're just being // used to get the classname of a nested styled component return false; } } if (attrs !== undefined) { // eslint-disable-next-line guard-for-in, no-restricted-syntax for (var key in attrs) { var value = attrs[key]; if (isFunction(value)) { return false; } } } return true; } // var GlobalStyle = function () { function GlobalStyle(rules, componentId) { classCallCheck(this, GlobalStyle); this.rules = rules; this.componentId = componentId; this.isStatic = isStaticRules(rules); if (!StyleSheet.master.hasId(componentId)) { StyleSheet.master.deferredInject(componentId, []); } } GlobalStyle.prototype.createStyles = function createStyles(executionContext, styleSheet) { var flatCSS = flatten(this.rules, executionContext); var css = stringifyRules(flatCSS, ''); styleSheet.inject(this.componentId, css); }; GlobalStyle.prototype.renderStyles = function renderStyles(executionContext, styleSheet) { this.removeStyles(styleSheet); this.createStyles(executionContext, styleSheet); }; GlobalStyle.prototype.removeStyles = function removeStyles(styleSheet) { var componentId = this.componentId; if (styleSheet.hasId(componentId)) { styleSheet.remove(componentId); } }; return GlobalStyle; }(); /* object-assign (c) Sindre Sorhus @license MIT */ /* eslint-disable no-unused-vars */ var getOwnPropertySymbols = Object.getOwnPropertySymbols; var hasOwnProperty = Object.prototype.hasOwnProperty; var propIsEnumerable = Object.prototype.propertyIsEnumerable; function toObject(val) { if (val === null || val === undefined) { throw new TypeError('Object.assign cannot be called with null or undefined'); } return Object(val); } function shouldUseNative() { try { if (!Object.assign) { return false; } // Detect buggy property enumeration order in older V8 versions. // https://bugs.chromium.org/p/v8/issues/detail?id=4118 var test1 = new String('abc'); // eslint-disable-line no-new-wrappers test1[5] = 'de'; if (Object.getOwnPropertyNames(test1)[0] === '5') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test2 = {}; for (var i = 0; i < 10; i++) { test2['_' + String.fromCharCode(i)] = i; } var order2 = Object.getOwnPropertyNames(test2).map(function (n) { return test2[n]; }); if (order2.join('') !== '0123456789') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test3 = {}; 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { test3[letter] = letter; }); if (Object.keys(Object.assign({}, test3)).join('') !== 'abcdefghijklmnopqrst') { return false; } return true; } catch (err) { // We don't expect any of the above to throw, but better to be safe. return false; } } var objectAssign = shouldUseNative() ? Object.assign : function (target, source) { var from; var to = toObject(target); var symbols; for (var s = 1; s < arguments.length; s++) { from = Object(arguments[s]); for (var key in from) { if (hasOwnProperty.call(from, key)) { to[key] = from[key]; } } if (getOwnPropertySymbols) { symbols = getOwnPropertySymbols(from); for (var i = 0; i < symbols.length; i++) { if (propIsEnumerable.call(from, symbols[i])) { to[symbols[i]] = from[symbols[i]]; } } } } return to; }; /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'; var ReactPropTypesSecret_1 = ReactPropTypesSecret; var printWarning = function() {}; { var ReactPropTypesSecret$1 = ReactPropTypesSecret_1; var loggedTypeFailures = {}; printWarning = function(text) { var message = 'Warning: ' + text; if (typeof console !== 'undefined') { console.error(message); } try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. throw new Error(message); } catch (x) {} }; } /** * Assert that the values match with the type specs. * Error messages are memorized and will only be shown once. * * @param {object} typeSpecs Map of name to a ReactPropType * @param {object} values Runtime values that need to be type-checked * @param {string} location e.g. "prop", "context", "child context" * @param {string} componentName Name of the component for error messages. * @param {?Function} getStack Returns the component stack. * @private */ function checkPropTypes(typeSpecs, values, location, componentName, getStack) { { for (var typeSpecName in typeSpecs) { if (typeSpecs.hasOwnProperty(typeSpecName)) { var error; // Prop type validation may throw. In case they do, we don't want to // fail the render phase where it didn't fail before. So we log it. // After these have been cleaned up, we'll let them throw. try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. if (typeof typeSpecs[typeSpecName] !== 'function') { var err = Error( (componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' ); err.name = 'Invariant Violation'; throw err; } error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret$1); } catch (ex) { error = ex; } if (error && !(error instanceof Error)) { printWarning( (componentName || 'React class') + ': type specification of ' + location + ' `' + typeSpecName + '` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a ' + typeof error + '. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).' ); } if (error instanceof Error && !(error.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error.message] = true; var stack = getStack ? getStack() : ''; printWarning( 'Failed ' + location + ' type: ' + error.message + (stack != null ? stack : '') ); } } } } } var checkPropTypes_1 = checkPropTypes; var printWarning$1 = function() {}; { printWarning$1 = function(text) { var message = 'Warning: ' + text; if (typeof console !== 'undefined') { console.error(message); } try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. throw new Error(message); } catch (x) {} }; } function emptyFunctionThatReturnsNull() { return null; } var factoryWithTypeCheckers = function(isValidElement, throwOnDirectAccess) { /* global Symbol */ var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec. /** * Returns the iterator method function contained on the iterable object. * * Be sure to invoke the function with the iterable as context: * * var iteratorFn = getIteratorFn(myIterable); * if (iteratorFn) { * var iterator = iteratorFn.call(myIterable); * ... * } * * @param {?object} maybeIterable * @return {?function} */ function getIteratorFn(maybeIterable) { var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]); if (typeof iteratorFn === 'function') { return iteratorFn; } } /** * Collection of methods that allow declaration and validation of props that are * supplied to React components. Example usage: * * var Props = require('ReactPropTypes'); * var MyArticle = React.createClass({ * propTypes: { * // An optional string prop named "description". * description: Props.string, * * // A required enum prop named "category". * category: Props.oneOf(['News','Photos']).isRequired, * * // A prop named "dialog" that requires an instance of Dialog. * dialog: Props.instanceOf(Dialog).isRequired * }, * render: function() { ... } * }); * * A more formal specification of how these methods are used: * * type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...) * decl := ReactPropTypes.{type}(.isRequired)? * * Each and every declaration produces a function with the same signature. This * allows the creation of custom validation functions. For example: * * var MyLink = React.createClass({ * propTypes: { * // An optional string or URI prop named "href". * href: function(props, propName, componentName) { * var propValue = props[propName]; * if (propValue != null && typeof propValue !== 'string' && * !(propValue instanceof URI)) { * return new Error( * 'Expected a string or an URI for ' + propName + ' in ' + * componentName * ); * } * } * }, * render: function() {...} * }); * * @internal */ var ANONYMOUS = '<<anonymous>>'; // Important! // Keep this list in sync with production version in `./factoryWithThrowingShims.js`. var ReactPropTypes = { array: createPrimitiveTypeChecker('array'), bool: createPrimitiveTypeChecker('boolean'), func: createPrimitiveTypeChecker('function'), number: createPrimitiveTypeChecker('number'), object: createPrimitiveTypeChecker('object'), string: createPrimitiveTypeChecker('string'), symbol: createPrimitiveTypeChecker('symbol'), any: createAnyTypeChecker(), arrayOf: createArrayOfTypeChecker, element: createElementTypeChecker(), instanceOf: createInstanceTypeChecker, node: createNodeChecker(), objectOf: createObjectOfTypeChecker, oneOf: createEnumTypeChecker, oneOfType: createUnionTypeChecker, shape: createShapeTypeChecker, exact: createStrictShapeTypeChecker, }; /** * inlined Object.is polyfill to avoid requiring consumers ship their own * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is */ /*eslint-disable no-self-compare*/ function is(x, y) { // SameValue algorithm if (x === y) { // Steps 1-5, 7-10 // Steps 6.b-6.e: +0 != -0 return x !== 0 || 1 / x === 1 / y; } else { // Step 6.a: NaN == NaN return x !== x && y !== y; } } /*eslint-enable no-self-compare*/ /** * We use an Error-like object for backward compatibility as people may call * PropTypes directly and inspect their output. However, we don't use real * Errors anymore. We don't inspect their stack anyway, and creating them * is prohibitively expensive if they are created too often, such as what * happens in oneOfType() for any type before the one that matched. */ function PropTypeError(message) { this.message = message; this.stack = ''; } // Make `instanceof Error` still work for returned errors. PropTypeError.prototype = Error.prototype; function createChainableTypeChecker(validate) { { var manualPropTypeCallCache = {}; var manualPropTypeWarningCount = 0; } function checkType(isRequired, props, propName, componentName, location, propFullName, secret) { componentName = componentName || ANONYMOUS; propFullName = propFullName || propName; if (secret !== ReactPropTypesSecret_1) { if (throwOnDirectAccess) { // New behavior only for users of `prop-types` package var err = new Error( 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' + 'Use `PropTypes.checkPropTypes()` to call them. ' + 'Read more at http://fb.me/use-check-prop-types' ); err.name = 'Invariant Violation'; throw err; } else if (typeof console !== 'undefined') { // Old behavior for people using React.PropTypes var cacheKey = componentName + ':' + propName; if ( !manualPropTypeCallCache[cacheKey] && // Avoid spamming the console because they are often not actionable except for lib authors manualPropTypeWarningCount < 3 ) { printWarning$1( 'You are manually calling a React.PropTypes validation ' + 'function for the `' + propFullName + '` prop on `' + componentName + '`. This is deprecated ' + 'and will throw in the standalone `prop-types` package. ' + 'You may be seeing this warning due to a third-party PropTypes ' + 'library. See https://fb.me/react-warning-dont-call-proptypes ' + 'for details.' ); manualPropTypeCallCache[cacheKey] = true; manualPropTypeWarningCount++; } } } if (props[propName] == null) { if (isRequired) { if (props[propName] === null) { return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required ' + ('in `' + componentName + '`, but its value is `null`.')); } return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required in ' + ('`' + componentName + '`, but its value is `undefined`.')); } return null; } else { return validate(props, propName, componentName, location, propFullName); } } var chainedCheckType = checkType.bind(null, false); chainedCheckType.isRequired = checkType.bind(null, true); return chainedCheckType; } function createPrimitiveTypeChecker(expectedType) { function validate(props, propName, componentName, location, propFullName, secret) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== expectedType) { // `propValue` being instance of, say, date/regexp, pass the 'object' // check, but we can offer a more precise error message here rather than // 'of type `object`'. var preciseType = getPreciseType(propValue); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.')); } return null; } return createChainableTypeChecker(validate); } function createAnyTypeChecker() { return createChainableTypeChecker(emptyFunctionThatReturnsNull); } function createArrayOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { if (typeof typeChecker !== 'function') { return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.'); } var propValue = props[propName]; if (!Array.isArray(propValue)) { var propType = getPropType(propValue); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.')); } for (var i = 0; i < propValue.length; i++) { var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']', ReactPropTypesSecret_1); if (error instanceof Error) { return error; } } return null; } return createChainableTypeChecker(validate); } function createElementTypeChecker() { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; if (!isValidElement(propValue)) { var propType = getPropType(propValue); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement.')); } return null; } return createChainableTypeChecker(validate); } function createInstanceTypeChecker(expectedClass) { function validate(props, propName, componentName, location, propFullName) { if (!(props[propName] instanceof expectedClass)) { var expectedClassName = expectedClass.name || ANONYMOUS; var actualClassName = getClassName(props[propName]); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.')); } return null; } return createChainableTypeChecker(validate); } function createEnumTypeChecker(expectedValues) { if (!Array.isArray(expectedValues)) { printWarning$1('Invalid argument supplied to oneOf, expected an instance of array.'); return emptyFunctionThatReturnsNull; } function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; for (var i = 0; i < expectedValues.length; i++) { if (is(propValue, expectedValues[i])) { return null; } } var valuesString = JSON.stringify(expectedValues); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of value `' + propValue + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.')); } return createChainableTypeChecker(validate); } function createObjectOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { if (typeof typeChecker !== 'function') { return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.'); } var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.')); } for (var key in propValue) { if (propValue.hasOwnProperty(key)) { var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret_1); if (error instanceof Error) { return error; } } } return null; } return createChainableTypeChecker(validate); } function createUnionTypeChecker(arrayOfTypeCheckers) { if (!Array.isArray(arrayOfTypeCheckers)) { printWarning$1('Invalid argument supplied to oneOfType, expected an instance of array.'); return emptyFunctionThatReturnsNull; } for (var i = 0; i < arrayOfTypeCheckers.length; i++) { var checker = arrayOfTypeCheckers[i]; if (typeof checker !== 'function') { printWarning$1( 'Invalid argument supplied to oneOfType. Expected an array of check functions, but ' + 'received ' + getPostfixForTypeWarning(checker) + ' at index ' + i + '.' ); return emptyFunctionThatReturnsNull; } } function validate(props, propName, componentName, location, propFullName) { for (var i = 0; i < arrayOfTypeCheckers.length; i++) { var checker = arrayOfTypeCheckers[i]; if (checker(props, propName, componentName, location, propFullName, ReactPropTypesSecret_1) == null) { return null; } } return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.')); } return createChainableTypeChecker(validate); } function createNodeChecker() { function validate(props, propName, componentName, location, propFullName) { if (!isNode(props[propName])) { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.')); } return null; } return createChainableTypeChecker(validate); } function createShapeTypeChecker(shapeTypes) { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.')); } for (var key in shapeTypes) { var checker = shapeTypes[key]; if (!checker) { continue; } var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret_1); if (error) { return error; } } return null; } return createChainableTypeChecker(validate); } function createStrictShapeTypeChecker(shapeTypes) { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.')); } // We need to check all keys in case some are required but missing from // props. var allKeys = objectAssign({}, props[propName], shapeTypes); for (var key in allKeys) { var checker = shapeTypes[key]; if (!checker) { return new PropTypeError( 'Invalid ' + location + ' `' + propFullName + '` key `' + key + '` supplied to `' + componentName + '`.' + '\nBad object: ' + JSON.stringify(props[propName], null, ' ') + '\nValid keys: ' + JSON.stringify(Object.keys(shapeTypes), null, ' ') ); } var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret_1); if (error) { return error; } } return null; } return createChainableTypeChecker(validate); } function isNode(propValue) { switch (typeof propValue) { case 'number': case 'string': case 'undefined': return true; case 'boolean': return !propValue; case 'object': if (Array.isArray(propValue)) { return propValue.every(isNode); } if (propValue === null || isValidElement(propValue)) { return true; } var iteratorFn = getIteratorFn(propValue); if (iteratorFn) { var iterator = iteratorFn.call(propValue); var step; if (iteratorFn !== propValue.entries) { while (!(step = iterator.next()).done) { if (!isNode(step.value)) { return false; } } } else { // Iterator will provide entry [k,v] tuples rather than values. while (!(step = iterator.next()).done) { var entry = step.value; if (entry) { if (!isNode(entry[1])) { return false; } } } } } else { return false; } return true; default: return false; } } function isSymbol(propType, propValue) { // Native Symbol. if (propType === 'symbol') { return true; } // 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol' if (propValue['@@toStringTag'] === 'Symbol') { return true; } // Fallback for non-spec compliant Symbols which are polyfilled. if (typeof Symbol === 'function' && propValue instanceof Symbol) { return true; } return false; } // Equivalent of `typeof` but with special handling for array and regexp. function getPropType(propValue) { var propType = typeof propValue; if (Array.isArray(propValue)) { return 'array'; } if (propValue instanceof RegExp) { // Old webkits (at least until Android 4.0) return 'function' rather than // 'object' for typeof a RegExp. We'll normalize this here so that /bla/ // passes PropTypes.object. return 'object'; } if (isSymbol(propType, propValue)) { return 'symbol'; } return propType; } // This handles more types than `getPropType`. Only used for error messages. // See `createPrimitiveTypeChecker`. function getPreciseType(propValue) { if (typeof propValue === 'undefined' || propValue === null) { return '' + propValue; } var propType = getPropType(propValue); if (propType === 'object') { if (propValue instanceof Date) { return 'date'; } else if (propValue instanceof RegExp) { return 'regexp'; } } return propType; } // Returns a string that is postfixed to a warning about an invalid type. // For example, "undefined" or "of type array" function getPostfixForTypeWarning(value) { var type = getPreciseType(value); switch (type) { case 'array': case 'object': return 'an ' + type; case 'boolean': case 'date': case 'regexp': return 'a ' + type; default: return type; } } // Returns class name of the object, if any. function getClassName(propValue) { if (!propValue.constructor || !propValue.constructor.name) { return ANONYMOUS; } return propValue.constructor.name; } ReactPropTypes.checkPropTypes = checkPropTypes_1; ReactPropTypes.PropTypes = ReactPropTypes; return ReactPropTypes; }; var propTypes = createCommonjsModule(function (module) { /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ { var REACT_ELEMENT_TYPE = (typeof Symbol === 'function' && Symbol.for && Symbol.for('react.element')) || 0xeac7; var isValidElement = function(object) { return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; }; // By explicitly using `prop-types` you are opting into new development behavior. // http://fb.me/prop-types-in-prod var throwOnDirectAccess = true; module.exports = factoryWithTypeCheckers(isValidElement, throwOnDirectAccess); } }); var simpleIsEqual = function simpleIsEqual(a, b) { return a === b; }; function index (resultFn, isEqual) { if (isEqual === void 0) { isEqual = simpleIsEqual; } var lastThis; var lastArgs = []; var lastResult; var calledOnce = false; var isNewArgEqualToLast = function isNewArgEqualToLast(newArg, index) { return isEqual(newArg, lastArgs[index]); }; var result = function result() { for (var _len = arguments.length, newArgs = new Array(_len), _key = 0; _key < _len; _key++) { newArgs[_key] = arguments[_key]; } if (calledOnce && lastThis === this && newArgs.length === lastArgs.length && newArgs.every(isNewArgEqualToLast)) { return lastResult; } lastResult = resultFn.apply(this, newArgs); calledOnce = true; lastThis = this; lastArgs = newArgs; return lastResult; }; return result; } // var ServerStyleSheet = function () { function ServerStyleSheet() { classCallCheck(this, ServerStyleSheet); /* The master sheet might be reset, so keep a reference here */ this.masterSheet = StyleSheet.master; this.instance = this.masterSheet.clone(); this.sealed = false; } /** * Mark the ServerStyleSheet as being fully emitted and manually GC it from the * StyleSheet singleton. */ ServerStyleSheet.prototype.seal = function seal() { if (!this.sealed) { /* Remove sealed StyleSheets from the master sheet */ var index = this.masterSheet.clones.indexOf(this.instance); this.masterSheet.clones.splice(index, 1); this.sealed = true; } }; ServerStyleSheet.prototype.collectStyles = function collectStyles(children) { if (this.sealed) { throw new StyledComponentsError(2); } return React__default.createElement( StyleSheetManager, { sheet: this.instance }, children ); }; ServerStyleSheet.prototype.getStyleTags = function getStyleTags() { this.seal(); return this.instance.toHTML(); }; ServerStyleSheet.prototype.getStyleElement = function getStyleElement() { this.seal(); return this.instance.toReactElements(); }; ServerStyleSheet.prototype.interleaveWithNodeStream = function interleaveWithNodeStream(readableStream) { var _this = this; { throw new StyledComponentsError(3); } /* the tag index keeps track of which tags have already been emitted */ var instance = this.instance; var instanceTagIndex = 0; var streamAttr = SC_STREAM_ATTR + '="true"'; var transformer = new stream.Transform({ transform: function appendStyleChunks(chunk, /* encoding */_, callback) { var tags = instance.tags; var html = ''; /* retrieve html for each new style tag */ for (; instanceTagIndex < tags.length; instanceTagIndex += 1) { var tag = tags[instanceTagIndex]; html += tag.toHTML(streamAttr); } /* force our StyleSheets to emit entirely new tags */ instance.sealAllTags(); /* prepend style html to chunk */ this.push(html + chunk); callback(); } }); readableStream.on('end', function () { return _this.seal(); }); readableStream.on('error', function (err) { _this.seal(); // forward the error to the transform stream transformer.emit('error', err); }); return readableStream.pipe(transformer); }; return ServerStyleSheet; }(); // var StyleSheetContext = React.createContext(); var StyleSheetConsumer = StyleSheetContext.Consumer; var StyleSheetManager = function (_Component) { inherits(StyleSheetManager, _Component); function StyleSheetManager(props) { classCallCheck(this, StyleSheetManager); var _this = possibleConstructorReturn(this, _Component.call(this, props)); _this.getContext = index(_this.getContext); return _this; } StyleSheetManager.prototype.getContext = function getContext(sheet, target) { if (sheet) { return sheet; } else if (target) { return new StyleSheet(target); } else { throw new StyledComponentsError(4); } }; StyleSheetManager.prototype.render = function render() { var _props = this.props, children = _props.children, sheet = _props.sheet, target = _props.target; var context = this.getContext(sheet, target); return React__default.createElement( StyleSheetContext.Provider, { value: context }, React__default.Children.only(children) ); }; return StyleSheetManager; }(React.Component); StyleSheetManager.propTypes = { sheet: propTypes.oneOfType([propTypes.instanceOf(StyleSheet), propTypes.instanceOf(ServerStyleSheet)]), target: propTypes.shape({ appendChild: propTypes.func.isRequired }) }; // var determineTheme = (function (props, fallbackTheme, defaultProps) { // Props should take precedence over ThemeProvider, which should take precedence over // defaultProps, but React automatically puts defaultProps on props. /* eslint-disable react/prop-types */ var isDefaultTheme = defaultProps ? props.theme === defaultProps.theme : false; var theme = props.theme && !isDefaultTheme ? props.theme : fallbackTheme || defaultProps.theme; /* eslint-enable */ return theme; }); // var ThemeContext = React.createContext(); var ThemeConsumer = ThemeContext.Consumer; /** * Provide a theme to an entire react component tree via context */ var ThemeProvider = function (_Component) { inherits(ThemeProvider, _Component); function ThemeProvider(props) { classCallCheck(this, ThemeProvider); var _this = possibleConstructorReturn(this, _Component.call(this, props)); _this.getContext = index(_this.getContext.bind(_this)); _this.renderInner = _this.renderInner.bind(_this); return _this; } ThemeProvider.prototype.render = function render() { if (!this.props.children) return null; return React__default.createElement( ThemeContext.Consumer, null, this.renderInner ); }; ThemeProvider.prototype.renderInner = function renderInner(outerTheme) { var context = this.getContext(this.props.theme, outerTheme); return React__default.createElement( ThemeContext.Provider, { value: context }, React__default.Children.only(this.props.children) ); }; /** * Get the theme from the props, supporting both (outerTheme) => {} * as well as object notation */ ThemeProvider.prototype.getTheme = function getTheme(theme, outerTheme) { if (isFunction(theme)) { var mergedTheme = theme(outerTheme); if (mergedTheme === null || Array.isArray(mergedTheme) || (typeof mergedTheme === 'undefined' ? 'undefined' : _typeof(mergedTheme)) !== 'object') { throw new StyledComponentsError(7); } return mergedTheme; } if (theme === null || Array.isArray(theme) || (typeof theme === 'undefined' ? 'undefined' : _typeof(theme)) !== 'object') { throw new StyledComponentsError(8); } return _extends({}, outerTheme, theme); }; ThemeProvider.prototype.getContext = function getContext(theme, outerTheme) { return this.getTheme(theme, outerTheme); }; return ThemeProvider; }(React.Component); // // Source: https://github.com/garycourt/murmurhash-js/blob/master/murmurhash2_gc.js function murmurhash(c) { for (var e = c.length | 0, a = e | 0, d = 0, b; e >= 4;) { b = c.charCodeAt(d) & 255 | (c.charCodeAt(++d) & 255) << 8 | (c.charCodeAt(++d) & 255) << 16 | (c.charCodeAt(++d) & 255) << 24, b = 1540483477 * (b & 65535) + ((1540483477 * (b >>> 16) & 65535) << 16), b ^= b >>> 24, b = 1540483477 * (b & 65535) + ((1540483477 * (b >>> 16) & 65535) << 16), a = 1540483477 * (a & 65535) + ((1540483477 * (a >>> 16) & 65535) << 16) ^ b, e -= 4, ++d; } switch (e) { case 3: a ^= (c.charCodeAt(d + 2) & 255) << 16; case 2: a ^= (c.charCodeAt(d + 1) & 255) << 8; case 1: a ^= c.charCodeAt(d) & 255, a = 1540483477 * (a & 65535) + ((1540483477 * (a >>> 16) & 65535) << 16); } a ^= a >>> 13; a = 1540483477 * (a & 65535) + ((1540483477 * (a >>> 16) & 65535) << 16); return (a ^ a >>> 15) >>> 0; } // function createGlobalStyle(strings) { for (var _len = arguments.length, interpolations = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { interpolations[_key - 1] = arguments[_key]; } var rules = css.apply(undefined, [strings].concat(interpolations)); var id = 'sc-global-' + murmurhash(JSON.stringify(rules)); var style = new GlobalStyle(rules, id); var count = 0; var GlobalStyleComponent = function (_React$PureComponent) { inherits(GlobalStyleComponent, _React$PureComponent); function GlobalStyleComponent() { classCallCheck(this, GlobalStyleComponent); var _this = possibleConstructorReturn(this, _React$PureComponent.call(this)); count += 1; return _this; } GlobalStyleComponent.prototype.componentWillUnmount = function componentWillUnmount() { count -= 1; /** * Depending on the order "render" is called this can cause the styles to be lost * until the next render pass of the remaining instance, which may * not be immediate. */ if (count === 0) style.removeStyles(this.styleSheet);else if (IS_BROWSER && count > 1) { console.warn('The global style component ' + id + ' was composed and rendered multiple times in your React component tree. Only the last-rendered copy will have its styles remain in <head>.'); } }; GlobalStyleComponent.prototype.render = function render() { var _this2 = this; if (React__default.Children.count(this.props.children)) { throw new StyledComponentsError(11); } return React__default.createElement( StyleSheetConsumer, null, function (styleSheet) { _this2.styleSheet = styleSheet || StyleSheet.master; if (style.isStatic) { style.renderStyles(STATIC_EXECUTION_CONTEXT, _this2.styleSheet); return null; } else { return React__default.createElement( ThemeConsumer, null, function (theme) { var defaultProps = _this2.constructor.defaultProps; var context = _extends({}, _this2.props); if (typeof theme !== 'undefined') { context.theme = determineTheme(_this2.props, theme, defaultProps); } style.renderStyles(context, _this2.styleSheet); return null; } ); } } ); }; return GlobalStyleComponent; }(React__default.PureComponent); GlobalStyleComponent.styledComponentId = id; return GlobalStyleComponent; } // var replaceWhitespace = function replaceWhitespace(str) { return str.replace(/\s|\\n/g, ''); }; var _keyframes = (function (nameGenerator, stringifyRules, css) { return function () { var rules = css.apply(undefined, arguments); var name = nameGenerator(murmurhash(replaceWhitespace(JSON.stringify(rules)))); return new Keyframes(name, stringifyRules(rules, name, '@keyframes')); }; }); var reactIs_production_min = createCommonjsModule(function (module, exports) { Object.defineProperty(exports,"__esModule",{value:!0});var b="function"===typeof Symbol&&Symbol.for,c=b?Symbol.for("react.element"):60103,d=b?Symbol.for("react.portal"):60106,e=b?Symbol.for("react.fragment"):60107,f=b?Symbol.for("react.strict_mode"):60108,g=b?Symbol.for("react.profiler"):60114,h=b?Symbol.for("react.provider"):60109,k=b?Symbol.for("react.context"):60110,l=b?Symbol.for("react.async_mode"):60111,m=b?Symbol.for("react.forward_ref"):60112,n=b?Symbol.for("react.timeout"):60113; function q(a){if("object"===typeof a&&null!==a){var p=a.$$typeof;switch(p){case c:switch(a=a.type,a){case l:case e:case g:case f:return a;default:switch(a=a&&a.$$typeof,a){case k:case m:case h:return a;default:return p}}case d:return p}}}exports.typeOf=q;exports.AsyncMode=l;exports.ContextConsumer=k;exports.ContextProvider=h;exports.Element=c;exports.ForwardRef=m;exports.Fragment=e;exports.Profiler=g;exports.Portal=d;exports.StrictMode=f; exports.isValidElementType=function(a){return "string"===typeof a||"function"===typeof a||a===e||a===l||a===g||a===f||a===n||"object"===typeof a&&null!==a&&(a.$$typeof===h||a.$$typeof===k||a.$$typeof===m)};exports.isAsyncMode=function(a){return q(a)===l};exports.isContextConsumer=function(a){return q(a)===k};exports.isContextProvider=function(a){return q(a)===h};exports.isElement=function(a){return "object"===typeof a&&null!==a&&a.$$typeof===c};exports.isForwardRef=function(a){return q(a)===m}; exports.isFragment=function(a){return q(a)===e};exports.isProfiler=function(a){return q(a)===g};exports.isPortal=function(a){return q(a)===d};exports.isStrictMode=function(a){return q(a)===f}; }); unwrapExports(reactIs_production_min); var reactIs_production_min_1 = reactIs_production_min.typeOf; var reactIs_production_min_2 = reactIs_production_min.AsyncMode; var reactIs_production_min_3 = reactIs_production_min.ContextConsumer; var reactIs_production_min_4 = reactIs_production_min.ContextProvider; var reactIs_production_min_5 = reactIs_production_min.Element; var reactIs_production_min_6 = reactIs_production_min.ForwardRef; var reactIs_production_min_7 = reactIs_production_min.Fragment; var reactIs_production_min_8 = reactIs_production_min.Profiler; var reactIs_production_min_9 = reactIs_production_min.Portal; var reactIs_production_min_10 = reactIs_production_min.StrictMode; var reactIs_production_min_11 = reactIs_production_min.isValidElementType; var reactIs_production_min_12 = reactIs_production_min.isAsyncMode; var reactIs_production_min_13 = reactIs_production_min.isContextConsumer; var reactIs_production_min_14 = reactIs_production_min.isContextProvider; var reactIs_production_min_15 = reactIs_production_min.isElement; var reactIs_production_min_16 = reactIs_production_min.isForwardRef; var reactIs_production_min_17 = reactIs_production_min.isFragment; var reactIs_production_min_18 = reactIs_production_min.isProfiler; var reactIs_production_min_19 = reactIs_production_min.isPortal; var reactIs_production_min_20 = reactIs_production_min.isStrictMode; var reactIs_development = createCommonjsModule(function (module, exports) { { (function() { Object.defineProperty(exports, '__esModule', { value: true }); // The Symbol used to tag the ReactElement-like types. If there is no native Symbol // nor polyfill, then a plain number is used for performance. var hasSymbol = typeof Symbol === 'function' && Symbol.for; var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7; var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca; var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb; var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc; var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2; var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd; var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace; var REACT_ASYNC_MODE_TYPE = hasSymbol ? Symbol.for('react.async_mode') : 0xeacf; var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0; var REACT_TIMEOUT_TYPE = hasSymbol ? Symbol.for('react.timeout') : 0xead1; function isValidElementType(type) { return typeof type === 'string' || typeof type === 'function' || // Note: its typeof might be other than 'symbol' or 'number' if it's a polyfill. type === REACT_FRAGMENT_TYPE || type === REACT_ASYNC_MODE_TYPE || type === REACT_PROFILER_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_TIMEOUT_TYPE || typeof type === 'object' && type !== null && (type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE); } function typeOf(object) { if (typeof object === 'object' && object !== null) { var $$typeof = object.$$typeof; switch ($$typeof) { case REACT_ELEMENT_TYPE: var type = object.type; switch (type) { case REACT_ASYNC_MODE_TYPE: case REACT_FRAGMENT_TYPE: case REACT_PROFILER_TYPE: case REACT_STRICT_MODE_TYPE: return type; default: var $$typeofType = type && type.$$typeof; switch ($$typeofType) { case REACT_CONTEXT_TYPE: case REACT_FORWARD_REF_TYPE: case REACT_PROVIDER_TYPE: return $$typeofType; default: return $$typeof; } } case REACT_PORTAL_TYPE: return $$typeof; } } return undefined; } var AsyncMode = REACT_ASYNC_MODE_TYPE; var ContextConsumer = REACT_CONTEXT_TYPE; var ContextProvider = REACT_PROVIDER_TYPE; var Element = REACT_ELEMENT_TYPE; var ForwardRef = REACT_FORWARD_REF_TYPE; var Fragment = REACT_FRAGMENT_TYPE; var Profiler = REACT_PROFILER_TYPE; var Portal = REACT_PORTAL_TYPE; var StrictMode = REACT_STRICT_MODE_TYPE; function isAsyncMode(object) { return typeOf(object) === REACT_ASYNC_MODE_TYPE; } function isContextConsumer(object) { return typeOf(object) === REACT_CONTEXT_TYPE; } function isContextProvider(object) { return typeOf(object) === REACT_PROVIDER_TYPE; } function isElement(object) { return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; } function isForwardRef(object) { return typeOf(object) === REACT_FORWARD_REF_TYPE; } function isFragment(object) { return typeOf(object) === REACT_FRAGMENT_TYPE; } function isProfiler(object) { return typeOf(object) === REACT_PROFILER_TYPE; } function isPortal(object) { return typeOf(object) === REACT_PORTAL_TYPE; } function isStrictMode(object) { return typeOf(object) === REACT_STRICT_MODE_TYPE; } exports.typeOf = typeOf; exports.AsyncMode = AsyncMode; exports.ContextConsumer = ContextConsumer; exports.ContextProvider = ContextProvider; exports.Element = Element; exports.ForwardRef = ForwardRef; exports.Fragment = Fragment; exports.Profiler = Profiler; exports.Portal = Portal; exports.StrictMode = StrictMode; exports.isValidElementType = isValidElementType; exports.isAsyncMode = isAsyncMode; exports.isContextConsumer = isContextConsumer; exports.isContextProvider = isContextProvider; exports.isElement = isElement; exports.isForwardRef = isForwardRef; exports.isFragment = isFragment; exports.isProfiler = isProfiler; exports.isPortal = isPortal; exports.isStrictMode = isStrictMode; })(); } }); unwrapExports(reactIs_development); var reactIs_development_1 = reactIs_development.typeOf; var reactIs_development_2 = reactIs_development.AsyncMode; var reactIs_development_3 = reactIs_development.ContextConsumer; var reactIs_development_4 = reactIs_development.ContextProvider; var reactIs_development_5 = reactIs_development.Element; var reactIs_development_6 = reactIs_development.ForwardRef; var reactIs_development_7 = reactIs_development.Fragment; var reactIs_development_8 = reactIs_development.Profiler; var reactIs_development_9 = reactIs_development.Portal; var reactIs_development_10 = reactIs_development.StrictMode; var reactIs_development_11 = reactIs_development.isValidElementType; var reactIs_development_12 = reactIs_development.isAsyncMode; var reactIs_development_13 = reactIs_development.isContextConsumer; var reactIs_development_14 = reactIs_development.isContextProvider; var reactIs_development_15 = reactIs_development.isElement; var reactIs_development_16 = reactIs_development.isForwardRef; var reactIs_development_17 = reactIs_development.isFragment; var reactIs_development_18 = reactIs_development.isProfiler; var reactIs_development_19 = reactIs_development.isPortal; var reactIs_development_20 = reactIs_development.isStrictMode; var reactIs = createCommonjsModule(function (module) { { module.exports = reactIs_development; } }); var _ReactIs$ForwardRef; 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; } /** * Copyright 2015, Yahoo! Inc. * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. */ var REACT_STATICS = { childContextTypes: true, contextTypes: true, defaultProps: true, displayName: true, getDefaultProps: true, getDerivedStateFromProps: true, mixins: true, propTypes: true, type: true }; var KNOWN_STATICS = { name: true, length: true, prototype: true, caller: true, callee: true, arguments: true, arity: true }; var TYPE_STATICS = _defineProperty({}, reactIs.ForwardRef, (_ReactIs$ForwardRef = {}, _defineProperty(_ReactIs$ForwardRef, '$$typeof', true), _defineProperty(_ReactIs$ForwardRef, 'render', true), _ReactIs$ForwardRef)); var defineProperty$1 = Object.defineProperty; var getOwnPropertyNames = Object.getOwnPropertyNames; var getOwnPropertySymbols$1 = Object.getOwnPropertySymbols; var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; var getPrototypeOf = Object.getPrototypeOf; var objectPrototype = Object.prototype; function hoistNonReactStatics(targetComponent, sourceComponent, blacklist) { if (typeof sourceComponent !== 'string') { // don't hoist over string (html) components if (objectPrototype) { var inheritedComponent = getPrototypeOf(sourceComponent); if (inheritedComponent && inheritedComponent !== objectPrototype) { hoistNonReactStatics(targetComponent, inheritedComponent, blacklist); } } var keys = getOwnPropertyNames(sourceComponent); if (getOwnPropertySymbols$1) { keys = keys.concat(getOwnPropertySymbols$1(sourceComponent)); } var targetStatics = TYPE_STATICS[targetComponent['$$typeof']] || REACT_STATICS; var sourceStatics = TYPE_STATICS[sourceComponent['$$typeof']] || REACT_STATICS; for (var i = 0; i < keys.length; ++i) { var key = keys[i]; if (!KNOWN_STATICS[key] && !(blacklist && blacklist[key]) && !(sourceStatics && sourceStatics[key]) && !(targetStatics && targetStatics[key])) { var descriptor = getOwnPropertyDescriptor(sourceComponent, key); try { // Avoid failures from read-only properties defineProperty$1(targetComponent, key, descriptor); } catch (e) {} } } return targetComponent; } return targetComponent; } var hoistNonReactStatics_cjs = hoistNonReactStatics; // function getComponentName(target) { return target.displayName || target.name || 'Component'; } // var withTheme = (function (Component) { var WithTheme = React__default.forwardRef(function (props, ref) { return React__default.createElement( ThemeConsumer, null, function (theme) { // $FlowFixMe var defaultProps = WithTheme.defaultProps; var themeProp = determineTheme(props, theme, defaultProps); if (themeProp === undefined) { // eslint-disable-next-line no-console console.warn('[withTheme] You are not using a ThemeProvider nor passing a theme prop or a theme in defaultProps in component class ' + getComponentName(Component)); } return React__default.createElement(Component, _extends({}, props, { theme: themeProp, ref: ref })); } ); }); hoistNonReactStatics_cjs(WithTheme, Component); WithTheme.displayName = 'WithTheme(' + getComponentName(Component) + ')'; return WithTheme; }); // /* eslint-disable */ var __DO_NOT_USE_OR_YOU_WILL_BE_HAUNTED_BY_SPOOKY_GHOSTS = { StyleSheet: StyleSheet }; // /* Warning if you've imported this file on React Native */ if (typeof navigator !== 'undefined' && navigator.product === 'ReactNative') { // eslint-disable-next-line no-console console.warn("It looks like you've imported 'styled-components' on React Native.\n" + "Perhaps you're looking to import 'styled-components/native'?\n" + 'Read more about this at https://www.styled-components.com/docs/basics#react-native'); } /* Warning if there are several instances of styled-components */ if (typeof window !== 'undefined' && typeof navigator !== 'undefined' && typeof navigator.userAgent === 'string' && navigator.userAgent.indexOf('Node.js') === -1 && navigator.userAgent.indexOf('jsdom') === -1) { window['__styled-components-init__'] = window['__styled-components-init__'] || 0; if (window['__styled-components-init__'] === 1) { // eslint-disable-next-line no-console console.warn("It looks like there are several instances of 'styled-components' initialized in this application. " + 'This may cause dynamic styles not rendering properly, errors happening during rehydration process ' + 'and makes your application bigger without a good reason.\n\n' + 'See https://s-c.sh/2BAXzed for more info.'); } window['__styled-components-init__'] += 1; } /* Instantiate exported singletons */ var keyframes = _keyframes(generateAlphabeticName, stringifyRules, css); var secondary = /*#__PURE__*/Object.freeze({ css: css, keyframes: keyframes, createGlobalStyle: createGlobalStyle, isStyledComponent: isStyledComponent, ThemeConsumer: ThemeConsumer, ThemeProvider: ThemeProvider, withTheme: withTheme, ServerStyleSheet: ServerStyleSheet, StyleSheetManager: StyleSheetManager, __DO_NOT_USE_OR_YOU_WILL_BE_HAUNTED_BY_SPOOKY_GHOSTS: __DO_NOT_USE_OR_YOU_WILL_BE_HAUNTED_BY_SPOOKY_GHOSTS }); var reactIs_production_min$2 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports,"__esModule",{value:!0}); var b="function"===typeof Symbol&&Symbol.for,c=b?Symbol.for("react.element"):60103,d=b?Symbol.for("react.portal"):60106,e=b?Symbol.for("react.fragment"):60107,f=b?Symbol.for("react.strict_mode"):60108,g=b?Symbol.for("react.profiler"):60114,h=b?Symbol.for("react.provider"):60109,k=b?Symbol.for("react.context"):60110,l=b?Symbol.for("react.async_mode"):60111,m=b?Symbol.for("react.forward_ref"):60112,n=b?Symbol.for("react.placeholder"):60113; function q(a){if("object"===typeof a&&null!==a){var p=a.$$typeof;switch(p){case c:switch(a=a.type,a){case l:case e:case g:case f:return a;default:switch(a=a&&a.$$typeof,a){case k:case m:case h:return a;default:return p}}case d:return p}}}exports.typeOf=q;exports.AsyncMode=l;exports.ContextConsumer=k;exports.ContextProvider=h;exports.Element=c;exports.ForwardRef=m;exports.Fragment=e;exports.Profiler=g;exports.Portal=d;exports.StrictMode=f; exports.isValidElementType=function(a){return "string"===typeof a||"function"===typeof a||a===e||a===l||a===g||a===f||a===n||"object"===typeof a&&null!==a&&("function"===typeof a.then||a.$$typeof===h||a.$$typeof===k||a.$$typeof===m)};exports.isAsyncMode=function(a){return q(a)===l};exports.isContextConsumer=function(a){return q(a)===k};exports.isContextProvider=function(a){return q(a)===h};exports.isElement=function(a){return "object"===typeof a&&null!==a&&a.$$typeof===c}; exports.isForwardRef=function(a){return q(a)===m};exports.isFragment=function(a){return q(a)===e};exports.isProfiler=function(a){return q(a)===g};exports.isPortal=function(a){return q(a)===d};exports.isStrictMode=function(a){return q(a)===f}; }); unwrapExports(reactIs_production_min$2); var reactIs_production_min_1$1 = reactIs_production_min$2.typeOf; var reactIs_production_min_2$1 = reactIs_production_min$2.AsyncMode; var reactIs_production_min_3$1 = reactIs_production_min$2.ContextConsumer; var reactIs_production_min_4$1 = reactIs_production_min$2.ContextProvider; var reactIs_production_min_5$1 = reactIs_production_min$2.Element; var reactIs_production_min_6$1 = reactIs_production_min$2.ForwardRef; var reactIs_production_min_7$1 = reactIs_production_min$2.Fragment; var reactIs_production_min_8$1 = reactIs_production_min$2.Profiler; var reactIs_production_min_9$1 = reactIs_production_min$2.Portal; var reactIs_production_min_10$1 = reactIs_production_min$2.StrictMode; var reactIs_production_min_11$1 = reactIs_production_min$2.isValidElementType; var reactIs_production_min_12$1 = reactIs_production_min$2.isAsyncMode; var reactIs_production_min_13$1 = reactIs_production_min$2.isContextConsumer; var reactIs_production_min_14$1 = reactIs_production_min$2.isContextProvider; var reactIs_production_min_15$1 = reactIs_production_min$2.isElement; var reactIs_production_min_16$1 = reactIs_production_min$2.isForwardRef; var reactIs_production_min_17$1 = reactIs_production_min$2.isFragment; var reactIs_production_min_18$1 = reactIs_production_min$2.isProfiler; var reactIs_production_min_19$1 = reactIs_production_min$2.isPortal; var reactIs_production_min_20$1 = reactIs_production_min$2.isStrictMode; var reactIs_development$2 = createCommonjsModule(function (module, exports) { { (function() { Object.defineProperty(exports, '__esModule', { value: true }); // The Symbol used to tag the ReactElement-like types. If there is no native Symbol // nor polyfill, then a plain number is used for performance. var hasSymbol = typeof Symbol === 'function' && Symbol.for; var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7; var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca; var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb; var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc; var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2; var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd; var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace; var REACT_ASYNC_MODE_TYPE = hasSymbol ? Symbol.for('react.async_mode') : 0xeacf; var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0; var REACT_PLACEHOLDER_TYPE = hasSymbol ? Symbol.for('react.placeholder') : 0xead1; function isValidElementType(type) { return typeof type === 'string' || typeof type === 'function' || // Note: its typeof might be other than 'symbol' or 'number' if it's a polyfill. type === REACT_FRAGMENT_TYPE || type === REACT_ASYNC_MODE_TYPE || type === REACT_PROFILER_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_PLACEHOLDER_TYPE || typeof type === 'object' && type !== null && (typeof type.then === 'function' || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE); } function typeOf(object) { if (typeof object === 'object' && object !== null) { var $$typeof = object.$$typeof; switch ($$typeof) { case REACT_ELEMENT_TYPE: var type = object.type; switch (type) { case REACT_ASYNC_MODE_TYPE: case REACT_FRAGMENT_TYPE: case REACT_PROFILER_TYPE: case REACT_STRICT_MODE_TYPE: return type; default: var $$typeofType = type && type.$$typeof; switch ($$typeofType) { case REACT_CONTEXT_TYPE: case REACT_FORWARD_REF_TYPE: case REACT_PROVIDER_TYPE: return $$typeofType; default: return $$typeof; } } case REACT_PORTAL_TYPE: return $$typeof; } } return undefined; } var AsyncMode = REACT_ASYNC_MODE_TYPE; var ContextConsumer = REACT_CONTEXT_TYPE; var ContextProvider = REACT_PROVIDER_TYPE; var Element = REACT_ELEMENT_TYPE; var ForwardRef = REACT_FORWARD_REF_TYPE; var Fragment = REACT_FRAGMENT_TYPE; var Profiler = REACT_PROFILER_TYPE; var Portal = REACT_PORTAL_TYPE; var StrictMode = REACT_STRICT_MODE_TYPE; function isAsyncMode(object) { return typeOf(object) === REACT_ASYNC_MODE_TYPE; } function isContextConsumer(object) { return typeOf(object) === REACT_CONTEXT_TYPE; } function isContextProvider(object) { return typeOf(object) === REACT_PROVIDER_TYPE; } function isElement(object) { return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; } function isForwardRef(object) { return typeOf(object) === REACT_FORWARD_REF_TYPE; } function isFragment(object) { return typeOf(object) === REACT_FRAGMENT_TYPE; } function isProfiler(object) { return typeOf(object) === REACT_PROFILER_TYPE; } function isPortal(object) { return typeOf(object) === REACT_PORTAL_TYPE; } function isStrictMode(object) { return typeOf(object) === REACT_STRICT_MODE_TYPE; } exports.typeOf = typeOf; exports.AsyncMode = AsyncMode; exports.ContextConsumer = ContextConsumer; exports.ContextProvider = ContextProvider; exports.Element = Element; exports.ForwardRef = ForwardRef; exports.Fragment = Fragment; exports.Profiler = Profiler; exports.Portal = Portal; exports.StrictMode = StrictMode; exports.isValidElementType = isValidElementType; exports.isAsyncMode = isAsyncMode; exports.isContextConsumer = isContextConsumer; exports.isContextProvider = isContextProvider; exports.isElement = isElement; exports.isForwardRef = isForwardRef; exports.isFragment = isFragment; exports.isProfiler = isProfiler; exports.isPortal = isPortal; exports.isStrictMode = isStrictMode; })(); } }); unwrapExports(reactIs_development$2); var reactIs_development_1$1 = reactIs_development$2.typeOf; var reactIs_development_2$1 = reactIs_development$2.AsyncMode; var reactIs_development_3$1 = reactIs_development$2.ContextConsumer; var reactIs_development_4$1 = reactIs_development$2.ContextProvider; var reactIs_development_5$1 = reactIs_development$2.Element; var reactIs_development_6$1 = reactIs_development$2.ForwardRef; var reactIs_development_7$1 = reactIs_development$2.Fragment; var reactIs_development_8$1 = reactIs_development$2.Profiler; var reactIs_development_9$1 = reactIs_development$2.Portal; var reactIs_development_10$1 = reactIs_development$2.StrictMode; var reactIs_development_11$1 = reactIs_development$2.isValidElementType; var reactIs_development_12$1 = reactIs_development$2.isAsyncMode; var reactIs_development_13$1 = reactIs_development$2.isContextConsumer; var reactIs_development_14$1 = reactIs_development$2.isContextProvider; var reactIs_development_15$1 = reactIs_development$2.isElement; var reactIs_development_16$1 = reactIs_development$2.isForwardRef; var reactIs_development_17$1 = reactIs_development$2.isFragment; var reactIs_development_18$1 = reactIs_development$2.isProfiler; var reactIs_development_19$1 = reactIs_development$2.isPortal; var reactIs_development_20$1 = reactIs_development$2.isStrictMode; var reactIs$1 = createCommonjsModule(function (module) { { module.exports = reactIs_development$2; } }); var reactIs_1 = reactIs$1.isValidElementType; // function constructWithOptions(componentConstructor, tag) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : EMPTY_OBJECT; if (!reactIs_1(tag)) { throw new StyledComponentsError(1, String(tag)); } /* This is callable directly as a template function */ // $FlowFixMe: Not typed to avoid destructuring arguments var templateFunction = function templateFunction() { return componentConstructor(tag, options, css.apply(undefined, arguments)); }; /* If config methods are called, wrap up a new template function and merge options */ templateFunction.withConfig = function (config) { return constructWithOptions(componentConstructor, tag, _extends({}, options, config)); }; templateFunction.attrs = function (attrs) { return constructWithOptions(componentConstructor, tag, _extends({}, options, { attrs: _extends({}, options.attrs || EMPTY_OBJECT, attrs) })); }; return templateFunction; } function memoize(fn) { var cache = {}; return function (arg) { if (cache[arg] === undefined) cache[arg] = fn(arg); return cache[arg]; }; } var reactPropsRegex = /^((children|dangerouslySetInnerHTML|key|ref|autoFocus|defaultValue|defaultChecked|innerHTML|suppressContentEditableWarning|valueLink|accept|acceptCharset|accessKey|action|allow|allowFullScreen|allowTransparency|alt|async|autoComplete|autoPlay|capture|cellPadding|cellSpacing|challenge|charSet|checked|cite|classID|className|cols|colSpan|content|contentEditable|contextMenu|controls|controlsList|coords|crossOrigin|data|dateTime|default|defer|dir|disabled|download|draggable|encType|form|formAction|formEncType|formMethod|formNoValidate|formTarget|frameBorder|headers|height|hidden|high|href|hrefLang|htmlFor|httpEquiv|id|inputMode|integrity|is|keyParams|keyType|kind|label|lang|list|loop|low|marginHeight|marginWidth|max|maxLength|media|mediaGroup|method|min|minLength|multiple|muted|name|nonce|noValidate|open|optimum|pattern|placeholder|playsInline|poster|preload|profile|radioGroup|readOnly|referrerPolicy|rel|required|reversed|role|rows|rowSpan|sandbox|scope|scoped|scrolling|seamless|selected|shape|size|sizes|slot|span|spellCheck|src|srcDoc|srcLang|srcSet|start|step|style|summary|tabIndex|target|title|type|useMap|value|width|wmode|wrap|about|datatype|inlist|prefix|property|resource|typeof|vocab|autoCapitalize|autoCorrect|autoSave|color|itemProp|itemScope|itemType|itemID|itemRef|results|security|unselectable|accentHeight|accumulate|additive|alignmentBaseline|allowReorder|alphabetic|amplitude|arabicForm|ascent|attributeName|attributeType|autoReverse|azimuth|baseFrequency|baselineShift|baseProfile|bbox|begin|bias|by|calcMode|capHeight|clip|clipPathUnits|clipPath|clipRule|colorInterpolation|colorInterpolationFilters|colorProfile|colorRendering|contentScriptType|contentStyleType|cursor|cx|cy|d|decelerate|descent|diffuseConstant|direction|display|divisor|dominantBaseline|dur|dx|dy|edgeMode|elevation|enableBackground|end|exponent|externalResourcesRequired|fill|fillOpacity|fillRule|filter|filterRes|filterUnits|floodColor|floodOpacity|focusable|fontFamily|fontSize|fontSizeAdjust|fontStretch|fontStyle|fontVariant|fontWeight|format|from|fr|fx|fy|g1|g2|glyphName|glyphOrientationHorizontal|glyphOrientationVertical|glyphRef|gradientTransform|gradientUnits|hanging|horizAdvX|horizOriginX|ideographic|imageRendering|in|in2|intercept|k|k1|k2|k3|k4|kernelMatrix|kernelUnitLength|kerning|keyPoints|keySplines|keyTimes|lengthAdjust|letterSpacing|lightingColor|limitingConeAngle|local|markerEnd|markerMid|markerStart|markerHeight|markerUnits|markerWidth|mask|maskContentUnits|maskUnits|mathematical|mode|numOctaves|offset|opacity|operator|order|orient|orientation|origin|overflow|overlinePosition|overlineThickness|panose1|paintOrder|pathLength|patternContentUnits|patternTransform|patternUnits|pointerEvents|points|pointsAtX|pointsAtY|pointsAtZ|preserveAlpha|preserveAspectRatio|primitiveUnits|r|radius|refX|refY|renderingIntent|repeatCount|repeatDur|requiredExtensions|requiredFeatures|restart|result|rotate|rx|ry|scale|seed|shapeRendering|slope|spacing|specularConstant|specularExponent|speed|spreadMethod|startOffset|stdDeviation|stemh|stemv|stitchTiles|stopColor|stopOpacity|strikethroughPosition|strikethroughThickness|string|stroke|strokeDasharray|strokeDashoffset|strokeLinecap|strokeLinejoin|strokeMiterlimit|strokeOpacity|strokeWidth|surfaceScale|systemLanguage|tableValues|targetX|targetY|textAnchor|textDecoration|textRendering|textLength|to|transform|u1|u2|underlinePosition|underlineThickness|unicode|unicodeBidi|unicodeRange|unitsPerEm|vAlphabetic|vHanging|vIdeographic|vMathematical|values|vectorEffect|version|vertAdvY|vertOriginX|vertOriginY|viewBox|viewTarget|visibility|widths|wordSpacing|writingMode|x|xHeight|x1|x2|xChannelSelector|xlinkActuate|xlinkArcrole|xlinkHref|xlinkRole|xlinkShow|xlinkTitle|xlinkType|xmlBase|xmlns|xmlnsXlink|xmlLang|xmlSpace|y|y1|y2|yChannelSelector|z|zoomAndPan|for|class)|(on[A-Z].*)|((data|aria|x)-.*))$/i; var index$1 = memoize(reactPropsRegex.test.bind(reactPropsRegex)); // // var isHMREnabled = typeof module !== 'undefined' && module.hot; /* combines hashStr (murmurhash) and nameGenerator for convenience */ var hasher = function hasher(str) { return generateAlphabeticName(murmurhash(str)); }; /* ComponentStyle is all the CSS-specific stuff, not the React-specific stuff. */ var ComponentStyle = function () { function ComponentStyle(rules, attrs, componentId) { classCallCheck(this, ComponentStyle); this.rules = rules; this.isStatic = !isHMREnabled && isStaticRules(rules, attrs); this.componentId = componentId; if (!StyleSheet.master.hasId(componentId)) { var placeholder = ['.' + componentId + ' {}']; StyleSheet.master.deferredInject(componentId, placeholder); } } /* * Flattens a rule set into valid CSS * Hashes it, wraps the whole chunk in a .hash1234 {} * Returns the hash to be injected on render() * */ ComponentStyle.prototype.generateAndInjectStyles = function generateAndInjectStyles(executionContext, styleSheet) { var isStatic = this.isStatic, componentId = this.componentId, lastClassName = this.lastClassName; if (IS_BROWSER && isStatic && lastClassName !== undefined && styleSheet.hasNameForId(componentId, lastClassName)) { return lastClassName; } var flatCSS = flatten(this.rules, executionContext, styleSheet); var name = hasher(this.componentId + flatCSS.join('')); if (!styleSheet.hasNameForId(componentId, name)) { styleSheet.inject(this.componentId, stringifyRules(flatCSS, '.' + name), name); } this.lastClassName = name; return name; }; ComponentStyle.generateName = function generateName(str) { return hasher(str); }; return ComponentStyle; }(); // var LIMIT = 200; var createWarnTooManyClasses = (function (displayName) { var generatedClasses = {}; var warningSeen = false; return function (className) { if (!warningSeen) { generatedClasses[className] = true; if (Object.keys(generatedClasses).length >= LIMIT) { // Unable to find latestRule in test environment. /* eslint-disable no-console, prefer-template */ console.warn('Over ' + LIMIT + ' classes were generated for component ' + displayName + '. \n' + 'Consider using the attrs method, together with a style object for frequently changed styles.\n' + 'Example:\n' + ' const Component = styled.div.attrs({\n' + ' style: ({ background }) => ({\n' + ' background,\n' + ' }),\n' + ' })`width: 100%;`\n\n' + ' <Component />'); warningSeen = true; generatedClasses = {}; } } }; }); // var escapeRegex = /[[\].#*$><+~=|^:(),"'`-]+/g; var dashesAtEnds = /(^-|-$)/g; /** * TODO: Explore using CSS.escape when it becomes more available * in evergreen browsers. */ function escape(str) { return str // Replace all possible CSS selectors .replace(escapeRegex, '-') // Remove extraneous hyphens at the start and end .replace(dashesAtEnds, ''); } // function isTag(target) /* : %checks */{ return typeof target === 'string'; } // function generateDisplayName(target) { return isTag(target) ? 'styled.' + target : 'Styled(' + getComponentName(target) + ')'; } // function isDerivedReactComponent(fn) { return !!(fn && fn.prototype && fn.prototype.isReactComponent); } // // HACK for generating all static styles without needing to allocate // an empty execution context every single time... var STATIC_EXECUTION_CONTEXT$1 = {}; var identifiers = {}; /* We depend on components having unique IDs */ function generateId(componentStyleInstance, _displayName, parentComponentId) { var displayName = typeof _displayName !== 'string' ? 'sc' : escape(_displayName); /** * This ensures uniqueness if two components happen to share * the same displayName. */ var nr = (identifiers[displayName] || 0) + 1; identifiers[displayName] = nr; var componentId = displayName + '-' + componentStyleInstance.generateName(displayName + nr); return parentComponentId ? parentComponentId + '-' + componentId : componentId; } var warnInnerRef = once(function () { return ( // eslint-disable-next-line no-console console.warn('The "innerRef" API has been removed in styled-components v4 in favor of React 16 ref forwarding, use "ref" instead like a typical component.') ); }); // $FlowFixMe var BaseStyledComponent = function (_PureComponent) { inherits(BaseStyledComponent, _PureComponent); function BaseStyledComponent() { classCallCheck(this, BaseStyledComponent); var _this = possibleConstructorReturn(this, _PureComponent.call(this)); _this.attrs = {}; _this.renderOuter = _this.renderOuter.bind(_this); _this.renderInner = _this.renderInner.bind(_this); return _this; } BaseStyledComponent.prototype.render = function render() { return React__default.createElement( StyleSheetConsumer, null, this.renderOuter ); }; BaseStyledComponent.prototype.renderOuter = function renderOuter(styleSheet) { this.styleSheet = styleSheet; return React__default.createElement( ThemeConsumer, null, this.renderInner ); }; BaseStyledComponent.prototype.renderInner = function renderInner(theme) { var _props$forwardedClass = this.props.forwardedClass, componentStyle = _props$forwardedClass.componentStyle, defaultProps = _props$forwardedClass.defaultProps, styledComponentId = _props$forwardedClass.styledComponentId, target = _props$forwardedClass.target; var isTargetTag = isTag(this.props.as || target); var generatedClassName = void 0; if (componentStyle.isStatic) { generatedClassName = this.generateAndInjectStyles(STATIC_EXECUTION_CONTEXT$1, this.props, this.styleSheet); } else if (theme !== undefined) { var determinedTheme = determineTheme(this.props, theme, defaultProps); generatedClassName = this.generateAndInjectStyles(determinedTheme, this.props, this.styleSheet); } else { generatedClassName = this.generateAndInjectStyles(this.props.theme || EMPTY_OBJECT, this.props, this.styleSheet); } var propsForElement = _extends({}, this.attrs); var key = void 0; for (key in this.props) { if (key === 'forwardedClass' || key === 'as') continue;else if (key === 'innerRef') { warnInnerRef(); } else if (key === 'forwardedRef') propsForElement.ref = this.props[key]; // Don't pass through non HTML tags through to HTML elements else if (!isTargetTag || index$1(key)) { propsForElement[key] = key === 'style' && key in this.attrs ? _extends({}, this.attrs[key], this.props[key]) : this.props[key]; } } propsForElement.className = [this.props.className, styledComponentId, this.attrs.className, generatedClassName].filter(Boolean).join(' '); return React.createElement(this.props.as || target, propsForElement); }; BaseStyledComponent.prototype.buildExecutionContext = function buildExecutionContext(theme, props, attrs) { var context = _extends({}, props, { theme: theme }); if (attrs === undefined) return context; this.attrs = {}; var attr = void 0; var key = void 0; /* eslint-disable guard-for-in */ for (key in attrs) { attr = attrs[key]; this.attrs[key] = isFunction(attr) && !isDerivedReactComponent(attr) && !isStyledComponent(attr) ? attr(context) : attr; } /* eslint-enable */ return _extends({}, context, this.attrs); }; BaseStyledComponent.prototype.generateAndInjectStyles = function generateAndInjectStyles(theme, props) { var styleSheet = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : StyleSheet.master; var _props$forwardedClass2 = props.forwardedClass, attrs = _props$forwardedClass2.attrs, componentStyle = _props$forwardedClass2.componentStyle, warnTooManyClasses = _props$forwardedClass2.warnTooManyClasses; // statically styled-components don't need to build an execution context object, // and shouldn't be increasing the number of class names if (componentStyle.isStatic && attrs === undefined) { return componentStyle.generateAndInjectStyles(STATIC_EXECUTION_CONTEXT$1, styleSheet); } else { var executionContext = this.buildExecutionContext(theme, props, props.forwardedClass.attrs); var className = componentStyle.generateAndInjectStyles(executionContext, styleSheet); if (warnTooManyClasses !== undefined) { warnTooManyClasses(className); } return className; } }; return BaseStyledComponent; }(React.PureComponent); function createStyledComponent(target, options, rules) { var isTargetStyledComp = isStyledComponent(target); var isClass = !isTag(target); var _options$displayName = options.displayName, displayName = _options$displayName === undefined ? generateDisplayName(target) : _options$displayName, _options$componentId = options.componentId, componentId = _options$componentId === undefined ? generateId(ComponentStyle, options.displayName, options.parentComponentId) : _options$componentId, _options$ParentCompon = options.ParentComponent, ParentComponent = _options$ParentCompon === undefined ? BaseStyledComponent : _options$ParentCompon, attrs = options.attrs; var styledComponentId = options.displayName && options.componentId ? escape(options.displayName) + '-' + options.componentId : options.componentId || componentId; // fold the underlying StyledComponent attrs up (implicit extend) var finalAttrs = // $FlowFixMe isTargetStyledComp && target.attrs ? _extends({}, target.attrs, attrs) : attrs; var componentStyle = new ComponentStyle(isTargetStyledComp ? // fold the underlying StyledComponent rules up (implicit extend) // $FlowFixMe target.componentStyle.rules.concat(rules) : rules, finalAttrs, styledComponentId); /** * forwardRef creates a new interim component, which we'll take advantage of * instead of extending ParentComponent to create _another_ interim class */ var StyledComponent = React__default.forwardRef(function (props, ref) { return React__default.createElement(ParentComponent, _extends({}, props, { forwardedClass: StyledComponent, forwardedRef: ref })); }); // $FlowFixMe StyledComponent.attrs = finalAttrs; // $FlowFixMe StyledComponent.componentStyle = componentStyle; StyledComponent.displayName = displayName; // $FlowFixMe StyledComponent.styledComponentId = styledComponentId; // fold the underlying StyledComponent target up since we folded the styles // $FlowFixMe StyledComponent.target = isTargetStyledComp ? target.target : target; // $FlowFixMe StyledComponent.withComponent = function withComponent(tag) { var previousComponentId = options.componentId, optionsToCopy = objectWithoutProperties(options, ['componentId']); var newComponentId = previousComponentId && previousComponentId + '-' + (isTag(tag) ? tag : escape(getComponentName(tag))); var newOptions = _extends({}, optionsToCopy, { attrs: finalAttrs, componentId: newComponentId, ParentComponent: ParentComponent }); return createStyledComponent(tag, newOptions, rules); }; { // $FlowFixMe StyledComponent.warnTooManyClasses = createWarnTooManyClasses(displayName); } if (isClass) { hoistNonReactStatics_cjs(StyledComponent, target, { // all SC-specific things should not be hoisted attrs: true, componentStyle: true, displayName: true, styledComponentId: true, target: true, warnTooManyClasses: true, withComponent: true }); } return StyledComponent; } // // Thanks to ReactDOMFactories for this handy list! var domElements = ['a', 'abbr', 'address', 'area', 'article', 'aside', 'audio', 'b', 'base', 'bdi', 'bdo', 'big', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'cite', 'code', 'col', 'colgroup', 'data', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'div', 'dl', 'dt', 'em', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'iframe', 'img', 'input', 'ins', 'kbd', 'keygen', 'label', 'legend', 'li', 'link', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meta', 'meter', 'nav', 'noscript', 'object', 'ol', 'optgroup', 'option', 'output', 'p', 'param', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'script', 'section', 'select', 'small', 'source', 'span', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'track', 'u', 'ul', 'var', 'video', 'wbr', // SVG 'circle', 'clipPath', 'defs', 'ellipse', 'foreignObject', 'g', 'image', 'line', 'linearGradient', 'mask', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'stop', 'svg', 'text', 'tspan']; // var styled = function styled(tag) { return constructWithOptions(createStyledComponent, tag); }; // Shorthands for all valid HTML Elements domElements.forEach(function (domElement) { styled[domElement] = styled(domElement); }); // /** * eliminates the need to do styled.default since the other APIs * are directly assigned as properties to the main function * */ // eslint-disable-next-line guard-for-in for (var key in secondary) { styled[key] = secondary[key]; } return styled; }(React)); ;window.styled = styled; //# sourceMappingURL=styled-components.js.map
admin/src/phase/LoadingPhase.js
zentrope/webl
// // Copyright (c) 2017 Keith Irwin // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation, either version 3 of the License, // or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. import React from 'react'; class LoadingPhase extends React.PureComponent { render() { return ( <div className="Loading"> <h1>Loading...</h1> </div> ) } } export { LoadingPhase }
test/components/Footer/Legal.spec.js
intrepion/sign-up-client-jsonapi-reactjs-foundation
import expect from 'expect'; import React from 'react'; import TestUtils from 'react-addons-test-utils'; import Legal from '../../../components/Footer/Legal'; function setup() { let props = { }; let renderer = TestUtils.createRenderer(); renderer.render(<Legal {...props} />); let output = renderer.getRenderOutput(); return { props, output, renderer, }; } describe('Legal component', () => { it('should render correctly', () => { const { output } = setup(); expect(output.type).toBe('ul'); expect(output.props.className).toBe('menu'); let [ li1, li2, li3 ] = output.props.children; expect(li1.type).toBe('li'); expect(li1.props.children.props.children).toBe('Terms'); expect(li2.type).toBe('li'); expect(li2.props.children.props.children).toBe('Privacy'); expect(li3.type).toBe('li'); expect(li3.props.children.type).toBe('span'); expect(li3.props.children.props.className).toBe('footer-item'); expect(li3.props.children.props.children).toBe('©9999 Company'); }); });
src/components/common/top-menu.js
AvaKathrynShaw/My-React-Material-Dashboard
import React from 'react'; import IconMenu from 'material-ui/IconMenu'; import MenuItem from 'material-ui/MenuItem'; import IconButton from 'material-ui/IconButton/IconButton'; import MoreVertIcon from 'material-ui/svg-icons/navigation/more-vert'; import {blue500, red500, greenA200, white, deepOrange300} from 'material-ui/styles/colors'; var FontAwesome = require('react-fontawesome'); require('./demo.css'); const IconMenuExampleSimple = () => ( <div> <IconMenu iconButtonElement={ <FontAwesome name='ellipsis-v' />} anchorOrigin={{horizontal: 'left', vertical: 'bottom'}} targetOrigin={{horizontal: 'left', vertical: 'bottom'}} > <MenuItem primaryText="Refresh" /> <MenuItem primaryText="Send feedback" /> <MenuItem primaryText="Settings" /> <MenuItem primaryText="Help" /> <MenuItem primaryText="Close" /> </IconMenu> </div> ); export default IconMenuExampleSimple;
ajax/libs/ngOfficeUiFabric/0.12.2/ngOfficeUiFabric.min.js
dakshshah96/cdnjs
/*! * ngOfficeUIFabric * http://ngofficeuifabric.com * Angular 1.x directives for Microsoft's Office UI Fabric * https://angularjs.org & https://dev.office.com/fabric * v0.12.2 */ !function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t(require("angular"));else if("function"==typeof define&&define.amd)define(["angular"],t);else{var i=t("object"==typeof exports?require("angular"):e.angular);for(var n in i)("object"==typeof exports?exports:e)[n]=i[n]}}(this,function(e){return function(e){function t(n){if(i[n])return i[n].exports;var r=i[n]={exports:{},id:n,loaded:!1};return e[n].call(r.exports,r,r.exports,t),r.loaded=!0,r.exports}var i={};return t.m=e,t.c=i,t.p="",t(0)}([function(e,t,i){i(1),e.exports=i(3)},function(e,t,i){"use strict";var n=i(2);t.module=n.module("officeuifabric.core",[])},function(t,i){t.exports=e},function(e,t,i){"use strict";var n=i(2),r=i(4),o=i(5),s=i(8),a=i(11),c=i(13),l=i(14),u=i(15),d=i(16),f=i(17),p=i(19),m=i(20),h=i(21),v=i(23),g=i(24),y=i(25),b=i(29),P=i(30),k=i(32),C=i(33),$=i(35),T=i(37),w=i(42),S=i(45),E=i(48),x=i(49),I=i(50),M=i(52),D=i(55),B=i(57),O=i(58),L=i(62);t.module=n.module("officeuifabric.components",[r.module.name,o.module.name,s.module.name,a.module.name,c.module.name,l.module.name,u.module.name,d.module.name,f.module.name,p.module.name,m.module.name,h.module.name,v.module.name,g.module.name,y.module.name,b.module.name,P.module.name,k.module.name,C.module.name,$.module.name,L.module.name,T.module.name,w.module.name,S.module.name,E.module.name,x.module.name,I.module.name,M.module.name,D.module.name,B.module.name,O.module.name])},function(e,t,i){"use strict";var n=i(2),r=function(){function e(){this.restrict="E",this.require="^uifBreadcrumb",this.transclude=!0,this.replace=!0,this.template='<li class="ms-Breadcrumb-listItem"><a class="ms-Breadcrumb-itemLink" ng-href="{{ngHref}}" tabindex="{{uifTabindex}}" ng-transclude></a><i class="ms-Breadcrumb-chevron ms-Icon ms-Icon--chevronRight"></i></li>',this.scope={ngHref:"@"}}return e.factory=function(){var t=function(){return new e};return t},e.prototype.link=function(e,t,i,n,r){var o=Array.prototype.indexOf.call(t.parent().children(),t[0])+2;e.uifTabindex=o},e}();t.BreadcrumbLinkDirective=r;var o=function(){function e(e,t){this.href=e,this.linkText=t}return e}();t.BreadcrumbLink=o;var s=function(){function e(t,i,r){this.$scope=t,this.$document=i,this.$window=r;var o=n.element(r);t.visibleElements=4,t.overflowMenuOpen=!1,t.isOverflow=function(){var e=!1;return e=n.isDefined(t.uifBreadcrumbLinks)&&t.uifBreadcrumbLinks.length>t.visibleElements},t.overflowElements=function(){return t.isOverflow()?t.uifBreadcrumbLinks.length-t.visibleElements:0},t.openOverflow=function(e){e.stopPropagation(),t.overflowMenuOpen=!0},t.adjustVisibleElements=function(){var i=r.innerWidth,n=i>e._breakingWidth?4:2;n!==t.visibleElements&&(t.visibleElements=n,t.$apply())},i.find("html").on("click",function(e){t.overflowMenuOpen=!1,t.$apply()}),o.on("resize",function(){t.adjustVisibleElements()})}return e.$inject=["$scope","$document","$window"],e._breakingWidth=639,e}();t.BreadcrumbController=s;var a=function(){function e(){this.restrict="E",this.replace=!0,this.template='<div class="ms-Breadcrumb" ng-class="{\'is-overflow\': isOverflow()}"><div class="ms-Breadcrumb-overflow"><div class="ms-Breadcrumb-overflowButton ms-Icon ms-Icon--ellipsis" ng-click="openOverflow($event)" tabindex="1"></div><i class="ms-Breadcrumb-chevron ms-Icon ms-Icon--chevronRight"></i><div class="ms-Breadcrumb-overflowMenu" ng-class="{\'is-open\': overflowMenuOpen}"><ul class="ms-ContextualMenu is-open"><li class="ms-ContextualMenu-item" ng-repeat="link in uifBreadcrumbLinks | limitTo:overflowElements()"><a class="ms-ContextualMenu-link" ng-href="{{link.href}}">{{link.linkText}}</a></li></ul></div></div><ul class="ms-Breadcrumb-list"><uif-breadcrumb-link ng-repeat="link in uifBreadcrumbLinks | limitTo:-visibleElements" ng-href="{{link.href}}">{{link.linkText}}</uif-breadcrumb-link></ul></div>',this.controller=s,this.require="uifBreadcrumb",this.scope={uifBreadcrumbLinks:"="}}return e.factory=function(){var t=function(){return new e};return t},e.prototype.link=function(e,t,i,n){e.adjustVisibleElements()},e}();t.BreadcrumbDirective=a,t.module=n.module("officeuifabric.components.breadcrumb",["officeuifabric.components"]).directive("uifBreadcrumb",a.factory()).directive("uifBreadcrumbLink",r.factory())},function(e,t,i){"use strict";var n=i(2),r=i(6),o=i(7),s=function(){function e(e){this.$log=e}return e.$inject=["$log"],e}(),a=function(){function e(e){var t=this;this.$log=e,this.restrict="E",this.transclude=!0,this.replace=!0,this.scope={},this.controller=s,this.controllerAs="button",this.templateOptions={},this.template=function(e,i){switch(!n.isUndefined(i.uifType)&&n.isUndefined(r.ButtonTypeEnum[i.uifType])&&t.$log.error("Error [ngOfficeUiFabric] officeuifabric.components.button - Unsupported button: The button ('"+i.uifType+"') is not supported by the Office UI Fabric. Supported options are listed here: https://github.com/ngOfficeUIFabric/ng-officeuifabric/blob/master/src/components/button/buttonTypeEnum.ts"),i.uifType){case r.ButtonTypeEnum[r.ButtonTypeEnum.primary]:return n.isUndefined(i.ngHref)?t.templateOptions[o.ButtonTemplateType.primaryButton]:t.templateOptions[o.ButtonTemplateType.primaryLink];case r.ButtonTypeEnum[r.ButtonTypeEnum.command]:return n.isUndefined(i.ngHref)?t.templateOptions[o.ButtonTemplateType.commandButton]:t.templateOptions[o.ButtonTemplateType.commandLink];case r.ButtonTypeEnum[r.ButtonTypeEnum.compound]:return n.isUndefined(i.ngHref)?t.templateOptions[o.ButtonTemplateType.compoundButton]:t.templateOptions[o.ButtonTemplateType.compoundLink];case r.ButtonTypeEnum[r.ButtonTypeEnum.hero]:return n.isUndefined(i.ngHref)?t.templateOptions[o.ButtonTemplateType.heroButton]:t.templateOptions[o.ButtonTemplateType.heroLink];default:return n.isUndefined(i.ngHref)?t.templateOptions[o.ButtonTemplateType.actionButton]:t.templateOptions[o.ButtonTemplateType.actionLink]}},this._populateHtmlTemplates()}return e.factory=function(){var t=function(t){return new e(t)};return t.$inject=["$log"],t},e.prototype.compile=function(e,t,i){return{post:this.postLink,pre:this.preLink}},e.prototype.preLink=function(e,t,i,n,r){i.$observe("disabled",function(t){e.disabled=!!t}),t.on("click",function(t){e.disabled&&t.preventDefault()})},e.prototype.postLink=function(e,t,i,o,s){if(n.isUndefined(i.uifType)||i.uifType===r.ButtonTypeEnum[r.ButtonTypeEnum.primary]||i.uifType===r.ButtonTypeEnum[r.ButtonTypeEnum.compound]){var a=t.find("uif-icon");0!==a.length&&(a.remove(),o.$log.error("Error [ngOfficeUiFabric] officeuifabric.components.button - Icon not allowed in primary or compound buttons: The primary & compound button does not support including icons in the body. The icon has been removed but may cause rendering errors. Consider buttons that support icons such as command or hero."))}s(function(e){var o;switch(i.uifType){case r.ButtonTypeEnum[r.ButtonTypeEnum.command]:for(var s=0;s<e.length;s++)"SPAN"===e[s].tagName&&(o=n.element("<span></span>"),o.addClass("ms-Button-label").append(e[s]),t.append(o)),"UIF-ICON"===e[s].tagName&&(o=n.element("<span></span>"),o.addClass("ms-Button-icon").append(e[s]),t.append(o));break;case r.ButtonTypeEnum[r.ButtonTypeEnum.compound]:for(var s=0;s<e.length;s++)"SPAN"===e[s].tagName&&("ng-scope"===e[s].classList[0]&&1===e[s].classList.length?(o=n.element("<span></span>"),o.addClass("ms-Button-label").append(e[s]),t.append(o)):t.append(e[s]));break;case r.ButtonTypeEnum[r.ButtonTypeEnum.hero]:for(var s=0;s<e.length;s++)"SPAN"===e[s].tagName&&(o=n.element("<span></span>"),o.addClass("ms-Button-label").append(e[s]),t.append(o)),"UIF-ICON"===e[s].tagName&&(o=n.element("<span></span>"),o.addClass("ms-Button-icon").append(e[s]),t.append(o))}})},e.prototype._populateHtmlTemplates=function(){this.templateOptions[o.ButtonTemplateType.actionButton]='<button class="ms-Button" ng-class="{\'is-disabled\': disabled}">\n <span class="ms-Button-label" ng-transclude></span>\n </button>',this.templateOptions[o.ButtonTemplateType.actionLink]='<a class="ms-Button" ng-class="{\'is-disabled\': disabled}">\n <span class="ms-Button-label" ng-transclude></span>\n </a>',this.templateOptions[o.ButtonTemplateType.primaryButton]='<button class="ms-Button ms-Button--primary" ng-class="{\'is-disabled\': disabled}">\n <span class="ms-Button-label" ng-transclude></span>\n </button>',this.templateOptions[o.ButtonTemplateType.primaryLink]='<a class="ms-Button ms-Button--primary" ng-class="{\'is-disabled\': disabled}">\n <span class="ms-Button-label" ng-transclude></span>\n </a>',this.templateOptions[o.ButtonTemplateType.commandButton]='<button class="ms-Button ms-Button--command" ng-class="{\'is-disabled\': disabled}"></button>',this.templateOptions[o.ButtonTemplateType.commandLink]='<a class="ms-Button ms-Button--command" ng-class="{\'is-disabled\': disabled}"></a>',this.templateOptions[o.ButtonTemplateType.compoundButton]='<button class="ms-Button ms-Button--compound" ng-class="{\'is-disabled\': disabled}"></button>',this.templateOptions[o.ButtonTemplateType.compoundLink]='<a class="ms-Button ms-Button--compound" ng-class="{\'is-disabled\': disabled}"></a>',this.templateOptions[o.ButtonTemplateType.heroButton]='<button class="ms-Button ms-Button--hero" ng-class="{\'is-disabled\': disabled}"></button>',this.templateOptions[o.ButtonTemplateType.heroLink]='<a class="ms-Button ms-Button--hero" ng-class="{\'is-disabled\': disabled}"></a>'},e}();t.ButtonDirective=a;var c=function(){function e(){this.restrict="E",this.require="^uifButton",this.transclude=!0,this.replace=!0,this.scope=!1,this.template='<span class="ms-Button-description" ng-transclude></span>'}return e.factory=function(){var t=function(){return new e};return t},e}();t.ButtonDescriptionDirective=c,t.module=n.module("officeuifabric.components.button",["officeuifabric.components"]).directive("uifButton",a.factory()).directive("uifButtonDescription",c.factory())},function(e,t){"use strict";!function(e){e[e.primary=0]="primary",e[e.command=1]="command",e[e.compound=2]="compound",e[e.hero=3]="hero"}(t.ButtonTypeEnum||(t.ButtonTypeEnum={}));t.ButtonTypeEnum},function(e,t){"use strict";!function(e){e[e.actionButton=0]="actionButton",e[e.actionLink=1]="actionLink",e[e.primaryButton=2]="primaryButton",e[e.primaryLink=3]="primaryLink",e[e.commandButton=4]="commandButton",e[e.commandLink=5]="commandLink",e[e.compoundButton=6]="compoundButton",e[e.compoundLink=7]="compoundLink",e[e.heroButton=8]="heroButton",e[e.heroLink=9]="heroLink"}(t.ButtonTemplateType||(t.ButtonTemplateType={}));t.ButtonTemplateType},function(e,t,i){"use strict";var n=i(2),r=i(9),o=i(10),s=function(){function e(e,t){this.$scope=e,this.$log=t}return e.$inject=["$scope","$log"],e}();t.CalloutController=s;var a=function(){function e(){this.restrict="E",this.transclude=!0,this.replace=!1,this.scope=!1,this.template='<div class="ms-Callout-header"><p class="ms-Callout-title" ng-transclude></p></div>'}return e.factory=function(){var t=function(){return new e};return t},e.prototype.link=function(e,t,i,r){var o=t.parent().parent();if(!n.isUndefined(o)&&o.hasClass("ms-Callout-main")){var s=t.detach();o.prepend(s)}},e}();t.CalloutHeaderDirective=a;var c=function(){function e(){this.restrict="E",this.transclude=!0,this.replace=!1,this.scope=!1,this.template='<div class="ms-Callout-content"><p class="ms-Callout-subText" ng-transclude></p></div>'}return e.factory=function(){var t=function(){return new e};return t},e}();t.CalloutContentDirective=c;var l=function(){function e(){this.restrict="E",this.transclude=!0,this.replace=!1,this.scope=!1,this.template='<div class="ms-Callout-actions" ng-transclude></div>',this.require="^?uifCallout"}return e.factory=function(){var t=function(){return new e};return t},e.prototype.link=function(e,t,i,r){n.isObject(r)&&r.$scope.$watch("hasSeparator",function(e){if(e)for(var i=t.children().eq(0).children(),n=0;n<i.length;n++){var r=i.eq(n);r.addClass("ms-Callout-action");for(var o=r.find("span"),s=0;s<o.length;s++){var a=o.eq(s);(a.hasClass("ms-Button-label")||a.hasClass("ms-Button-icon"))&&a.addClass("ms-Callout-actionText")}}})},e}();t.CalloutActionsDirective=l;var u=function(){function e(){this.restrict="E",this.transclude=!0,this.replace=!1,this.template="<div class=\"ms-Callout ms-Callout--arrow{{arrowDirection}}\" ng-class=\"{'ms-Callout--actionText': hasSeparator, 'ms-Callout--OOBE': uifType=='oobe', 'ms-Callout--Peek': uifType=='peek', 'ms-Callout--close': closeButton}\">"+'<div class="ms-Callout-main"><div class="ms-Callout-inner" ng-transclude></div></div></div>',this.require=["uifCallout"],this.scope={ngShow:"=?",uifType:"@"},this.controller=s}return e.factory=function(){var t=function(){return new e};return t},e.prototype.link=function(e,t,i,s){var a=s[0];if(i.$observe("uifType",function(e){n.isUndefined(r.CalloutType[e])&&a.$log.error('Error [ngOfficeUiFabric] officeuifabric.components.callout - "'+e+'" is not a valid value for uifType. It should be oobe or peek')}),i.uifArrow||(e.arrowDirection="Left"),i.$observe("uifArrow",function(t){if(n.isUndefined(o.CalloutArrow[t]))return void a.$log.error('Error [ngOfficeUiFabric] officeuifabric.components.callout - "'+t+'" is not a valid value for uifArrow. It should be left, right, top, bottom.');var i=t.charAt(0).toUpperCase();i+=t.slice(1).toLowerCase(),e.arrowDirection=i}),e.hasSeparator=!n.isUndefined(i.uifActionText)||!n.isUndefined(i.uifSeparator),!n.isUndefined(i.uifClose)){e.closeButton=!0;var c=n.element('<button class="ms-Callout-close" type="button"><i class="ms-Icon ms-Icon--x"></i></button>'),l=t.find("div").eq(0);l.append(c),c.bind("click",function(t){e.ngShow=!1,e.closeButtonClicked=!0,e.$apply()})}t.bind("mouseenter",function(t){e.isMouseOver=!0,e.$apply()}),t.bind("mouseleave",function(t){e.isMouseOver=!1,e.$apply()}),e.$watch("ngShow",function(t,i){var n=!t&&e.closeButtonClicked;return n?void(e.ngShow=e.closeButtonClicked=!1):void(t||(e.ngShow=e.isMouseOver))}),e.$watch("isMouseOver",function(t,i){!t&&i&&(e.closeButton||(e.ngShow=!1))})},e}();t.CalloutDirective=u,t.module=n.module("officeuifabric.components.callout",["officeuifabric.components"]).directive("uifCallout",u.factory()).directive("uifCalloutHeader",a.factory()).directive("uifCalloutContent",c.factory()).directive("uifCalloutActions",l.factory())},function(e,t){"use strict";!function(e){e[e.oobe=0]="oobe",e[e.peek=1]="peek"}(t.CalloutType||(t.CalloutType={}));t.CalloutType},function(e,t){"use strict";!function(e){e[e.left=0]="left",e[e.right=1]="right",e[e.top=2]="top",e[e.bottom=3]="bottom"}(t.CalloutArrow||(t.CalloutArrow={}));t.CalloutArrow},function(e,t,i){"use strict";var n=i(2),r=i(12),o=function(){function e(e){this.$log=e}return e.$inject=["$log"],e}();t.ChoicefieldOptionController=o;var s=function(){function e(){this.template='<div class="ms-ChoiceField"><input id="{{::$id}}" class="ms-ChoiceField-input" type="{{uifType}}" value="{{value}}" ng-disabled="disabled" ng-model="ngModel" ng-true-value="{{ngTrueValue}}" ng-false-value="{{ngFalseValue}}" /><label for="{{::$id}}" class="ms-ChoiceField-field"><span class="ms-Label" ng-transclude></span></label></div>',this.restrict="E",this.require=["uifChoicefieldOption","^?uifChoicefieldGroup"],this.replace=!0,this.transclude=!0,this.scope={ngFalseValue:"@",ngModel:"=",ngTrueValue:"@",uifType:"@",value:"@"},this.controller=o}return e.factory=function(){var t=function(){return new e};return t},e.prototype.compile=function(e,t,i){var n=e.find("input");return"ngModel"in t||n.removeAttr("ng-model"),{pre:this.preLink}},e.prototype.preLink=function(e,t,i,n,o){var s=n[0],a=n[1];if(e.$watch("uifType",function(e,t){void 0===r.ChoicefieldType[e]&&s.$log.error('Error [ngOfficeUiFabric] officeuifabric.components.choicefield - "'+e+'" is not a valid value for uifType. Supported options are listed here: https://github.com/ngOfficeUIFabric/ng-officeuifabric/blob/master/src/components/choicefield/choicefieldTypeEnum.ts')}),null!=a){var c=function(){var e=a.getViewValue()===i.value;t.find("input").prop("checked",e)};a.addRender(c),i.$observe("value",c),t.on("$destroy",function(){a.removeRender(c)})}var l=e.$parent.$parent,u=function(){e.disabled="disabled"in i&&i.disabled,e.disabled=e.disabled||null!=l&&l.disabled};e.$watch(function(){return t.attr("disabled")},function(e){u()}),e.$watch(function(){return null==l?"":l.disabled},function(e){u()}),u(),t.on("click",function(t){e.disabled||e.$apply(function(){null!=a&&a.setViewValue(i.value,t)})})},e}();t.ChoicefieldOptionDirective=s;var a=function(){function e(){this.template='<div class="ms-ChoiceFieldGroup-title"><ng-transclude /></div>',this.transclude=!0}return e.factory=function(){var t=function(){return new e};return t},e}();t.ChoicefieldGroupTitleDirective=a;var c=function(){function e(e,t){this.$element=e,this.$scope=t,this.renderFns=[]}return e.prototype.init=function(){var e=this;"undefined"!=typeof this.$scope.ngModel&&null!=this.$scope.ngModel&&(this.$scope.ngModel.$render=function(){e.render()},this.render())},e.prototype.addRender=function(e){this.renderFns.push(e)},e.prototype.removeRender=function(e){this.renderFns.splice(this.renderFns.indexOf(e))},e.prototype.setViewValue=function(e,t){this.$scope.ngModel.$setViewValue(e,t),this.render()},e.prototype.getViewValue=function(){if("undefined"!=typeof this.$scope.ngModel&&null!=this.$scope.ngModel)return this.$scope.ngModel.$viewValue},e.prototype.render=function(){for(var e=0;e<this.renderFns.length;e++)this.renderFns[e]()},e.$inject=["$element","$scope"],e}();t.ChoicefieldGroupController=c;var l=function(){function e(){this.template='<div class="ms-ChoiceFieldGroup"><ng-transclude /></div>',this.restrict="E",this.transclude=!0,this.require=["uifChoicefieldGroup","?ngModel"],this.controller=c,this.scope={}}return e.factory=function(){var t=function(){return new e};return t},e.prototype.compile=function(e,t,i){return{pre:this.preLink}},e.prototype.preLink=function(e,t,i,n){var r=n[0],o=n[1];e.ngModel=o,r.init(),e.$watch(function(){return t.attr("disabled")},function(t){e.disabled="undefined"!=typeof t}),e.disabled="disabled"in i},e}();t.ChoicefieldGroupDirective=l,t.module=n.module("officeuifabric.components.choicefield",["officeuifabric.components"]).directive("uifChoicefieldOption",s.factory()).directive("uifChoicefieldGroup",l.factory()).directive("uifChoicefieldGroupTitle",a.factory())},function(e,t){"use strict";!function(e){e[e.radio=0]="radio",e[e.checkbox=1]="checkbox"}(t.ChoicefieldType||(t.ChoicefieldType={}));t.ChoicefieldType},function(e,t,i){"use strict";var n=i(2),r=function(){function e(){this.restrict="E",this.template='<div class="ms-CommandBar" ng-transclude></div>',this.transclude=!0,this.replace=!0,this.scope={placeholder:"@",uifSearchTerm:"="}}return e.factory=function(){var t=function(){return new e};return t},e.prototype.link=function(e,t,i){e.focusSearchInput=function(){e.isSearchActive=!0,angular.element(t[0].querySelector(".ms-CommandBarSearch-input"))[0].focus()},e.clearSearchTerm=function(){e.uifSearchTerm=null,e.isSearchActive=!1}},e}();t.CommandBarDirective=r;var o=function(){function e(){this.restrict="E",this.replace=!0,this.transclude=!0,this.template='<div class="ms-CommandBarSearch" ng-class="$parent.isSearchActive == true ? \'is-active\' : \'\';">\n <input class="ms-CommandBarSearch-input"\n type="text"\n placeholder="{{$parent.placeholder}}"\n tabindex="1"\n ng-focus="$parent.isSearchActive = true;"\n ng-blur="$parent.isSearchActive = false;"\n ng-model="$parent.uifSearchTerm">\n <div class="ms-CommandBarSearch-iconWrapper ms-CommandBarSearch-iconSearchWrapper"\n ng-click="$parent.focusSearchInput()">\n <uif-icon uif-type="search" />\n </div>\n <div class="ms-CommandBarSearch-iconWrapper ms-CommandBarSearch-iconClearWrapper ms-font-s"\n ng-mousedown="$parent.clearSearchTerm()">\n <uif-icon uif-type="x"/>\n </div>\n </div>'}return e.factory=function(){var t=function(){return new e};return t},e}();t.CommandBarSearchDirective=o;var s=function(){function e(){this.restrict="E",this.template='<div class="ms-CommandBar-sideCommands" ng-transclude></div>',this.replace=!0,this.transclude=!0}return e.factory=function(){var t=function(){return new e};return t},e}();t.CommandBarSideDirective=s;var a=function(){function e(e){this.$timeout=e,this.restrict="E",this.template='<div class="ms-CommandBar-mainArea">\n <ng-transclude></ng-transclude>\n <div ng-if="uifShowOverflow"\n class="ms-CommandBarItem ms-CommandBarItem--iconOnly ms-CommandBarItem-overflow"\n ng-class="overflowVisible == true ? \'is-visible\' : \'\';">\n <div class="ms-CommandBarItem-linkWrapper"\n ng-click="openOverflowMenu()">\n <a class="ms-CommandBarItem-link" tabindex="2">\n <uif-icon uif-type="ellipsis" />\n </a>\n </div>\n </div>\n </div>',this.replace=!0,this.transclude=!0,this.controller=c,this.scope={uifShowOverflow:"="}}return e.factory=function(){var t=function(t){return new e(t)};return t.$inject=["$timeout"],t},e.prototype.compile=function(e,t,i){return{post:this.postLink}},e.prototype.postLink=function(e,t,i,n){e.openOverflowMenu=function(){e.overflowMenuOpen=!e.overflowMenuOpen;var i;i=' <uif-contextual-menu class="ms-CommandBar-overflowMenu"\n uif-is-open="overflowMenuOpen"\n uif-close-on-click="false">',angular.element(t[0].querySelector(".ms-CommandBarItem-overflow .ms-CommandBarItem-linkWrapper ul")).remove(),angular.forEach(e.hiddenItems,function(e){i+=e.submenu?'<uif-contextual-menu-item ng-model="hiddenItems['+e.i+"]\"\n ng-click='openOverflowItem(hiddenItems["+e.i+"])'\n uif-text='hiddenItems["+e.i+"].text'\n ng-show='hiddenItems["+e.i+"].visible'\n uif-type=\"subMenu\">\n <uif-contextual-menu>\n <uif-contextual-menu-item\n ng-click='openOverflowItem(subitem)'\n uif-text='subitem.text'\n uif-type=\"link\"\n ng-repeat=\"subitem in hiddenItems["+e.i+'].submenuitems track by $index"/>\n </uif-contextual-menu>\n </uif-contextual-menu-item>':'<uif-contextual-menu-item ng-model="hiddenItems['+e.i+"]\"\n ng-click='openOverflowItem(hiddenItems["+e.i+"])'\n uif-text='hiddenItems["+e.i+"].text'\n ng-show='hiddenItems["+e.i+'].visible\'\n uif-type="link">\n </uif-contextual-menu-item>'}),i+="</<uif-contextual-menu>";var r;r=t[0].querySelector(".ms-CommandBarItem-overflow .ms-CommandBarItem-linkWrapper"),angular.element(r).append(n.$compile(i)(e))},e.loadMenuItems=function(t){var i=0,n=0;e.commandItems=[],angular.forEach(t,function(t){angular.element(t).hasClass("ms-CommandBarItem-overflow")!==!0&&(i+=t.offsetWidth,e.commandItems.push({index:n,offset:i}),n++)})},e.openOverflowItem=function(e){e.submenu?(e.submenuitems=[],angular.forEach(e.submenu.children,function(t){var i;i={},i.text=t.innerText,i.menuType="item",i.childitem=!0,i.i=e.submenuitems.length,i.parent=e.i,e.submenuitems.push(i)})):n.$timeout(function(){if(e.childitem===!0){var i=void 0;i=t[0].querySelectorAll(".ms-CommandBarItem")[e.parent].querySelectorAll(".ms-ContextualMenu-item")[e.i],angular.element(i).triggerHandler("click")}else angular.element(t[0].querySelectorAll(".ms-CommandBarItem")[e.i]).triggerHandler("click")},1)},e.toggleItemVisibility=function(){var i;i=angular.element(t[0].querySelectorAll(".ms-CommandBar-mainArea .ms-CommandBarItem")),window.innerWidth<640&&e.mobileSwitch===!1?(e.loadMenuItems(i),e.mobileSwitch=!0):window.innerWidth>=640&&e.mobileSwitch===!0&&(e.loadMenuItems(i),e.mobileSwitch=!1),angular.forEach(e.commandItems,function(i){i.offset>=t.prop("offsetWidth")-200?(angular.element(t[0].querySelectorAll(".ms-CommandBarItem")[i.index]).addClass("is-hidden"),e.hiddenItems[i.index].visible=!0,e.overflowVisible=!0):(angular.element(t[0].querySelectorAll(".ms-CommandBarItem")[i.index]).removeClass("is-hidden"),e.hiddenItems[i.index].visible=!1,e.overflowVisible=!1)}),n.$timeout(function(){e.$apply()},1)},e.$on("uif-command-bar-resize",function(){e.overflowMenuOpen=!1,e.toggleItemVisibility()}),angular.element(window).bind("resize",function(){e.$broadcast("uif-command-bar-resize")}),angular.element(document).ready(function(){e.loadMenuItems(angular.element(t[0].querySelectorAll(".ms-CommandBarItem"))),e.toggleItemVisibility()})},e}();t.CommandBarMainDirective=a;var c=function(){function e(e,t,i,n){this.$scope=e,this.$element=t,this.$compile=i,this.$timeout=n}return e.prototype.addOverflowItem=function(e){null==this.$scope.hiddenItems&&(this.$scope.hiddenItems=[]),e.i=this.$scope.hiddenItems.length,this.$scope.hiddenItems.push(e)},e.$inject=["$scope","$element","$compile","$timeout"],e}();t.CommandBarMainController=c;var l=function(){function e(){this.restrict="E",this.template='<div class="ms-CommandBarItem"><div class="ms-CommandBarItem-linkWrapper"> <a class="ms-CommandBarItem-link"> </a></div></div>',this.transclude=!0,this.replace=!0,this.controller=c,this.require="^?uifCommandBarMain"}return e.factory=function(){var t=function(){return new e};return t},e.prototype.compile=function(e,t,i){return{post:this.postLink}},e.prototype.postLink=function(e,t,i,n,r){r(function(e){var i;i={};for(var r=0;r<e.length;r++)"UIF-ICON"===e[r].tagName&&angular.element(t[0].querySelector("a.ms-CommandBarItem-link")).append(e[r]),"SPAN"===e[r].tagName&&(e[r].classList.contains("ms-CommandBarItem-commandText")||e[r].classList.add("ms-CommandBarItem-commandText"),e[r].className.indexOf("ms-font-")===-1&&e[r].classList.add("ms-font-m"),angular.element(t[0].querySelector("a.ms-CommandBarItem-link")).append(e[r]),i.text=e[r].innerText),"UL"===e[r].tagName&&e[r].classList.contains("ms-ContextualMenu")&&(angular.element(t).append(e[r]),i.submenu=e[r]);null!==n&&(null==i.submenu?i.menuType="link":i.menuType="subMenu",n.addOverflowItem(i))}),0===angular.element(t[0].querySelector(".ms-CommandBarItem-link > uif-icon")).length&&angular.element(t[0].querySelector(".ms-CommandBarItem")).addClass("ms-CommandBarItem-hasTextOnly")},e}();t.CommandBarItemDirective=l,t.module=n.module("officeuifabric.components.commandbar",["officeuifabric.components"]).directive("uifCommandBar",r.factory()).directive("uifCommandBarSearch",o.factory()).directive("uifCommandBarItem",l.factory()).directive("uifCommandBarMain",a.factory()).directive("uifCommandBarSide",s.factory())},function(e,t,i){"use strict";var n=i(2),r=function(){function e(){this.replace=!0,this.restrict="E",this.transclude=!0,this.scope=!0,this.template='<span class="uif-content" ng-transclude></span>'}return e.factory=function(){var t=function(){return new e};return t},e.directiveName="uifContent",e}();t.ContentDirective=r,t.module=n.module("officeuifabric.components.content",["officeuifabric.components"]).directive(r.directiveName,r.factory())},function(e,t,i){"use strict";var n,r=i(2);!function(e){e[e.link=0]="link",e[e.divider=1]="divider",e[e.header=2]="header",e[e.subMenu=3]="subMenu"}(n||(n={}));var o=function(){function e(e){var t=this;this.$log=e,this.restrict="E",this.require="^uifContextualMenu",this.transclude=!0,this.controller=s,this.replace=!0,this.scope={isSelected:"=?uifIsSelected",onClick:"&ngClick",text:"=?uifText",type:"@uifType"},this.templateTypes={},this.template=function(e,i){var o=i.uifType;return r.isUndefined(o)?t.templateTypes[n.link]:(void 0===n[o]&&t.$log.error("Error [ngOfficeUiFabric] officeuifabric.components.contextualmenu - unsupported menu type:\nthe type '"+o+"' is not supported by ng-Office UI Fabric as valid type for context menu.Supported types can be found under MenuItemTypes enum here:\nhttps://github.com/ngOfficeUIFabric/ng-officeuifabric/blob/master/src/components/contextualmenu/contextualMenu.ts"),t.templateTypes[n[o]])},this.link=function(e,i,n,o,s){"boolean"!=typeof e.isSelected&&void 0!==e.isSelected&&o.$log.error("Error [ngOfficeUiFabric] officeuifabric.components.contextualmenu - invalid attribute type: 'uif-is-selected'.\nThe type '"+typeof e.isSelected+"' is not supported as valid type for 'uif-is-selected' attribute for <uif-contextual-menu-item />. The valid type is boolean."),n.$observe("disabled",function(t){e.isDisabled=!!t}),t.transcludeChilds(e,i,s),e.selectItem=function(t){o.isMultiSelectionMenu()||o.deselectItems(),r.isUndefined(e.isSelected)&&!e.isDisabled?e.isSelected=!0:e.isSelected=!e.isSelected,e.hasChildMenu?o.closeSubMenus(e.$id):(o.closeSubMenus(null,!0),o.isRootMenu()||o.deselectItems(!0)),e.hasChildMenu&&e.childMenuCtrl.openMenu(),r.isUndefined(e.onClick)||e.onClick(),t.stopPropagation()},e.$on("uif-menu-deselect",function(){e.isSelected=!1}),e.$on("uif-menu-close",function(t,i){e.hasChildMenu&&e.$id!==i&&e.childMenuCtrl.closeMenu()})},this.templateTypes[n.subMenu]='<li class="ms-ContextualMenu-item">\n <a class="ms-ContextualMenu-link ms-ContextualMenu-link--hasMenu"\n ng-class="{\'is-selected\': isSelected, \'is-disabled\': isDisabled}" ng-click="selectItem($event)" href>\n <span class=\'uif-item-content\'></span></a>\n <i class="ms-ContextualMenu-subMenuIcon ms-Icon ms-Icon--chevronRight"></i>\n <div class="uif-context-submenu"></div>\n </li>',this.templateTypes[n.link]='<li class="ms-ContextualMenu-item">\n <a class="ms-ContextualMenu-link" ng-class="{\'is-selected\': isSelected, \'is-disabled\': isDisabled}"\n ng-click="selectItem($event)" href><span class=\'uif-item-content\'></span></a>\n </li>',this.templateTypes[n.header]="\n <li class=\"ms-ContextualMenu-item ms-ContextualMenu-item--header\">\n <span class='uif-item-content'></span>\n </li>",this.templateTypes[n.divider]='<li class="ms-ContextualMenu-item ms-ContextualMenu-item--divider"></li>'}return e.factory=function(){var t=function(t){return new e(t)};return t.$inject=["$log"],t},e.prototype.transcludeChilds=function(e,t,i){var n=this;i(function(i){var r=n.hasItemContent(i);r||e.text||e.hasChildMenu||"divider"===e.type||n.$log.error("Error [ngOfficeUiFabric] officeuifabric.components.contextualmenu - you need to provide a text for a contextual menu item.\nFor <uif-contextual-menu-item> you need to specify either 'uif-text' as attribute or <uif-content> as a child directive"),n.insertItemContent(i,e,t),n.insertSubMenu(i,e,t)})},e.prototype.insertItemContent=function(e,t,i){var n=angular.element(i[0].querySelector(".uif-item-content"));if(this.hasItemContent(e))for(var r=0;r<e.length;r++){var o=angular.element(e[r]);if(o.hasClass("uif-content")){n.replaceWith(o);break}}else n.replaceWith(angular.element("<span>"+t.text+"</span>")); },e.prototype.insertSubMenu=function(e,t,i){for(var n=0;n<e.length;n++){var r=angular.element(e[n]);r.hasClass("ms-ContextualMenu")&&angular.element(i[0].querySelector(".uif-context-submenu")).replaceWith(r)}},e.prototype.hasItemContent=function(e){for(var t=0;t<e.length;t++){var i=angular.element(e[t]);if(i.hasClass("uif-content"))return!0}return!1},e.directiveName="uifContextualMenuItem",e}();t.ContextualMenuItemDirective=o;var s=function(){function e(e,t){this.$scope=e,this.$element=t}return e.prototype.setChildMenu=function(e){this.$scope.hasChildMenu=!0,this.$scope.childMenuCtrl=e},e.$inject=["$scope","$element"],e}();t.ContextualMenuItemController=s;var a=function(){function e(){this.restrict="E",this.require=e.directiveName,this.transclude=!0,this.template='<ul class="ms-ContextualMenu" ng-transclude></ul>',this.replace=!0,this.controller=c,this.scope={closeOnClick:"@uifCloseOnClick",isOpen:"=?uifIsOpen",multiselect:"@uifMultiselect"}}return e.factory=function(){var t=function(){return new e};return t},e.prototype.link=function(e,t,i,n){var s=function(t){r.isUndefined(t)?e.closeOnClick=!0:e.closeOnClick="true"===t.toString().toLowerCase()};s(e.closeOnClick),i.$observe("uifCloseOnClick",s);var a=t.controller(o.directiveName);r.isUndefined(a)||a.setChildMenu(n),r.isUndefined(e.multiselect)||"true"!==e.multiselect.toLowerCase()||t.addClass("ms-ContextualMenu--multiselect")},e.directiveName="uifContextualMenu",e}();t.ContextualMenuDirective=a;var c=function(){function e(e,t,i,n){var s=this;this.$scope=e,this.$animate=t,this.$element=i,this.$log=n,this.onRootMenuClosed=[],this.isOpenClassName="is-open",r.isUndefined(i.controller(o.directiveName))&&(e.isRootMenu=!0),e.$watch("isOpen",function(e){"boolean"!=typeof e&&void 0!==e&&s.$log.error("Error [ngOfficeUiFabric] officeuifabric.components.contextualmenu - invalid attribute type: 'uif-is-open'.\nThe type '"+typeof e+"' is not supported as valid type for 'uif-is-open' attribute for <uif-contextual-menu />. The valid type is boolean."),t[e?"addClass":"removeClass"](i,s.isOpenClassName)}),this.onRootMenuClosed.push(function(){s.closeMenu(),s.deselectItems(!0)}),e.$on("uif-menu-close",function(){e.isRootMenu&&e.closeOnClick&&s.onRootMenuClosed.forEach(function(e){e()})})}return e.prototype.deselectItems=function(e){this.$scope.$broadcast("uif-menu-deselect"),e&&this.$scope.$emit("uif-menu-deselect")},e.prototype.closeSubMenus=function(e,t){this.$scope.$broadcast("uif-menu-close",e),t&&this.$scope.$emit("uif-menu-close")},e.prototype.openMenu=function(){this.$scope.isOpen=!0},e.prototype.closeMenu=function(){this.$scope.isOpen=!1},e.prototype.isRootMenu=function(){return this.$scope.isRootMenu},e.prototype.isMultiSelectionMenu=function(){return!r.isUndefined(this.$scope.multiselect)&&"true"===this.$scope.multiselect.toLowerCase()},e.prototype.isMenuOpened=function(){return this.$element.hasClass("is-open")},e.$inject=["$scope","$animate","$element","$log"],e}();t.ContextualMenuController=c,t.module=r.module("officeuifabric.components.contextualmenu",["officeuifabric.components"]).directive(a.directiveName,a.factory()).directive(o.directiveName,o.factory())},function(e,t,i){"use strict";var n=i(2),r=function(){function e(e,t){this.$scope=t,this.isPickingYears=!1,this.isPickingMonths=!1,this.displayDateFormat="d mmmm, yyyy",this.jElement=$(e[0]),this.displayDateFormat=t.uifDateFormat,t.ctrl=this}return e.prototype.range=function(e,t,i){i=i||1;for(var n=[],r=e;r<=t;r+=i)n.push(r);return n},e.prototype.getPicker=function(){return this.jElement.find(".ms-TextField-field").pickadate("picker")},e.prototype.setValue=function(e){this.getPicker().set("select",e),this.changeHighlightedDate(e.getFullYear(),e.getMonth(),e.getDate())},e.prototype.initDatepicker=function(e){var t=this;this.jElement.find(".ms-TextField-field").pickadate({clear:"",close:"",format:t.displayDateFormat,klass:{active:"ms-DatePicker-input--active",box:"ms-DatePicker-dayPicker",day:"ms-DatePicker-day",disabled:"ms-DatePicker-day--disabled",focused:"ms-DatePicker-picker--focused",frame:"ms-DatePicker-frame",header:"ms-DatePicker-header",holder:"ms-DatePicker-holder",infocus:"ms-DatePicker-day--infocus",input:"ms-DatePicker-input",month:"ms-DatePicker-month",now:"ms-DatePicker-day--today",opened:"ms-DatePicker-picker--opened",outfocus:"ms-DatePicker-day--outfocus",picker:"ms-DatePicker-picker",selected:"ms-DatePicker-day--selected",table:"ms-DatePicker-table",weekdays:"ms-DatePicker-weekday",wrap:"ms-DatePicker-wrap",year:"ms-DatePicker-year"},onStart:function(){t.initCustomView()},today:"",weekdaysShort:["S","M","T","W","T","F","S"]});var i=this.getPicker();i.on({open:function(){t.scrollUp()},set:function(t){var n=i.get("select","yyyy-mm-dd");e.$setViewValue(n)}})},e.prototype.initCustomView=function(){var e=this.jElement.find(".ms-DatePicker-monthComponents"),t=this.jElement.find(".ms-DatePicker-goToday"),i=this.jElement.find(".ms-DatePicker-monthPicker"),n=this.jElement.find(".ms-DatePicker-yearPicker"),r=this.jElement.find(".ms-DatePicker-wrap"),o=this.getPicker(),s=this;e.appendTo(r),t.appendTo(r),i.appendTo(r),n.appendTo(r),e.on("click",".js-prevMonth",function(e){e.preventDefault();var t=o.get("highlight").month-1;s.changeHighlightedDate(null,t,null),s.$scope.$apply()}),e.on("click",".js-nextMonth",function(e){e.preventDefault();var t=o.get("highlight").month+1;s.changeHighlightedDate(null,t,null),s.$scope.$apply()}),i.on("click",".js-prevYear",function(e){e.preventDefault();var t=o.get("highlight").year-1;s.changeHighlightedDate(t,null,null),s.$scope.$apply()}),i.on("click",".js-nextYear",function(e){e.preventDefault();var t=o.get("highlight").year+1;s.changeHighlightedDate(t,null,null),s.$scope.$apply()}),n.on("click",".js-prevDecade",function(e){e.preventDefault();var t=o.get("highlight").year-10;s.changeHighlightedDate(t,null,null),s.$scope.$apply()}),n.on("click",".js-nextDecade",function(e){e.preventDefault();var t=o.get("highlight").year+10;s.changeHighlightedDate(t,null,null),s.$scope.$apply()}),t.on("click",function(e){e.preventDefault();var t=new Date;o.set("select",t),s.jElement.removeClass("is-pickingMonths").removeClass("is-pickingYears"),s.$scope.$apply()}),i.on("click",".js-changeDate",function(e){e.preventDefault();var t=o.get("highlight"),i=t.year,n=+$(this).attr("data-month"),r=t.day;s.changeHighlightedDate(i,n,r),s.jElement.hasClass("is-pickingMonths")&&s.jElement.removeClass("is-pickingMonths"),s.$scope.$apply()}),n.on("click",".js-changeDate",function(e){e.preventDefault();var t=o.get("highlight"),i=+$(this).attr("data-year"),n=t.month,r=t.day;s.changeHighlightedDate(i,n,r),s.jElement.hasClass("is-pickingYears")&&s.jElement.removeClass("is-pickingYears"),s.$scope.$apply()}),e.on("click",".js-showMonthPicker",function(e){s.isPickingMonths=!s.isPickingMonths,s.$scope.$apply()}),i.on("click",".js-showYearPicker",function(e){s.isPickingYears=!s.isPickingYears,s.$scope.$apply()}),s.$scope.highlightedValue=o.get("highlight")},e.prototype.scrollUp=function(){$("html, body").animate({scrollTop:this.jElement.offset().top},367)},e.prototype.changeHighlightedDate=function(e,t,i){var n=this.getPicker();null==e&&(e=n.get("highlight").year),null==t&&(t=n.get("highlight").month),null==i&&(i=n.get("highlight").date),n.set("highlight",[e,t,i]),this.$scope.highlightedValue=n.get("highlight")},e.$inject=["$element","$scope"],e}();t.DatepickerController=r;var o=function(){function e(){this.template='<div ng-class="{\'ms-DatePicker\': true, \'is-pickingYears\': ctrl.isPickingYears, \'is-pickingMonths\': ctrl.isPickingMonths}"><div class="ms-TextField"><i class="ms-DatePicker-event ms-Icon ms-Icon--event"></i><input class="ms-TextField-field" type="text" placeholder="{{placeholder}}" ng-disabled="isDisabled"></div><div class="ms-DatePicker-monthComponents"><span class="ms-DatePicker-nextMonth js-nextMonth"><i class="ms-Icon ms-Icon--chevronRight"></i></span><span class="ms-DatePicker-prevMonth js-prevMonth"><i class="ms-Icon ms-Icon--chevronLeft"></i></span><div class="ms-DatePicker-headerToggleView js-showMonthPicker"></div></div><span class="ms-DatePicker-goToday js-goToday">Go to today</span><div class="ms-DatePicker-monthPicker"><div class="ms-DatePicker-header"><div class="ms-DatePicker-yearComponents"><span class="ms-DatePicker-nextYear js-nextYear"><i class="ms-Icon ms-Icon--chevronRight"></i></span><span class="ms-DatePicker-prevYear js-prevYear"><i class="ms-Icon ms-Icon--chevronLeft"></i></span></div><div class="ms-DatePicker-currentYear js-showYearPicker">{{highlightedValue.year}}</div></div><div class="ms-DatePicker-optionGrid" ><span ng-repeat="month in monthsArray"ng-class="{\'ms-DatePicker-monthOption js-changeDate\': true, \'is-highlighted\': highlightedValue.month == $index}"data-month="{{$index}}">{{month}}</span></div></div><div class="ms-DatePicker-yearPicker"><div class="ms-DatePicker-decadeComponents"><span class="ms-DatePicker-nextDecade js-nextDecade"><i class="ms-Icon ms-Icon--chevronRight"></i></span><span class="ms-DatePicker-prevDecade js-prevDecade"><i class="ms-Icon ms-Icon--chevronLeft"></i></span></div><div class="ms-DatePicker-currentDecade">{{highlightedValue.year - 10}} - {{highlightedValue.year}}</div><div class="ms-DatePicker-optionGrid"><span ng-class="{\'ms-DatePicker-yearOption js-changeDate\': true,\'is-highlighted\': highlightedValue.year == year}" ng-repeat="year in ctrl.range(highlightedValue.year - 10, highlightedValue.year)"data-year="{{year}}">{{year}}</span></div></div></div>',this.controller=r,this.restrict="E",this.replace=!0,this.scope={placeholder:"@",uifDateFormat:"@",uifMonths:"@"},this.require=["uifDatepicker","?ngModel"]}return e.factory=function(){var t=function(){return new e};return t},e.prototype.compile=function(e,t,i){return{post:this.postLink,pre:this.preLink}},e.prototype.preLink=function(e,t,i,n){if(e.uifMonths||(e.uifMonths="Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec"),e.placeholder||(e.placeholder="Select a date"),e.uifDateFormat||(e.uifDateFormat="d mmmm, yyyy"),e.monthsArray=e.uifMonths.split(","),12!==e.monthsArray.length)throw"Months setting should have 12 months, separated by a comma";i.$observe("disabled",function(t){e.isDisabled=!!t})},e.prototype.postLink=function(e,t,i,n){var r=n[0],o=n[1];r.initDatepicker(o),o.$render=function(){if(""!==o.$modelValue&&"undefined"!=typeof o.$modelValue)if("string"==typeof o.$modelValue){var e=new Date(o.$modelValue);r.setValue(e)}else r.setValue(o.$modelValue)}},e}();t.DatepickerDirective=o,t.module=n.module("officeuifabric.components.datepicker",["officeuifabric.components"]).directive("uifDatepicker",o.factory())},function(e,t,i){"use strict";var n=i(2),r=i(18),o=function(){function e(e){this.$log=e}return e.$inject=["$log"],e}();t.DialogController=o;var s=function(){function e(){this.restrict="E",this.controller=o,this.replace=!0,this.transclude=!0,this.template="<div class=\"ms-Dialog\"ng-class=\"{ 'ms-Dialog--close': uifClose=='true', 'ms-Dialog--lgHeader': uifType=='header', 'ms-Dialog--multiline': uifType=='multiline' }\"><uif-overlay uif-mode=\"{{uifOverlay}}\"></uif-overlay><div class=\"ms-Dialog-main\" ng-transclude></div></div>",this.scope={uifClose:"@",uifOverlay:"@",uifType:"@"}}return e.factory=function(){var t=function(){return new e};return t},e.prototype.link=function(e,t,i,n){e.$watch("uifType",function(t,i){"undefined"!=typeof t&&void 0===r.DialogTypeEnum[t]&&n.$log.error("Error [ngOfficeUiFabric] officeuifabric.components.dialog - Unsupported type:The type ('"+e.uifType+"') is not supported by the Office UI Fabric.Supported options are listed here: https://github.com/ngOfficeUIFabric/ng-officeuifabric/blob/master/src/components/dialog/dialogEnums.ts")})},e}();t.DialogDirective=s;var a=function(){function e(){this.restrict="E",this.replace=!0,this.transclude=!0,this.require="^^uifDialog",this.template='<div class="ms-Dialog-header"><button ng-if="$parent.uifClose" class="ms-Dialog-button ms-Dialog-button--close"><i class="ms-Icon ms-Icon--x"></i></button><ng-transclude></ng-transclude></div>'}return e.factory=function(){var t=function(){return new e};return t},e}();t.DialogHeaderDirective=a;var c=function(){function e(){this.restrict="E",this.replace=!0,this.transclude=!0,this.template='<div class="ms-Dialog-content" ng-transclude></div>'}return e.factory=function(){var t=function(){return new e};return t},e}();t.DialogContentDirective=c;var l=function(){function e(){this.restrict="E",this.replace=!0,this.transclude=!0,this.template='<div class="ms-Dialog-inner" ng-transclude></div>'}return e.factory=function(){var t=function(){return new e};return t},e}();t.DialogInnerDirective=l;var u=function(){function e(){this.restrict="E",this.replace=!0,this.transclude=!0,this.template='<p class="ms-Dialog-subText" ng-transclude></p>'}return e.factory=function(){var t=function(){return new e};return t},e}();t.DialogSubtextDirective=u;var d=function(){function e(e){this.$log=e}return e.$inject=["$log"],e}();t.DialogActionsController=d;var f=function(){function e(){this.restrict="E",this.replace=!0,this.transclude=!0,this.controller=d,this.template="<div class=\"ms-Dialog-actions\"><div ng-class=\"{ 'ms-Dialog-actionsRight': uifPosition=='right'}\"><ng-transclude></ng-transclude></div></div>",this.scope={uifPosition:"@"}}return e.factory=function(){var t=function(){return new e};return t},e.prototype.link=function(e,t,i,n){e.$watch("uifPosition",function(t,i){"undefined"!=typeof t&&void 0===r.DialogActionsPositionEnum[t]&&n.$log.error("Error [ngOfficeUiFabric] officeuifabric.components.dialog - Unsupported type:The type ('"+e.uifPosition+"') is not supported by the Office UI Fabric.Supported options are listed here: https://github.com/ngOfficeUIFabric/ng-officeuifabric/blob/master/src/components/dialog/dialogEnums.ts")})},e}();t.DialogActionsDirective=f,t.module=n.module("officeuifabric.components.dialog",["officeuifabric.components"]).directive("uifDialog",s.factory()).directive("uifDialogHeader",a.factory()).directive("uifDialogContent",c.factory()).directive("uifDialogInner",l.factory()).directive("uifDialogSubtext",u.factory()).directive("uifDialogActions",f.factory())},function(e,t){"use strict";!function(e){e[e.none=0]="none",e[e.header=1]="header",e[e.multiline=2]="multiline"}(t.DialogTypeEnum||(t.DialogTypeEnum={}));t.DialogTypeEnum;!function(e){e[e.none=0]="none",e[e.left=1]="left",e[e.right=2]="right"}(t.DialogActionsPositionEnum||(t.DialogActionsPositionEnum={}));t.DialogActionsPositionEnum},function(e,t,i){"use strict";var n=i(2),r=function(){function e(){this.template='<li class="ms-Dropdown-item" ng-transclude></li>',this.restrict="E",this.require="^uifDropdown",this.replace=!0,this.transclude=!0}return e.factory=function(){var t=function(){return new e};return t},e.prototype.compile=function(e,t,i){return{post:this.postLink}},e.prototype.postLink=function(e,t,i,n,r){if(!n)throw"Dropdown controller not found!";t.on("click",function(r){e.$apply(function(){n.setViewValue(t.find("span").html(),i.value,r)})});var o=""+n.getViewValue();o&&o===i.value&&n.setViewValue(i.title,i.value,null)},e}();t.DropdownOptionDirective=r;var o=function(){function e(e,t,i){this.$element=e,this.$scope=t,this.$document=i}return e.prototype.init=function(){var e=this;this.$element.on("click",function(t){if(!e.$scope.disabled){e.$scope.isOpen=!e.$scope.isOpen,e.$scope.$apply();var i=angular.element(this.querySelector(".ms-Dropdown"))[0].clientWidth;if(angular.element(this.querySelector(".ms-Dropdown-items"))[0].style.width=i+"px",t.stopPropagation(),e.$scope.isOpen){var n=function(){e.$scope.isOpen=!1,e.$scope.$apply(),e.$document.off("click",n)};e.$document.on("click",n),e.$scope.$on("$destroy",function(){e.$document.off("click",n)})}}}),"undefined"!=typeof this.$scope.ngModel&&null!=this.$scope.ngModel&&(this.$scope.ngModel.$render=function(){for(var t=!1,i=e.$element.find("li"),n=0;n<i.length;n++){var r=i[n],o=r.getAttribute("value");if(o===e.$scope.ngModel.$viewValue){e.$scope.selectedTitle=angular.element(r).find("span").html(),t=!0;break}}t||(e.$scope.selectedTitle="")})},e.prototype.setViewValue=function(e,t,i){this.$scope.selectedTitle=e,this.$scope.ngModel.$setViewValue(t,i)},e.prototype.getViewValue=function(){if("undefined"!=typeof this.$scope.ngModel&&null!=this.$scope.ngModel)return this.$scope.ngModel.$viewValue},e.$inject=["$element","$scope","$document"],e}();t.DropdownController=o;var s=function(){function e(){this.template='<div ng-click="dropdownClick" ng-class="{\'ms-Dropdown\' : true, \'is-open\': isOpen, \'is-disabled\': disabled}" tabindex="0"><i class="ms-Dropdown-caretDown ms-Icon ms-Icon--caretDown"></i><span class="ms-Dropdown-title">{{selectedTitle}}</span><ul class="ms-Dropdown-items"><ng-transclude></ng-transclude></ul></div>',this.restrict="E",this.transclude=!0,this.require=["uifDropdown","?ngModel"],this.scope={},this.controller=o}return e.factory=function(){var t=function(){return new e};return t},e.prototype.compile=function(e,t,i){return{pre:this.preLink}},e.prototype.preLink=function(e,t,i,n){var r=n[0],o=n[1];e.ngModel=o,r.init(),e.$watch(function(){return t.attr("disabled")},function(t){e.disabled="undefined"!=typeof t}),e.disabled="disabled"in i},e}();t.DropdownDirective=s,t.module=n.module("officeuifabric.components.dropdown",["officeuifabric.components"]).directive("uifDropdownOption",r.factory()).directive("uifDropdown",s.factory())},function(e,t,i){"use strict";var n=i(2),r=function(){function e(){this.transclude=!0,this.replace=!0,this.restrict="E",this.template='<div class="ms-Facepile">\n <ng-transclude></ng-transclude>\n <div class="ms-Facepile-members">\n <div ng-repeat="member in members track by $index"\n role="button"\n ng-if ="$index < uifOverflowLimit"\n class="ms-Facepile-itemBtn ms-Facepile-itemBtn--member"\n title="{{member.primaryText}}" tabindex="0">\n <uif-persona uif-style="round" uif-size="xsmall" uif-image-url="{{member.icon}}">\n <uif-persona-initials uif-color="{{member.color}}">{{member.initials}}</uif-persona-initials>\n </uif-persona>\n </div>\n <button type="button"\n ng-show="uifOverflowLimit > 0 && members.length > uifOverflowLimit"\n ng-click="overflowPanelIsOpen = true;"\n class="ms-Facepile-itemBtn ms-Facepile-itemBtn--overflow js-overflowPanel is-active">\n <span class="ms-Facepile-overflowText">+{{members.length - uifOverflowLimit}}</span\n </button>\n </div>\n <uif-panel\n uif-type="medium"\n uif-is-open="overflowPanelIsOpen"\n uif-show-overlay="true"\n uif-show-close="true">\n <uif-panel-header>{{members.length}} {{uifFacepileName}}</uif-panel-header>\n <uif-content>\n <div ng-repeat="member in members track by $index" title="{{member.primaryText}}" tabindex="0">\n <uif-persona uif-style="round" uif-size="medium" uif-image-url="{{member.icon}}">\n <uif-persona-initials uif-color="{{member.color}}">{{member.initials}}</uif-persona-initials>\n <uif-persona-primary-text>{{member.primaryText}}</uif-persona-primary-text>\n <uif-persona-secondary-text>{{member.secondaryText}}</uif-persona-secondary-text>\n </uif-persona>\n </div>\n </uif-content>\n </uif-panel>\n </div>',this.scope={members:"=ngModel",uifFacepileName:"@uifFacepileName",uifOverflowLimit:"@"}}return e.factory=function(){var t=function(){return new e};return t},e}();t.FacepileDirective=r;var o=function(){function e(){this.transclude=!0,this.restrict="E",this.template='<button type="button"\n class="ms-Facepile-itemBtn ms-Facepile-itemBtn--addPerson js-addPerson"\n ng-click="peoplepickerPanelIsOpen = true;">\n <i class="ms-Facepile-addPersonIcon ms-Icon ms-Icon--personAdd"></i>\n </button>\n <uif-panel\n uif-type="large"\n uif-is-open="peoplepickerPanelIsOpen"\n uif-show-overlay="true"\n uif-show-close="true">\n <uif-panel-header>{{peoplePickerPlaceholder}}</uif-panel-header>\n <uif-content>\n <uif-people-picker\n uif-people="onFacePileSearch"\n ng-model="parentScope.members"\n uif-search-delay="500"\n uif-type="facePile">\n <uif-selected-people-header>\n {{selectedFacePilePeople.length}} selected person(s)\n </uif-selected-people-header>\n <uif-people-search-more>\n <uif-primary-text uif-search-for-text="You are searching for: ">\n Search organization people\n </uif-primary-text>\n </uif-people-search-more>\n </uif-people-picker>\n </uif-content>\n </uif-panel>',this.scope={onFacePileSearch:"=uifPeople",peoplePickerPlaceholder:"@placeholder"}}return e.factory=function(){var t=function(){return new e};return t},e.prototype.link=function(e,t,i){e.parentScope=e.$parent.$parent},e}();t.FacepileAddIconDirective=o,t.module=n.module("officeuifabric.components.facepile",["officeuifabric.components"]).directive("uifFacepile",r.factory()).directive("uifFacepileAddIcon",o.factory())},function(e,t,i){"use strict";var n=i(2),r=i(22),o=function(){function e(e){this.$log=e}return e.$inject=["$log"],e}(),s=function(){function e(){this.restrict="E",this.template='<i class="ms-Icon ms-Icon--{{uifType}}" aria-hidden="true"></i>',this.scope={uifType:"@"},this.transclude=!0,this.controller=o,this.controllerAs="icon"}return e.factory=function(){var t=function(){return new e};return t},e.prototype.link=function(e,t,i,n){e.$watch("uifType",function(t,i){void 0===r.IconEnum[t]&&n.$log.error("Error [ngOfficeUiFabric] officeuifabric.components.icon - Unsupported icon: The icon ('"+e.uifType+"') is not supported by the Office UI Fabric. Supported options are listed here: https://github.com/ngOfficeUIFabric/ng-officeuifabric/blob/master/src/components/icon/iconEnum.ts")})},e}();t.IconDirective=s,t.module=n.module("officeuifabric.components.icon",["officeuifabric.components"]).directive("uifIcon",s.factory())},function(e,t){"use strict";!function(e){e[e.alert=0]="alert",e[e.alert2=1]="alert2",e[e.alertOutline=2]="alertOutline",e[e.arrowDown=3]="arrowDown",e[e.arrowDown2=4]="arrowDown2",e[e.arrowDownLeft=5]="arrowDownLeft",e[e.arrowDownRight=6]="arrowDownRight",e[e.arrowLeft=7]="arrowLeft",e[e.arrowRight=8]="arrowRight",e[e.arrowUp=9]="arrowUp",e[e.arrowUp2=10]="arrowUp2",e[e.arrowUpLeft=11]="arrowUpLeft",e[e.arrowUpRight=12]="arrowUpRight",e[e.ascending=13]="ascending",e[e.at=14]="at",e[e.attachment=15]="attachment",e[e.bag=16]="bag",e[e.balloon=17]="balloon",e[e.bell=18]="bell",e[e.boards=19]="boards",e[e.bold=20]="bold",e[e.bookmark=21]="bookmark",e[e.books=22]="books",e[e.briefcase=23]="briefcase",e[e.bundle=24]="bundle",e[e.cake=25]="cake",e[e.calendar=26]="calendar",e[e.calendarDay=27]="calendarDay",e[e.calendarPublic=28]="calendarPublic",e[e.calendarWeek=29]="calendarWeek",e[e.calendarWorkWeek=30]="calendarWorkWeek",e[e.camera=31]="camera",e[e.car=32]="car",e[e.caretDown=33]="caretDown",e[e.caretDownLeft=34]="caretDownLeft",e[e.caretDownOutline=35]="caretDownOutline",e[e.caretDownRight=36]="caretDownRight",e[e.caretLeft=37]="caretLeft",e[e.caretLeftOutline=38]="caretLeftOutline",e[e.caretRight=39]="caretRight",e[e.caretRightOutline=40]="caretRightOutline",e[e.caretUp=41]="caretUp",e[e.caretUpLeft=42]="caretUpLeft",e[e.caretUpOutline=43]="caretUpOutline",e[e.caretUpRight=44]="caretUpRight",e[e.cart=45]="cart",e[e.cat=46]="cat",e[e.chart=47]="chart",e[e.chat=48]="chat",e[e.chatAdd=49]="chatAdd",e[e.check=50]="check",e[e.checkbox=51]="checkbox",e[e.checkboxCheck=52]="checkboxCheck",e[e.checkboxEmpty=53]="checkboxEmpty",e[e.checkboxMixed=54]="checkboxMixed",e[e.checkPeople=55]="checkPeople",e[e.chevronDown=56]="chevronDown",e[e.chevronLeft=57]="chevronLeft",e[e.chevronRight=58]="chevronRight",e[e.chevronsDown=59]="chevronsDown",e[e.chevronsLeft=60]="chevronsLeft",e[e.chevronsRight=61]="chevronsRight",e[e.chevronsUp=62]="chevronsUp",e[e.chevronThickDown=63]="chevronThickDown",e[e.chevronThickLeft=64]="chevronThickLeft",e[e.chevronThickRight=65]="chevronThickRight",e[e.chevronThickUp=66]="chevronThickUp",e[e.chevronThinDown=67]="chevronThinDown",e[e.chevronThinLeft=68]="chevronThinLeft",e[e.chevronThinRight=69]="chevronThinRight",e[e.chevronThinUp=70]="chevronThinUp",e[e.chevronUp=71]="chevronUp",e[e.circleBall=72]="circleBall",e[e.circleBalloons=73]="circleBalloons",e[e.circleCar=74]="circleCar",e[e.circleCat=75]="circleCat",e[e.circleCoffee=76]="circleCoffee",e[e.circleDog=77]="circleDog",e[e.circleEmpty=78]="circleEmpty",e[e.circleFill=79]="circleFill",e[e.circleFilled=80]="circleFilled",e[e.circleHalfFilled=81]="circleHalfFilled",e[e.circleInfo=82]="circleInfo",e[e.circleLightning=83]="circleLightning",e[e.circlePill=84]="circlePill",e[e.circlePlane=85]="circlePlane",e[e.circlePlus=86]="circlePlus",e[e.circlePoodle=87]="circlePoodle",e[e.circleUnfilled=88]="circleUnfilled",e[e.classNotebook=89]="classNotebook",e[e.classroom=90]="classroom",e[e.clock=91]="clock",e[e.clutter=92]="clutter",e[e.coffee=93]="coffee",e[e.collapse=94]="collapse",e[e.conflict=95]="conflict",e[e.contact=96]="contact",e[e.contactForm=97]="contactForm",e[e.contactPublic=98]="contactPublic",e[e.copy=99]="copy",e[e.creditCard=100]="creditCard",e[e.creditCardOutline=101]="creditCardOutline",e[e.dashboard=102]="dashboard",e[e.descending=103]="descending",e[e.desktop=104]="desktop",e[e.deviceWipe=105]="deviceWipe",e[e.dialpad=106]="dialpad",e[e.directions=107]="directions",e[e.document=108]="document",e[e.documentAdd=109]="documentAdd",e[e.documentForward=110]="documentForward",e[e.documentLandscape=111]="documentLandscape",e[e.documentPDF=112]="documentPDF",e[e.documentReply=113]="documentReply",e[e.documents=114]="documents",e[e.documentSearch=115]="documentSearch",e[e.dog=116]="dog",e[e.dogAlt=117]="dogAlt",e[e.dot=118]="dot",e[e.download=119]="download",e[e.drm=120]="drm",e[e.drop=121]="drop",e[e.dropdown=122]="dropdown",e[e.editBox=123]="editBox",e[e.ellipsis=124]="ellipsis",e[e.embed=125]="embed",e[e.event=126]="event",e[e.eventCancel=127]="eventCancel",e[e.eventInfo=128]="eventInfo",e[e.eventRecurring=129]="eventRecurring",e[e.eventShare=130]="eventShare",e[e.exclamation=131]="exclamation",e[e.expand=132]="expand",e[e.eye=133]="eye",e[e.favorites=134]="favorites",e[e.fax=135]="fax",e[e.fieldMail=136]="fieldMail",e[e.fieldNumber=137]="fieldNumber",e[e.fieldText=138]="fieldText",e[e.fieldTextBox=139]="fieldTextBox",e[e.fileDocument=140]="fileDocument",e[e.fileImage=141]="fileImage",e[e.filePDF=142]="filePDF",e[e.filter=143]="filter",e[e.filterClear=144]="filterClear",e[e.firstAid=145]="firstAid",e[e.flag=146]="flag",e[e.folder=147]="folder",e[e.folderMove=148]="folderMove",e[e.folderPublic=149]="folderPublic",e[e.folderSearch=150]="folderSearch",e[e.fontColor=151]="fontColor",e[e.fontDecrease=152]="fontDecrease",e[e.fontIncrease=153]="fontIncrease",e[e.frowny=154]="frowny",e[e.fullscreen=155]="fullscreen",e[e.gear=156]="gear",e[e.glasses=157]="glasses",e[e.globe=158]="globe",e[e.graph=159]="graph",e[e.group=160]="group",e[e.header=161]="header",e[e.heart=162]="heart",e[e.heartEmpty=163]="heartEmpty",e[e.hide=164]="hide",e[e.home=165]="home",e[e.inboxCheck=166]="inboxCheck",e[e.info=167]="info",e[e.infoCircle=168]="infoCircle",e[e.italic=169]="italic",e[e.key=170]="key",e[e.late=171]="late",e[e.lifesaver=172]="lifesaver",e[e.lifesaverLock=173]="lifesaverLock",e[e.lightBulb=174]="lightBulb",e[e.lightning=175]="lightning",e[e.link=176]="link",e[e.linkRemove=177]="linkRemove",e[e.listBullets=178]="listBullets",e[e.listCheck=179]="listCheck",e[e.listCheckbox=180]="listCheckbox",e[e.listGroup=181]="listGroup",e[e.listGroup2=182]="listGroup2",e[e.listNumbered=183]="listNumbered",e[e.lock=184]="lock",e[e.mail=185]="mail",e[e.mailCheck=186]="mailCheck",e[e.mailDown=187]="mailDown",e[e.mailEdit=188]="mailEdit",e[e.mailEmpty=189]="mailEmpty",e[e.mailError=190]="mailError",e[e.mailOpen=191]="mailOpen",e[e.mailPause=192]="mailPause",e[e.mailPublic=193]="mailPublic",e[e.mailRead=194]="mailRead",e[e.mailSend=195]="mailSend",e[e.mailSync=196]="mailSync",e[e.mailUnread=197]="mailUnread",e[e.mapMarker=198]="mapMarker",e[e.meal=199]="meal",e[e.menu=200]="menu",e[e.menu2=201]="menu2",e[e.merge=202]="merge",e[e.metadata=203]="metadata",e[e.microphone=204]="microphone",e[e.miniatures=205]="miniatures",e[e.minus=206]="minus",e[e.mobile=207]="mobile",e[e.money=208]="money",e[e.move=209]="move",e[e.multiChoice=210]="multiChoice",e[e.music=211]="music",e[e.navigate=212]="navigate",e[e["new"]=213]="new",e[e.newsfeed=214]="newsfeed",e[e.note=215]="note",e[e.notebook=216]="notebook",e[e.noteEdit=217]="noteEdit",e[e.noteForward=218]="noteForward",e[e.noteReply=219]="noteReply",e[e.notRecurring=220]="notRecurring",e[e.onedrive=221]="onedrive",e[e.onlineAdd=222]="onlineAdd",e[e.onlineJoin=223]="onlineJoin",e[e.oofReply=224]="oofReply",e[e.org=225]="org",e[e.page=226]="page",e[e.paint=227]="paint",e[e.panel=228]="panel",e[e.partner=229]="partner",e[e.pause=230]="pause",e[e.pencil=231]="pencil",e[e.people=232]="people",e[e.peopleAdd=233]="peopleAdd",e[e.peopleCheck=234]="peopleCheck",e[e.peopleError=235]="peopleError",e[e.peoplePause=236]="peoplePause",e[e.peopleRemove=237]="peopleRemove",e[e.peopleSecurity=238]="peopleSecurity",e[e.peopleSync=239]="peopleSync",e[e.person=240]="person",e[e.personAdd=241]="personAdd",e[e.personRemove=242]="personRemove",e[e.phone=243]="phone",e[e.phoneAdd=244]="phoneAdd",e[e.phoneTransfer=245]="phoneTransfer",e[e.picture=246]="picture",e[e.pictureAdd=247]="pictureAdd",e[e.pictureEdit=248]="pictureEdit",e[e.pictureRemove=249]="pictureRemove",e[e.pill=250]="pill",e[e.pinDown=251]="pinDown",e[e.pinLeft=252]="pinLeft",e[e.placeholder=253]="placeholder",e[e.plane=254]="plane",e[e.play=255]="play",e[e.plus=256]="plus",e[e.plus2=257]="plus2",e[e.pointItem=258]="pointItem",e[e.popout=259]="popout",e[e.post=260]="post",e[e.print=261]="print",e[e.protectionCenter=262]="protectionCenter",e[e.question=263]="question",e[e.questionReverse=264]="questionReverse",e[e.quote=265]="quote",e[e.radioButton=266]="radioButton",e[e.reactivate=267]="reactivate",e[e.receiptCheck=268]="receiptCheck",e[e.receiptForward=269]="receiptForward",e[e.receiptReply=270]="receiptReply",e[e.refresh=271]="refresh", e[e.reload=272]="reload",e[e.reply=273]="reply",e[e.replyAll=274]="replyAll",e[e.replyAllAlt=275]="replyAllAlt",e[e.replyAlt=276]="replyAlt",e[e.ribbon=277]="ribbon",e[e.room=278]="room",e[e.save=279]="save",e[e.scheduling=280]="scheduling",e[e.search=281]="search",e[e.section=282]="section",e[e.sections=283]="sections",e[e.settings=284]="settings",e[e.share=285]="share",e[e.shield=286]="shield",e[e.sites=287]="sites",e[e.smiley=288]="smiley",e[e.soccer=289]="soccer",e[e.socialListening=290]="socialListening",e[e.sort=291]="sort",e[e.sortLines=292]="sortLines",e[e.split=293]="split",e[e.star=294]="star",e[e.starEmpty=295]="starEmpty",e[e.stopwatch=296]="stopwatch",e[e.story=297]="story",e[e.styleRemove=298]="styleRemove",e[e.subscribe=299]="subscribe",e[e.sun=300]="sun",e[e.sunAdd=301]="sunAdd",e[e.sunQuestion=302]="sunQuestion",e[e.support=303]="support",e[e.table=304]="table",e[e.tablet=305]="tablet",e[e.tag=306]="tag",e[e.taskRecurring=307]="taskRecurring",e[e.tasks=308]="tasks",e[e.teamwork=309]="teamwork",e[e.text=310]="text",e[e.textBox=311]="textBox",e[e.tile=312]="tile",e[e.timeline=313]="timeline",e[e.today=314]="today",e[e.toggle=315]="toggle",e[e.toggleMiddle=316]="toggleMiddle",e[e.touch=317]="touch",e[e.trash=318]="trash",e[e.triangleDown=319]="triangleDown",e[e.triangleEmptyDown=320]="triangleEmptyDown",e[e.triangleEmptyLeft=321]="triangleEmptyLeft",e[e.triangleEmptyRight=322]="triangleEmptyRight",e[e.triangleEmptyUp=323]="triangleEmptyUp",e[e.triangleLeft=324]="triangleLeft",e[e.triangleRight=325]="triangleRight",e[e.triangleUp=326]="triangleUp",e[e.trophy=327]="trophy",e[e.underline=328]="underline",e[e.unsubscribe=329]="unsubscribe",e[e.upload=330]="upload",e[e.video=331]="video",e[e.voicemail=332]="voicemail",e[e.voicemailForward=333]="voicemailForward",e[e.voicemailReply=334]="voicemailReply",e[e.waffle=335]="waffle",e[e.work=336]="work",e[e.wrench=337]="wrench",e[e.x=338]="x",e[e.xCircle=339]="xCircle"}(t.IconEnum||(t.IconEnum={}));t.IconEnum},function(e,t,i){"use strict";var n=i(2),r=function(){function e(){this.restrict="E",this.transclude=!0,this.replace=!1,this.scope=!1,this.template='<label class="ms-Label"><ng-transclude/></label>'}return e.factory=function(){var t=function(){return new e};return t},e.prototype.link=function(e,t,i){n.isDefined(i.disabled)&&t.find("label").eq(0).addClass("is-disabled"),n.isDefined(i.required)&&t.find("label").eq(0).addClass("is-required")},e}();t.LabelDirective=r,t.module=n.module("officeuifabric.components.label",["officeuifabric.components"]).directive("uifLabel",r.factory())},function(e,t,i){"use strict";var n=i(2),r=function(){function e(){this.restrict="E",this.template='<a ng-href="{{ ngHref }}" class="ms-Link" ng-transclude></a>',this.scope={ngHref:"@"},this.transclude=!0,this.replace=!0}return e.factory=function(){var t=function(){return new e};return t},e}();t.LinkDirective=r,t.module=n.module("officeuifabric.components.link",["officeuifabric.components"]).directive("uifLink",r.factory())},function(e,t,i){"use strict";var n=i(2),r=i(26),o=i(27),s=i(28),a=function(){function e(e,t){this.$scope=e,this.$log=t,this.$scope.items=[],this.$scope.selectedItems||(this.$scope.selectedItems=[])}return Object.defineProperty(e.prototype,"itemSelectMode",{get:function(){return this.$scope.itemSelectMode},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"selectedItems",{get:function(){return this.$scope.selectedItems},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"items",{get:function(){return this.$scope.items},enumerable:!0,configurable:!0}),e.$inject=["$scope","$log"],e}(),c=function(){function e(){this.restrict="E",this.transclude=!0,this.replace=!1,this.template='<ul class="ms-List" ng-transclude></ul>',this.controller=a,this.controllerAs="list",this.scope={selectedItems:"=?uifSelectedItems"}}return e.factory=function(){var t=function(){return new e};return t},e.prototype.link=function(e,t,i,n){void 0!==i.uifLayout&&null!==i.uifLayout&&(void 0===s.ListLayoutEnum[i.uifLayout]?n.$log.error("Error [ngOfficeUiFabric] officeuifabric.components.list. '"+i.uifLayout+"' is not a valid option for 'uif-layout'. Valid options are list|grid."):e.layout=i.uifLayout),void 0===e.layout&&(e.layout=s.ListLayoutEnum[s.ListLayoutEnum.list]),e.layout===s.ListLayoutEnum[s.ListLayoutEnum.grid]&&t.children().eq(0).addClass("ms-List--grid"),void 0!==i.uifItemSelectMode&&null!==i.uifItemSelectMode&&(void 0===r.ListItemSelectModeEnum[i.uifItemSelectMode]?n.$log.error("Error [ngOfficeUiFabric] officeuifabric.components.list. '"+i.uifItemSelectMode+"' is not a valid option for 'uif-item-select-mode'. Valid options are none|single|multiple."):e.itemSelectMode=i.uifItemSelectMode),void 0===e.itemSelectMode&&(e.itemSelectMode=r.ListItemSelectModeEnum[r.ListItemSelectModeEnum.none])},e}();t.ListDirective=c;var l=function(){function e(e,t){this.$scope=e,this.$log=t}return e.$inject=["$scope","$log"],e}(),u=function(){function e(){this.restrict="E",this.transclude=!0,this.replace=!1,this.template='<li class="ms-ListItem" ng-transclude></li>',this.require="^uifList",this.scope={item:"=uifItem"},this.controller=l}return e.factory=function(){var t=function(){return new e};return t},e.prototype.link=function(e,t,i,n){if(void 0!==i.uifSelected&&null!==i.uifSelected){var s=i.uifSelected.toLowerCase();"true"!==s&&"false"!==s?n.$log.error("Error [ngOfficeUiFabric] officeuifabric.components.list. '"+i.uifSelected+"' is not a valid boolean value. Valid options are true|false."):"true"===s&&(e.selected=!0)}if(e.item&&n.selectedItems.length>0)for(var a=0;a<n.selectedItems.length;a++)n.selectedItems[a]===e.item&&(e.selected=!0);switch(void 0!==i.uifType&&null!==i.uifType&&(void 0===o.ListItemTypeEnum[i.uifType]?n.$log.error("Error [ngOfficeUiFabric] officeuifabric.components.list. '"+i.uifType+"' is not a valid option for 'uif-type'. Valid options are item|itemWithImage|itemWithIcon."):e.type=o.ListItemTypeEnum[i.uifType]),e.type){case o.ListItemTypeEnum.itemWithIcon:t.children().eq(0).addClass("ms-ListItem--document"),0===t.children().find("uif-list-item-icon").length&&n.$log.error("Error [ngOfficeUiFabric] officeuifabric.components.list. List item type itemWithIcon requires the uif-list-item-icon directive");break;case o.ListItemTypeEnum.itemWithImage:t.children().eq(0).addClass("ms-ListItem--image"),0===t.children().find("uif-list-item-image").length&&n.$log.error("Error [ngOfficeUiFabric] officeuifabric.components.list. List item type itemWithImage requires the uif-list-item-image directive")}if(void 0!==i.uifUnread&&null!==i.uifUnread){var c=i.uifUnread.toLowerCase();"true"!==c&&"false"!==c?n.$log.error("Error [ngOfficeUiFabric] officeuifabric.components.list. '"+i.uifUnread+"' is not a valid boolean value. Valid options are true|false."):"true"===c&&(e.unread=!0)}if(void 0!==i.uifUnseen&&null!==i.uifUnseen){var l=i.uifUnseen.toLowerCase();"true"!==l&&"false"!==l?n.$log.error("Error [ngOfficeUiFabric] officeuifabric.components.list. '"+i.uifUnseen+"' is not a valid boolean value. Valid options are true|false."):"true"===l&&(e.unseen=!0)}void 0!==e.item&&n.items.push(e),e.itemClick=function(t){e.selected=!e.selected,e.$apply()},e.$watch("selected",function(e,i,o){if(e===!0){if(n.itemSelectMode===r.ListItemSelectModeEnum[r.ListItemSelectModeEnum.single]&&(n.selectedItems.length=0,n.items))for(var s=0;s<n.items.length;s++)n.items[s]!==o&&(n.items[s].selected=!1);for(var a=!1,s=0;s<n.selectedItems.length;s++)if(n.selectedItems[s]===o.item){a=!0;break}a||n.selectedItems.push(o.item),t.children().eq(0).addClass("is-selected")}else{for(var s=0;s<n.selectedItems.length;s++)if(n.selectedItems[s]===o.item){n.selectedItems.splice(s,1);break}t.children().eq(0).removeClass("is-selected")}}),e.$watch("unread",function(e,i,n){e===!0?t.children().eq(0).addClass("is-unread"):t.children().eq(0).removeClass("is-unread")}),e.$watch("unseen",function(e,i,n){e===!0?t.children().eq(0).addClass("is-unseen"):t.children().eq(0).removeClass("is-unseen")}),n.itemSelectMode!==r.ListItemSelectModeEnum[r.ListItemSelectModeEnum.none]&&(t.on("click",e.itemClick),t.children().eq(0).addClass("is-selectable"))},e}();t.ListItemDirective=u;var d=function(){function e(){this.restrict="E",this.transclude=!0,this.template='<span class="ms-ListItem-primaryText" ng-transclude></span>',this.replace=!1}return e.factory=function(){var t=function(){return new e};return t},e}();t.ListItemPrimaryTextDirective=d;var f=function(){function e(){this.restrict="E",this.transclude=!0,this.template='<span class="ms-ListItem-secondaryText" ng-transclude></span>',this.replace=!1}return e.factory=function(){var t=function(){return new e};return t},e}();t.ListItemSecondaryTextDirective=f;var p=function(){function e(){this.restrict="E",this.transclude=!0,this.template='<span class="ms-ListItem-tertiaryText" ng-transclude></span>',this.replace=!1}return e.factory=function(){var t=function(){return new e};return t},e}();t.ListItemTertiaryTextDirective=p;var m=function(){function e(){this.restrict="E",this.transclude=!0,this.template='<span class="ms-ListItem-metaText" ng-transclude></span>',this.replace=!1}return e.factory=function(){var t=function(){return new e};return t},e}();t.ListItemMetaTextDirective=m;var h=function(){function e(){this.restrict="E",this.transclude=!0,this.template='<div class="ms-ListItem-image" ng-transclude></div>',this.replace=!1}return e.factory=function(){var t=function(){return new e};return t},e}();t.ListItemImageDirective=h;var v=function(){function e(){this.restrict="E",this.transclude=!0,this.template='<div class="ms-ListItem-itemIcon" ng-transclude></div>',this.replace=!1}return e.factory=function(){var t=function(){return new e};return t},e}();t.ListItemIconDirective=v;var g=function(){function e(){this.restrict="E",this.transclude=!0,this.template='<div class="ms-ListItem-selectionTarget" ng-transclude></div>',this.replace=!1}return e.factory=function(){var t=function(){return new e};return t},e}();t.ListItemSelectionTargetDirective=g;var y=function(){function e(){this.restrict="E",this.transclude=!0,this.template='<div class="ms-ListItem-actions" ng-transclude></div>',this.replace=!1}return e.factory=function(){var t=function(){return new e};return t},e}();t.ListItemActionsDirective=y;var b=function(){function e(){this.restrict="E",this.transclude=!0,this.template='<div class="ms-ListItem-action" ng-transclude></div>',this.replace=!1}return e.factory=function(){var t=function(){return new e};return t},e}();t.ListItemActionDirective=b,t.module=n.module("officeuifabric.components.list",["officeuifabric.components"]).directive("uifList",c.factory()).directive("uifListItem",u.factory()).directive("uifListItemPrimaryText",d.factory()).directive("uifListItemSecondaryText",f.factory()).directive("uifListItemTertiaryText",p.factory()).directive("uifListItemMetaText",m.factory()).directive("uifListItemImage",h.factory()).directive("uifListItemIcon",v.factory()).directive("uifListItemSelectionTarget",g.factory()).directive("uifListItemActions",y.factory()).directive("uifListItemAction",b.factory())},function(e,t){"use strict";!function(e){e[e.none=0]="none",e[e.single=1]="single",e[e.multiple=2]="multiple"}(t.ListItemSelectModeEnum||(t.ListItemSelectModeEnum={}));t.ListItemSelectModeEnum},function(e,t){"use strict";!function(e){e[e.item=0]="item",e[e.itemWithImage=1]="itemWithImage",e[e.itemWithIcon=2]="itemWithIcon"}(t.ListItemTypeEnum||(t.ListItemTypeEnum={}));t.ListItemTypeEnum},function(e,t){"use strict";!function(e){e[e.list=0]="list",e[e.grid=1]="grid"}(t.ListLayoutEnum||(t.ListLayoutEnum={}));t.ListLayoutEnum},function(e,t,i){"use strict";var n=i(2),r=function(){function e(e,t,i){this.$scope=e,this.$log=t,this.$window=i}return e.$inject=["$scope","$log","$window"],e}();t.MessageBannerController=r;var o=function(){function e(e,t){var i=this;this.$log=e,this.$timeout=t,this.controller=r,this.restrict="E",this.transclude=!0,this.replace=!1,this.require="uifMessageBanner",this.isExpanded=!1,this.template='\n <div class="ms-MessageBanner" ng-show="uifIsVisible">\n <div class="ms-MessageBanner-content">\n <div class="ms-MessageBanner-text">\n <div class="ms-MessageBanner-clipper"></div>\n </div>\n <uif-button type="button" uif-type="command" class="ms-MessageBanner-expand" ng-show="!isExpanded" style="height:52px">\n <uif-icon uif-type="chevronsDown"></uif-icon>\n </uif-button>\n <uif-button type="button" uif-type="command" class="ms-MessageBanner-expand" ng-show="isExpanded" style="height:52px">\n <uif-icon uif-type="chevronsUp"></uif-icon>\n </uif-button>\n <div class="ms-MessageBanner-action">\n <uif-button type="button" uif-type="primary" class="ms-fontColor-neutralLight" ng-click="uifAction()">{{ uifActionLabel }}</uif-button>\n </div>\n </div>\n <uif-button type="button" uif-type="command" class="ms-MessageBanner-close" ng-click="uifOnClose()" style="height:52px">\n <uif-icon uif-type="x"></uif-icon>\n </uif-button>\n </div>',this.scope={uifAction:"&",uifActionLabel:"@",uifIsVisible:"=?",uifOnClose:"&?"},this._textContainerMaxWidth=700,this._bufferElementsWidth=88,this._bufferElementsWidthSmall=35,this.SMALL_BREAK_POINT=480,this.link=function(e,t,r,o,s){e.uifActionLabel=r.uifActionLabel,e.isExpanded=!1,i._initLocals(t),i.transcludeChilds(e,t,s),n.element(o.$window).bind("resize",function(){i._onResize(),e.$digest()}),n.element(i._chevronButton).bind("click",function(){i._toggleExpansion(e)}),n.element(i._closeButton).bind("click",function(){i._hideBanner(e)}),i._onResize()}}return e.factory=function(){var t=function(t,i){return new e(t,i)};return t.$inject=["$log","$timeout"],t},e.prototype.transcludeChilds=function(e,t,i){var n=this;i(function(i){var r=n.hasItemContent(i);r||n.$log.error("Error [ngOfficeUiFabric] officeuifabric.components.messagebanner - you need to provide a text for the message banner.\nFor <uif-message-banner> you need to specify<uif-content> as a child directive"),n.insertItemContent(i,e,t)})},e.prototype.insertItemContent=function(e,t,i){var n=angular.element(i[0].querySelector(".ms-MessageBanner-clipper"));if(this.hasItemContent(e))for(var r=0;r<e.length;r++){var o=angular.element(e[r]);if(o.hasClass("uif-content")){n.append(o);break}}},e.prototype.hasItemContent=function(e){for(var t=0;t<e.length;t++){var i=angular.element(e[t]);if(i.hasClass("uif-content"))return!0}return!1},e.prototype._initLocals=function(e){this._messageBanner=n.element(e[0].querySelector(".ms-MessageBanner")),this._clipper=n.element(e[0].querySelector(".ms-MessageBanner-clipper")),this._chevronButton=n.element(e[0].querySelectorAll(".ms-MessageBanner-expand")),this._actionButton=n.element(e[0].querySelector(".ms-MessageBanner-action")),this._bufferSize=this._actionButton[0].offsetWidth+this._bufferElementsWidth,this._closeButton=n.element(e[0].querySelector(".ms-MessageBanner-close"))},e.prototype._onResize=function(){this._clientWidth=this._messageBanner[0].offsetWidth,window.innerWidth>=this.SMALL_BREAK_POINT?this._resizeRegular():this._resizeSmall()},e.prototype._resizeRegular=function(){if(this._clientWidth-this._bufferSize>this._initTextWidth&&this._initTextWidth<this._textContainerMaxWidth)this._textWidth="auto",this._chevronButton.addClass("ms-MessageBanner-expand");else{this._textWidth=Math.min(this._clientWidth-this._bufferSize,this._textContainerMaxWidth)+"px";for(var e=0;e<this._chevronButton.length;e++){var t=n.element(this._chevronButton[e]);t.hasClass("is-visible")||t.hasClass("ng-hide")?t.removeClass("is-visible"):t.addClass("is-visible")}}this._clipper[0].style.width=this._textWidth},e.prototype._resizeSmall=function(){this._clientWidth-(this._bufferElementsWidthSmall+this._closeButton[0].offsetWidth)>this._initTextWidth?this._textWidth="auto":this._textWidth=this._clientWidth-(this._bufferElementsWidthSmall+this._closeButton[0].offsetWidth)+"px",this._clipper[0].style.width=this._textWidth},e.prototype._toggleExpansion=function(e){e.isExpanded=!e.isExpanded,e.$digest(),this._messageBanner.toggleClass("is-expanded")},e.prototype._hideBanner=function(e){var t=this;e.uifIsVisible&&(this._messageBanner.addClass("hide"),this.$timeout(function(){e.uifIsVisible=!1,e.$apply(),t._messageBanner.removeClass("hide")},500))},e}();t.MessageBannerDirective=o,t.module=n.module("officeuifabric.components.messagebanner",["officeuifabric.components"]).directive("uifMessageBanner",o.factory())},function(e,t,i){"use strict";var n=i(2),r=i(31),o=function(){function e(e,t){this.$scope=e,this.$log=t}return e.$inject=["$scope","$log"],e}();t.MessageBarController=o;var s=function(){function e(e,t){var i=this;this.$log=e,this.$timeout=t,this.controller=o,this.restrict="E",this.transclude=!0,this.replace=!1,this.require="uifMessageBar",this.template='<div ng-class="[\'ms-MessageBar\', classType]"><div class="ms-MessageBar-content"><div class="ms-MessageBar-icon"><i ng-class="[\'ms-Icon\', iconType]"></i></div><div class="ms-MessageBar-text" /></div></div>',this.scope={uifType:"@"},this.link=function(e,t,n,o,s){e.iconType="ms-Icon--infoCircle",e.classType="",e.uifType=n.uifType,e.$watch("uifType",function(t,i){if("undefined"!=typeof t)if(void 0===r.MessageBarTypeEnum[t])o.$log.error("Error [ngOfficeUiFabric] officeuifabric.components.messagebar - Unsupported type: The type ('"+e.uifType+"') is not supported by the Office UI Fabric. Supported options are listed here: https://github.com/ngOfficeUIFabric/ng-officeuifabric/blob/master/src/components/messagebar/messageBarTypeEnum.ts");else{var n=" ms-MessageBar--";switch(e.classType=n+t,r.MessageBarTypeEnum[t]){case r.MessageBarTypeEnum.error:e.iconType="ms-Icon--xCircle";break;case r.MessageBarTypeEnum.remove:e.iconType="ms-Icon--minus ms-Icon--circle";break;case r.MessageBarTypeEnum.severewarning:e.iconType="ms-Icon--alert";break;case r.MessageBarTypeEnum.success:e.iconType="ms-Icon--checkboxCheck ms-Icon--circle"}}}),i.transcludeChilds(e,t,s)}}return e.factory=function(){var t=function(t,i){return new e(t,i)};return t.$inject=["$log","$timeout"],t},e.prototype.transcludeChilds=function(e,t,i){var n=this;i(function(i){var r=n.hasItemContent(i,"uif-content");r||n.$log.error("Error [ngOfficeUiFabric] officeuifabric.components.MessageBar - you need to provide a text for the message bar.\nFor <uif-message-bar> you need to specify<uif-content> as a child directive"),n.insertItemContent(i,e,t)})},e.prototype.insertItemContent=function(e,t,i){var n=angular.element(i[0].querySelector(".ms-MessageBar-text"));if(this.hasItemContent(e,"uif-content"))for(var r=0;r<e.length;r++){var o=angular.element(e[r]);if(o.hasClass("uif-content")){n.append(o);break}}if(this.hasItemContent(e,"ms-Link"))for(var r=0;r<e.length;r++){var o=angular.element(e[r]);if(o.hasClass("ms-Link")){n.append(angular.element("<br />")),n.append(o);break}}},e.prototype.hasItemContent=function(e,t){for(var i=0;i<e.length;i++){var n=angular.element(e[i]);if(n.hasClass(t))return!0}return!1},e}();t.MessageBarDirective=s,t.module=n.module("officeuifabric.components.messagebar",["officeuifabric.components"]).directive("uifMessageBar",s.factory())},function(e,t){"use strict";!function(e){e[e.error=0]="error",e[e.remove=1]="remove",e[e.severewarning=2]="severewarning",e[e.success=3]="success",e[e.warning=4]="warning"}(t.MessageBarTypeEnum||(t.MessageBarTypeEnum={}));t.MessageBarTypeEnum},function(e,t,i){"use strict";var n=i(2),r=i(15),o=function(){function e(e,t,i,n){this.$scope=e,this.$animate=t,this.$element=i,this.$log=n}return e.prototype.openMobileMenu=function(){var e=this.$element.hasClass("is-open");this.$animate[e?"removeClass":"addClass"](this.$element,"is-open")},e.prototype.closeMobileMenu=function(){this.$element.hasClass("is-open")&&this.$animate.removeClass(this.$element,"is-open")},e.prototype.closeAllContextMenus=function(){for(var e=this.$element[0].querySelectorAll(".ms-NavBar-item"),t=0;t<e.length;t++){var i=angular.element(e[t]),n=i.controller(l.directiveName);n&&(n.closeContextualMenu(),n.deselectItem())}},e.prototype.hideSearchTextBox=function(){for(var e=this.$element[0].querySelectorAll(".ms-NavBar-item--search"),t=0;t<e.length;t++){var i=angular.element(e[t]),n=i.controller(d.directiveName);n&&n.closeSearch()}},e.$inject=["$scope","$animate","$element","$log"],e}();t.NavBarController=o;var s=function(){function e(e,t,i){var n=this;this.$log=e,this.$animate=t,this.$document=i,this.replace=!0,this.restrict="E",this.transclude=!0,this.controller=o,this.controllerAs="nav",this.template='\n <div class="ms-NavBar">\n <div class="ms-NavBar-openMenu js-openMenu" ng-click="nav.openMobileMenu()">\n <uif-icon uif-type="menu"></uif-icon>\n </div>\n <uif-overlay uif-mode="{{overlay}}" ng-click="nav.closeMobileMenu()"></uif-overlay>\n <ul class="ms-NavBar-items">\n <div class=\'uif-nav-items\'></div>\n </ul>\n </div>',this.scope={overlay:"@?uifOverlay"},this.link=function(e,t,i,r,o){n.$document.on("click",function(){r.closeAllContextMenus(),r.hideSearchTextBox()}),o(function(e){var i=angular.element(t[0].querySelector(".uif-nav-items"));i.replaceWith(e)})}}return e.factory=function(){var t=function(t,i,n){return new e(t,i,n)};return t.$inject=["$log","$animate","$document"],t},e.directiveName="uifNavBar",e.overlayValues=["light","dark"],e}();t.NavBarDirective=s;var a;!function(e){e[e.link=0]="link",e[e.menu=1]="menu"}(a||(a={}));var c=function(){function e(e,t){this.$scope=e,this.$element=t}return e.prototype.closeContextualMenu=function(){this.$scope.hasChildMenu&&this.$scope.contextMenuCtrl.closeMenu()},e.prototype.deselectItem=function(){this.$element.removeClass("is-selected")},e.$inject=["$scope","$element"],e}();t.NavBarItemController=c;var l=function(){function e(e){var t=this;this.$log=e,this.replace=!0,this.restrict="E",this.transclude=!0,this.controller=c,this.require="^"+s.directiveName,this.scope={isDisabled:"@?disabled",position:"@?uifPosition",text:"=?uifText",type:"@?uifType"},this.templateTypes={},this.template=function(e,i){var r=i.uifType;return n.isUndefined(r)?t.templateTypes[a.link]:void 0===a[r]?(t.$log.error("Error [ngOfficeUiFabric] officeuifabric.components.navbar - unsupported nav bar item type:\nthe type '"+r+"' is not supported by ng-Office UI Fabric as valid type for nav bar item.Supported types can be found under NavBarItemTypes enum here:\nhttps://github.com/ngOfficeUIFabric/ng-officeuifabric/blob/master/src/components/navbar/navbarDirective.ts"),"<div></div>"):t.templateTypes[a[r]]},this.link=function(e,i,o,s,c){if(e.isDisabled){var l=angular.element(i[0].querySelector(".ms-NavBar-link"));l.removeAttr("href")}n.isUndefined(e.type)&&(e.type=a[a.link]),e.selectItem=function(t){t.stopPropagation(),i.hasClass("is-disabled")||(i.parent().find("li").removeClass("is-selected"),s.closeAllContextMenus(),s.hideSearchTextBox(),i.toggleClass("is-selected"),e.hasChildMenu&&e.contextMenuCtrl.isMenuOpened()?(e.contextMenuCtrl.closeMenu(),i.removeClass("is-selected")):e.hasChildMenu&&!e.contextMenuCtrl.isMenuOpened()?(e.contextMenuCtrl.openMenu(),i.addClass("is-selected")):e.hasChildMenu||s.closeMobileMenu(),e.$apply())},i.on("click",e.selectItem),t.transcludeChilds(e,i,c);var u=angular.element(i[0].querySelector(".ms-ContextualMenu")).controller(r.ContextualMenuDirective.directiveName);u&&(e.hasChildMenu=!0,e.contextMenuCtrl=u,e.contextMenuCtrl.onRootMenuClosed.push(function(){s.closeMobileMenu(),i.removeClass("is-selected")}))},this.templateTypes[a.link]="\n <li class=\"ms-NavBar-item\"\n ng-class=\"{'is-disabled': isDisabled, 'ms-NavBar-item--right': position === 'right'}\">\n <a class=\"ms-NavBar-link\" href=\"\"><span class='uif-nav-item-content'></span></a>\n </li>",this.templateTypes[a.menu]='\n <li class="ms-NavBar-item ms-NavBar-item--hasMenu" ng-class="{\'is-disabled\': isDisabled}">\n <a class="ms-NavBar-link" href=""><span class=\'uif-nav-item-content\'></span></a>\n <i class="ms-NavBar-chevronDown ms-Icon ms-Icon--chevronDown"></i>\n <div class=\'uif-submenu\'></div>\n </li>'}return e.factory=function(){var t=function(t){return new e(t)};return t.$inject=["$log"],t},e.prototype.transcludeChilds=function(e,t,i){var n=this;i(function(i){var r=n.hasItemContent(i);r||e.text||n.$log.error("Error [ngOfficeUiFabric] officeuifabric.components.navbar - you need to provide a text for a nav bar menu item.\nFor <uif-nav-bar-item> you need to specify either 'uif-text' as attribute or <uif-nav-item-content> as a child directive"),n.insertLink(i,e,t),n.insertMenu(i,e,t)})},e.prototype.insertLink=function(e,t,i){var n=angular.element(i[0].querySelector(".uif-nav-item-content"));if(this.hasItemContent(e))for(var r=0;r<e.length;r++){var o=angular.element(e[r]);if(o.hasClass("uif-content")){n.replaceWith(o);break}}else n.replaceWith(angular.element("<span>"+t.text+"</span>"))},e.prototype.insertMenu=function(e,t,i){for(var n=0;n<e.length;n++){var r=angular.element(e[n]);r.hasClass("ms-ContextualMenu")&&angular.element(i[0].querySelector(".uif-submenu")).replaceWith(r)}},e.prototype.hasItemContent=function(e){for(var t=0;t<e.length;t++){var i=angular.element(e[t]);if(i.hasClass("uif-content"))return!0}return!1},e.directiveName="uifNavBarItem",e}();t.NavBarItemDirective=l;var u=function(){function e(e,t,i,n,r){this.$scope=e,this.$element=t,this.$document=i,this.$animate=n,this.$timeout=r}return e.prototype.closeSearch=function(){var e=this;this.$timeout(function(){e.$scope.searchText||e.$animate.removeClass(e.$element,"is-open"),e.$animate.removeClass(e.$element,"is-selected")})},e.$inject=["$scope","$element","$document","$animate","$timeout"],e}();t.NavBarSearchController=u;var d=function(){function e(t,i,n){var r=this;this.$document=t,this.$animate=i,this.$timeout=n,this.replace=!0,this.restrict="E",this.controller=u,this.require=["^"+s.directiveName,""+e.directiveName],this.transclude=!0,this.scope={onSearchCallback:"&?uifOnSearch",placeholder:"@?placeholder"},this.template='\n <li class="ms-NavBar-item ms-NavBar-item--search ms-u-hiddenSm" ng-click="onSearch($event)">\n <div class="ms-TextField" ng-click="skipOnClick($event)">\n <input placeholder={{placeholder}} class="ms-TextField-field" type="text" ng-keypress="onSearch($event)" ng-model="searchText">\n </div>\n </li>',this.link=function(e,t,i,n,o){r.$document.on("click",function(){n[1].closeSearch()}),e.skipOnClick=function(e){r.applyCssClasses(t),e.stopPropagation()},e.onSearch=function(i){n[0].closeAllContextMenus(),i instanceof KeyboardEvent&&13===i.which&&e.onSearchCallback?e.onSearchCallback({search:e.searchText}):i instanceof MouseEvent&&t.hasClass("is-open")&&e.onSearchCallback&&e.onSearchCallback({search:e.searchText}),r.applyCssClasses(t),i.stopPropagation()}}}return e.factory=function(){var t=function(t,i,n){return new e(t,i,n)};return t.$inject=["$document","$animate","$timeout"],t},e.prototype.applyCssClasses=function(e){e.hasClass("is-open")||(this.$animate.addClass(e,"is-open"),this.$timeout(function(){angular.element(e[0].querySelector(".ms-TextField-field"))[0].focus()},1)),e.parent().find("li").removeClass("is-selected"),this.$animate.addClass(e,"is-selected")},e.directiveName="uifNavBarSearch",e}();t.NavBarSearch=d,t.module=n.module("officeuifabric.components.navbar",["officeuifabric.components"]).directive(s.directiveName,s.factory()).directive(l.directiveName,l.factory()).directive(d.directiveName,d.factory())},function(e,t,i){"use strict";var n=i(2),r=i(34),o=(function(){function e(e){this.log=e}return e.$inject=["$log"],e}(),function(){function e(t){this.log=t,this.restrict="E",this.template="<div class=\"ms-Overlay\" ng-class=\"{'ms-Overlay--dark': uifMode == 'dark'}\" ng-transclude></div>",this.scope={uifMode:"@"},this.transclude=!0,e.log=t}return e.factory=function(){var t=function(t){return new e(t)};return t.$inject=["$log"],t},e.prototype.link=function(t){t.$watch("uifMode",function(i,n){void 0===r.OverlayMode[i]&&e.log.error("Error [ngOfficeUiFabric] officeuifabric.components.overlay - Unsupported overlay mode: The overlay mode ('"+t.uifMode+"') is not supported by the Office UI Fabric. Supported options are listed here: https://github.com/ngOfficeUIFabric/ng-officeuifabric/blob/master/src/components/overlay/overlayModeEnum.ts")})},e}());t.OverlayDirective=o,t.module=n.module("officeuifabric.components.overlay",["officeuifabric.components"]).directive("uifOverlay",o.factory())},function(e,t){"use strict";!function(e){e[e.light=0]="light",e[e.dark=1]="dark"}(t.OverlayMode||(t.OverlayMode={}));t.OverlayMode},function(e,t,i){"use strict";var n=i(2),r=i(36),o=function(){function e(e,t,i){this.$log=e,this.$animate=t,this.$timeout=i,this.restrict="E",this.template='<div class="ms-Panel">\n <div class="ms-Overlay"\n ng-click="closePanel()"\n ng-class="uifShowOverlay === true ? \'ms-Overlay--dark\' : \'\';"></div>\n <div class="ms-Panel-main">\n <div class="ms-Panel-commands">\n <button type="button" ng-if="uifShowClose" class=\'ms-Panel-closeButton\' ng-click="closePanel()">\n <uif-icon uif-type=\'x\'></uif-icon>\n </button>\n </div>\n <div class="ms-Panel-contentInner">\n </div>\n </div>\n </div>',this.transclude=!0,this.replace=!0,this.controller=s,this.scope={uifIsOpen:"=",uifShowClose:"=",uifShowOverlay:"=",uifType:"@"}}return e.factory=function(){var t=function(t,i,n){return new e(t,i,n)};return t.$inject=["$log","$animate","$timeout"],t},e.prototype.compile=function(e,t,i){return{pre:this.preLink}},e.prototype.preLink=function(e,t,i,n,r){r(function(i){for(var n=0;n<i.length;n++)angular.element(i[n]).hasClass("ms-CommandBar")?angular.element(t[0].querySelector("div.ms-Panel-commands")).prepend(i[n]):"left"===e.uifType?angular.element(t[0].querySelector("div.ms-Panel-main")).append(i[n]):angular.element(t[0].querySelector("div.ms-Panel-contentInner")).append(i[n])}),e.closePanel=function(){e.uifIsOpen=!1}},e}();t.PanelDirective=o;var s=function(){function e(e,t,i,n,o){var s=this;this.$scope=e,this.$animate=t,this.$element=i,this.$log=n,this.$timeout=o,this.uifPanelSizeClasses=(c={},c[r.PanelTypes.small]="ms-Panel--sm",c[r.PanelTypes.medium]="ms-Panel--md",c[r.PanelTypes.large]="ms-Panel--lg",c[r.PanelTypes.extralarge]="ms-Panel--xl",c[r.PanelTypes.extraextralarge]="ms-Panel--xxl",c[r.PanelTypes.left]="ms-Panel--left",c),e.uifType||(e.uifType="medium"),void 0===r.PanelTypes[e.uifType]&&(this.$log.error("Error [ngOfficeUiFabric] officeuifabric.components.panel - unsupported panel type:\nthe type '"+e.uifType+"' is not supported by ng-Office UI Fabric as valid type for panels.Supported types can be found under PanelTypes enum here:\nhttps://github.com/ngOfficeUIFabric/ng-officeuifabric/blob/master/src/components/panel/panel.ts"),e.uifType="medium");var a=r.PanelTypes[e.uifType];i.addClass(this.uifPanelSizeClasses[a]),e.$watch("uifIsOpen",function(e){"boolean"!=typeof e&&void 0!==e&&s.$log.error("Error [ngOfficeUiFabric] officeuifabric.components.panel - invalid attribute type: 'uif-is-open'.\nThe type '"+typeof e+"' is not supported as valid type for 'uif-is-open' attribute for <uif-panel/>. The valid type is boolean."),e===!0?(t.addClass(s.$element,"ms-Panel-animateIn"),i.addClass("is-open"),i[0].querySelector(".ms-CommandBar")&&angular.element(i[0].querySelector(".ms-CommandBar")).scope().$broadcast("uif-command-bar-resize")):(t.addClass(s.$element,"ms-Panel-animateOut"),o(function(){i.removeClass("ms-Panel-animateIn ms-Panel-animateOut"),i.removeClass("is-open")},500))});var c}return e.$inject=["$scope","$animate","$element","$log","$timeout"], e}();t.PanelController=s;var a=function(){function e(){this.restrict="E",this.template='<p class="ms-Panel-headerText" ng-transclude></div>',this.transclude=!0,this.replace=!0,this.scope={uifHeaderText:"@"}}return e.factory=function(){var t=function(){return new e};return t},e}();t.PanelHeaderDirective=a,t.module=n.module("officeuifabric.components.panel",["officeuifabric.components"]).directive("uifPanel",o.factory()).directive("uifPanelHeader",a.factory())},function(e,t){"use strict";!function(e){e[e.small=0]="small",e[e.medium=1]="medium",e[e.large=2]="large",e[e.extralarge=3]="extralarge",e[e.extraextralarge=4]="extraextralarge",e[e.left=5]="left"}(t.PanelTypes||(t.PanelTypes={}));t.PanelTypes},function(e,t,i){"use strict";var n=i(2),r=i(38),o=i(39),s=i(40),a=i(41),c=function(){function e(){var e=this;this.restrict="E",this.transclude=!0,this.replace=!0,this.require=["uifPersonaCard"],this.controller=l,this.scope={uifPresence:"@",uifSize:"@",uifImageUrl:"@"},this.template='<div class="ms-PersonaCard" ng-class="getPersonaCardClasses()"><div class="ms-PersonaCard-persona"><div class="ms-Persona" ng-class="getPersonaClasses()"><div class="ms-Persona-imageArea"><uif-icon uif-type="person"></uif-icon><img class="ms-Persona-image" ng-src="{{uifImageUrl}}" ng-if="uifImageUrl"></div><div class="ms-Persona-presence"></div><div class="ms-Persona-details"></div></div></div><ul class="ms-PersonaCard-actions"><li ng-repeat="action in personaCardActions" ng-class="getActionClasses(action)" ng-click="selectAction($event, action)"><uif-icon uif-type={{action.icon}} ng-if="action.placeholder != \'overflow\'"></uif-icon></li></ul><div class="ms-PersonaCard-actionDetailBox"><ul ng-class="detailClass"></ul></div></div>',this.link=function(t,i,c,l,u){var d=l[0],f=i.find("uif-icon");return f.addClass("ms-Persona-placeholder"),n.isDefined(c.uifSize)&&n.isUndefined(r.PersonaSize[c.uifSize])?void d.$log.error('Error [ngOfficeUiFabric] officeuifabric.components.personacard - "'+c.uifSize+'" is not a valid value for uifSize. It should be xsmall, small, medium, large, xlarge.'):n.isDefined(c.uifStyle)&&n.isUndefined(s.PersonaStyleEnum[c.uifStyle])?void d.$log.error('Error [ngOfficeUiFabric] officeuifabric.components.personacard - "'+c.uifStyle+'" is not a valid value for uifStyle. It should be round or square.'):n.isDefined(c.uifPresence)&&n.isUndefined(a.PresenceEnum[c.uifPresence])?void d.$log.error('Error [ngOfficeUiFabric] officeuifabric.components.personacard - "'+c.uifPresence+'" is not a valid value for uifPresence. It should be available, away, blocked, busy, dnd or offline.'):(t.getActionClasses=function(e){var t=[],i=o.PlaceholderEnum[e.placeholder];switch(i){case o.PlaceholderEnum.topright:t.push("ms-PersonaCard-action"),t.push("ms-PersonaCard-orgChart");break;case o.PlaceholderEnum.regular:t.push("ms-PersonaCard-action")}return e.isActive&&t.push("is-active"),t.join(" ")},t.getPersonaClasses=function(){var e=[];switch(s.PersonaStyleEnum[c.uifStyle]===s.PersonaStyleEnum.square&&e.push("ms-Persona--square"),r.PersonaSize[c.uifSize]){case r.PersonaSize.xsmall:e.push("ms-Persona--xs");break;case r.PersonaSize.small:e.push("ms-Persona--sm");break;case r.PersonaSize.large:e.push("ms-Persona--lg");break;case r.PersonaSize.xlarge:e.push("ms-Persona--xl")}switch(a.PresenceEnum[c.uifPresence]){case a.PresenceEnum.available:e.push("ms-Persona--available");break;case a.PresenceEnum.away:e.push("ms-Persona--away");break;case a.PresenceEnum.blocked:e.push("ms-Persona--blocked");break;case a.PresenceEnum.busy:e.push("ms-Persona--busy");break;case a.PresenceEnum.dnd:e.push("ms-Persona--dnd");break;default:e.push("ms-Persona--offline")}return e.join(" ")},t.getPersonaCardClasses=function(){return s.PersonaStyleEnum[c.uifStyle]===s.PersonaStyleEnum.square?"ms-PersonaCard--square":""},void u(function(r){for(var s=n.element(i[0].getElementsByClassName("ms-Persona-details")),a=n.element(i[0].getElementsByClassName("ms-PersonaCard-actionDetailBox")).find("ul").eq(0),c=n.element(i[0].getElementsByClassName("ms-PersonaCard-actions")),l=0;l<r.length;l++){var u=r[l].tagName;switch(u){case"UIF-PERSONA-CARD-PRIMARY-TEXT":case"UIF-PERSONA-CARD-SECONDARY-TEXT":case"UIF-PERSONA-CARD-TERTIARY-TEXT":case"UIF-PERSONA-CARD-OPTIONAL-TEXT":s.append(r[l]);break;case"UIF-PERSONA-CARD-ACTION":var f=n.element(r[l]),p=f.attr("uif-placeholder");o.PlaceholderEnum[p]===o.PlaceholderEnum.overflow?c.append(f):a.append(e.processAction(f,t,d))}}}))}}return e.factory=function(){var t=function(){return new e};return t},e.prototype.processAction=function(e,t,i){var n="",r=e.attr("uif-placeholder"),s=e.attr("uif-icon"),a=new u(s,r);switch(r){case o.PlaceholderEnum[o.PlaceholderEnum.regular]:n="detail-"+ ++t.regularActionsCount;break;case o.PlaceholderEnum[o.PlaceholderEnum.topright]:n="detail-5"}return e.find("li").eq(0).addClass(n),a.detailClass=n,i.addAction(a),e},e}();t.PersonaCardDirective=c;var l=function(){function e(e,t){var i=this;this.$log=e,this.$scope=t,this.detailCss={1:"Chat",2:"Phone",3:"Video",4:"Mail",5:"Org"},t.personaCardActions=new Array,t.regularActionsCount=0,t.detailClass="ms-PersonaCard-detailChat",t.selectAction=function(e,n){t.personaCardActions.forEach(function(e){e.isActive=!1}),n.isActive=!0;var r=+n.detailClass.charAt(n.detailClass.length-1);t.detailClass="ms-PersonaCard-detail"+i.detailCss[r]}}return e.prototype.addAction=function(e){0===this.$scope.personaCardActions.length&&(e.isActive=!0),this.$scope.personaCardActions.push(e)},e.$inject=["$log","$scope"],e}();t.PersonaCardController=l;var u=function(){function e(e,t){this.icon=e,this.placeholder=t}return e}(),d=function(){function e(e){var t=this;this.directiveType=e,this.restrict="E",this.transclude=!0,this.replace=!1,this.scope=!1,this.availableClasses={primary:"ms-Persona-primaryText",secondary:"ms-Persona-secondaryText",tertiary:"ms-Persona-tertiaryText",optional:"ms-Persona-optionalText"},this.template=function(e,i){var n='<div class="'+t.availableClasses[t.directiveType]+'" ng-transclude></div>';return n},n.isUndefined(this.availableClasses[this.directiveType])&&(this.directiveType="optional")}return e.factory=function(t){var i=function(){return new e(t)};return i},e}();t.PersonaCardTextDirective=d;var f=function(){function e(e){var t=this;this.$log=e,this.restrict="E",this.transclude=!0,this.replace=!1,this.require="^?uifPersonaCard",this.scope=!1,this.template=function(e,i){return n.isDefined(i.uifPlaceholder)&&n.isUndefined(o.PlaceholderEnum[i.uifPlaceholder])?(t.$log.error('Error [ngOfficeUiFabric] officeuifabric.components.personacard - "'+i.uifPlaceholder+'" is not a valid value for uifPlaceholder. It should be regular, topright or overflow.'),""):o.PlaceholderEnum[i.uifPlaceholder]===o.PlaceholderEnum.overflow?'<li class="ms-PersonaCard-overflow" ng-transclude></li>':'<li class="ms-PersonaCard-actionDetails" ng-transclude></li>'}}return e.factory=function(){var t=function(t){return new e(t)};return t.$inject=["$log"],t},e}();t.PersonaCardActionDirective=f;var p=function(){function e(){this.restrict="E",this.transclude=!0,this.replace=!0,this.scope=!1,this.template='<span class="ms-PersonaCard-detailLabel" ng-transclude></span>'}return e.factory=function(){var t=function(){return new e};return t},e}();t.PersonaCardDetailLabelDirective=p;var m=function(){function e(){this.restrict="E",this.transclude=!0,this.replace=!0,this.scope=!1,this.template='<div class="ms-PersonaCard-detailLine" ng-transclude></div>'}return e.factory=function(){var t=function(){return new e};return t},e}();t.PersonaCardDetailLineDirective=m,t.module=n.module("officeuifabric.components.personacard",["officeuifabric.components"]).directive("uifPersonaCard",c.factory()).directive("uifPersonaCardAction",f.factory()).directive("uifPersonaCardDetailLabel",p.factory()).directive("uifPersonaCardDetailLine",m.factory()).directive("uifPersonaCardPrimaryText",d.factory("primary")).directive("uifPersonaCardSecondaryText",d.factory("secondary")).directive("uifPersonaCardTertiaryText",d.factory("tertiary")).directive("uifPersonaCardOptionalText",d.factory(""))},function(e,t){"use strict";!function(e){e[e.xsmall=0]="xsmall",e[e.small=1]="small",e[e.medium=2]="medium",e[e.large=3]="large",e[e.xlarge=4]="xlarge"}(t.PersonaSize||(t.PersonaSize={}));t.PersonaSize},function(e,t){"use strict";!function(e){e[e.regular=0]="regular",e[e.topright=1]="topright",e[e.overflow=2]="overflow"}(t.PlaceholderEnum||(t.PlaceholderEnum={}));t.PlaceholderEnum},function(e,t){"use strict";!function(e){e[e.round=0]="round",e[e.square=1]="square"}(t.PersonaStyleEnum||(t.PersonaStyleEnum={}));t.PersonaStyleEnum},function(e,t){"use strict";!function(e){e[e.available=0]="available",e[e.away=1]="away",e[e.blocked=2]="blocked",e[e.busy=3]="busy",e[e.dnd=4]="dnd",e[e.offline=5]="offline"}(t.PresenceEnum||(t.PresenceEnum={}));t.PresenceEnum},function(e,t,i){"use strict";var n=i(2),r=i(40),o=i(41),s=i(43),a=i(44),c=function(){function e(e){var t=this;this.directiveType=e,this.restrict="E",this.transclude=!0,this.replace=!1,this.scope=!1,this.availableClasses={primary:"ms-Persona-primaryText",secondary:"ms-Persona-secondaryText",tertiary:"ms-Persona-tertiaryText",optional:"ms-Persona-optionalText"},this.template=function(e,i){var n='<div class="'+t.availableClasses[t.directiveType]+'" ng-transclude></div>';return n},n.isUndefined(this.availableClasses[this.directiveType])&&(this.directiveType="optional")}return e.factory=function(t){var i=function(){return new e(t)};return i},e}();t.PersonaTextDirective=c;var l=function(){function e(){this.restrict="E",this.transclude=!0,this.replace=!1,this.require=["^uifPersona"],this.scope={uifColor:"@"},this.template='<div class="ms-Persona-initials ms-Persona-initials--{{uifColor}}" ng-transclude></div> ',this.link=function(e,t,i,r){var o=r[0];n.isUndefined(i.uifColor)&&(e.uifColor=s.PersonaInitialsColor[s.PersonaInitialsColor.blue]),e.$watch("uifColor",function(e){n.isUndefined(s.PersonaInitialsColor[e])&&o.$log.error('Error [ngOfficeUiFabric] officeuifabric.components.persona - "'+e+'" is not a valid value for uifColor. It should be lightBlue, blue, darkBlue, teal, lightGreen, green, darkGreen, lightPink, pink, magenta, purple, black, orange, red or darkRed.')})}}return e.factory=function(){var t=function(){return new e};return t},e}();t.PersonaInitialsDirective=l;var u=function(){function e(){var e=this;this.restrict="E",this.transclude=!0,this.replace=!0,this.require=["uifPersona"],this.controller=d,this.scope={uifPresence:"@",uifSize:"@",uifImageUrl:"@"},this.template='<div class="ms-Persona" ng-class="getPersonaClasses()"><div class="ms-Persona-imageArea" ng-show="getImageAreaVisibility()"><img class="ms-Persona-image" ng-src="{{uifImageUrl}}" ng-if="uifImageUrl"></div><div class="ms-Persona-presence"></div><div class="ms-Persona-details"></div></div>',this.uifSizeClasses=(t={},t[a.PersonaSize.tiny]="ms-Persona--tiny",t[a.PersonaSize.xsmall]="ms-Persona--xs",t[a.PersonaSize.small]="ms-Persona--sm",t[a.PersonaSize.large]="ms-Persona--lg",t[a.PersonaSize.xlarge]="ms-Persona--xl",t),this.uifPresenceClasses=(i={},i[o.PresenceEnum.available]="ms-Persona--available",i[o.PresenceEnum.away]="ms-Persona--away",i[o.PresenceEnum.blocked]="ms-Persona--blocked",i[o.PresenceEnum.busy]="ms-Persona--busy",i[o.PresenceEnum.dnd]="ms-Persona--dnd",i[o.PresenceEnum.offline]="ms-Persona--offline",i),this.link=function(t,i,s,c,l){var u=c[0];return n.isDefined(s.uifSize)&&n.isUndefined(a.PersonaSize[s.uifSize])?void u.$log.error('Error [ngOfficeUiFabric] officeuifabric.components.persona - "'+s.uifSize+'" is not a valid value for uifSize. It should be tiny, xsmall, small, medium, large, xlarge.'):n.isDefined(s.uifStyle)&&n.isUndefined(r.PersonaStyleEnum[s.uifStyle])?void u.$log.error('Error [ngOfficeUiFabric] officeuifabric.components.persona - "'+s.uifStyle+'" is not a valid value for uifStyle. It should be round or square.'):n.isDefined(s.uifPresence)&&n.isUndefined(o.PresenceEnum[s.uifPresence])?void u.$log.error('Error [ngOfficeUiFabric] officeuifabric.components.persona - "'+s.uifPresence+'" is not a valid value for uifPresence. It should be available, away, blocked, busy, dnd or offline.'):(t.getImageAreaVisibility=function(){return a.PersonaSize[s.uifSize]!==a.PersonaSize.tiny},t.getPersonaClasses=function(){var t=[],i=a.PersonaSize[s.uifSize],c=n.isDefined(s.uifPresence)?o.PresenceEnum[s.uifPresence]:o.PresenceEnum.offline;r.PersonaStyleEnum[s.uifStyle]===r.PersonaStyleEnum.square&&t.push("ms-Persona--square");var l=e.uifSizeClasses[i];return n.isDefined(l)&&t.push(l),t.push(e.uifPresenceClasses[c]),t.join(" ")},void l(function(e){for(var t=n.element(i[0].getElementsByClassName("ms-Persona-details")),r=n.element(i[0].getElementsByClassName("ms-Persona-imageArea")),o=0;o<e.length;o++){var s=e[o].tagName;switch(s){case"UIF-PERSONA-PRIMARY-TEXT":case"UIF-PERSONA-SECONDARY-TEXT":case"UIF-PERSONA-TERTIARY-TEXT":case"UIF-PERSONA-OPTIONAL-TEXT":t.append(e[o]);break;case"UIF-PERSONA-INITIALS":r.prepend(e[o])}}}))};var t,i}return e.factory=function(){var t=function(){return new e};return t},e}();t.PersonaDirective=u;var d=function(){function e(e){this.$log=e}return e.$inject=["$log"],e}();t.PersonaController=d,t.module=n.module("officeuifabric.components.persona",["officeuifabric.components"]).directive("uifPersona",u.factory()).directive("uifPersonaInitials",l.factory()).directive("uifPersonaPrimaryText",c.factory("primary")).directive("uifPersonaSecondaryText",c.factory("secondary")).directive("uifPersonaTertiaryText",c.factory("tertiary")).directive("uifPersonaOptionalText",c.factory(""))},function(e,t){"use strict";!function(e){e[e.lightBlue=0]="lightBlue",e[e.blue=1]="blue",e[e.darkBlue=2]="darkBlue",e[e.teal=3]="teal",e[e.lightGreen=4]="lightGreen",e[e.green=5]="green",e[e.darkGreen=6]="darkGreen",e[e.lightPink=7]="lightPink",e[e.pink=8]="pink",e[e.magenta=9]="magenta",e[e.purple=10]="purple",e[e.black=11]="black",e[e.orange=12]="orange",e[e.red=13]="red",e[e.darkRed=14]="darkRed"}(t.PersonaInitialsColor||(t.PersonaInitialsColor={}));t.PersonaInitialsColor},function(e,t){"use strict";!function(e){e[e.tiny=0]="tiny",e[e.xsmall=1]="xsmall",e[e.small=2]="small",e[e.medium=3]="medium",e[e.large=4]="large",e[e.xlarge=5]="xlarge"}(t.PersonaSize||(t.PersonaSize={}));t.PersonaSize},function(e,t,i){"use strict";var n=i(2),r=i(46),o=i(47),s=function(){function e(e,t){this.$log=e,this.$scope=t,t.pivotClick=function(e){t.uifPivots.forEach(function(i,n){i.selected=n===e,i.selected&&(t.uifSelected=i)})}}return e.$inject=["$log","$scope"],e}();t.PivotController=s;var a=function(){function e(e){this.title=e}return e}();t.PivotItem=a;var c=function(){function e(){this.restrict="E",this.transclude=!0,this.replace=!1,this.template='<li class="ms-Pivot-link ms-Pivot-link--overflow"><uif-icon uif-type="ellipsis" class="ms-Pivot-ellipsis"></uif-icon><ng-transclude></ng-transclude></li>',this.scope=!1}return e.factory=function(){var t=function(){return new e};return t},e}();t.PivotEllipsisDirective=c;var l=function(){function e(){this.restrict="E",this.transclude=!0,this.replace=!1,this.controller=s,this.require=["uifPivot"],this.template='<ul class="ms-Pivot" ng-class="getClasses()" ><span ng-repeat-start="pivot in uifPivots"></span><li class="ms-Pivot-link" ng-click="pivotClick($index)" ng-class="{\'is-selected\': pivot.selected}">{{pivot.title}}</li> <span ng-repeat-end></span><ng-transclude></ng-transclude></ul>',this.scope={uifPivots:"=?",uifSelected:"=?",uifSize:"@",uifType:"@"}}return e.factory=function(){var t=function(){return new e};return t},e.prototype.link=function(e,t,i,s){var a=s[0];e.$watch("uifSize",function(e){n.isDefined(e)&&n.isUndefined(r.PivotSize[e])&&a.$log.error('Error [ngOfficeUiFabric] officeuifabric.components.pivot - Unsupported size: "'+e+'" is not a valid value for uifSize. It should be regular or large.')}),e.$watch("uifType",function(e){n.isDefined(e)&&n.isUndefined(o.PivotType[e])&&a.$log.error('Error [ngOfficeUiFabric] officeuifabric.components.pivot - Unsupported size: "'+e+'" is not a valid value for uifType. It should be regular or tabs.')}),e.$watch("uifSelected",function(t,i){if(n.isDefined(t)){e.uifPivots.forEach(function(e){e.selected=e.title===t.title});var r=e.uifPivots.filter(function(e){return e.selected});if(r.length>1)for(var o=1;o<r.length;o++)r[o].selected=!1}}),e.getClasses=function(){var t="";return t+=o.PivotType[e.uifType]===o.PivotType.tabs?"ms-Pivot--tabs":"",t+=r.PivotSize[e.uifSize]===r.PivotSize.large?" ms-Pivot--large":""}},e}();t.PivotDirective=l,t.module=n.module("officeuifabric.components.pivot",["officeuifabric.components"]).directive("uifPivot",l.factory()).directive("uifPivotEllipsis",c.factory())},function(e,t){"use strict";!function(e){e[e.regular=0]="regular",e[e.large=1]="large"}(t.PivotSize||(t.PivotSize={}));t.PivotSize},function(e,t){"use strict";!function(e){e[e.regular=0]="regular",e[e.tabs=1]="tabs"}(t.PivotType||(t.PivotType={}));t.PivotType},function(e,t,i){"use strict";var n=i(2),r=function(){function e(t){this.log=t,this.restrict="E",this.template='<div class="ms-ProgressIndicator"><div class="ms-ProgressIndicator-itemName">{{uifName}}</div><div class="ms-ProgressIndicator-itemProgress"><div class="ms-ProgressIndicator-progressTrack"></div><div class="ms-ProgressIndicator-progressBar" ng-style="{width: uifPercentComplete+\'%\'}"></div></div><div class="ms-ProgressIndicator-itemDescription">{{uifDescription}}</div></div>',this.scope={uifDescription:"@",uifName:"@",uifPercentComplete:"@"},e.log=t}return e.factory=function(){var t=function(t){return new e(t)};return t.$inject=["$log"],t},e.prototype.link=function(t){t.$watch("uifPercentComplete",function(i,n){if(null==i||""===i)return void(t.uifPercentComplete=0);var r=parseFloat(i);(isNaN(r)||r<0||r>100)&&(e.log.error("Error [ngOfficeUiFabric] officeuifabric.components.progressindicator - Percent complete must be a valid number between 0 and 100."),t.uifPercentComplete=Math.max(Math.min(r,100),0))})},e}();t.ProgressIndicatorDirective=r,t.module=n.module("officeuifabric.components.progressindicator",["officeuifabric.components"]).directive("uifProgressIndicator",r.factory())},function(e,t,i){"use strict";var n=i(2),r=function(){function e(){this.template='<div class="ms-SearchBox" ng-class="{\'is-active\':isActive, \'is-disabled\':isDisabled}"><input class="ms-SearchBox-field" ng-focus="inputFocus()" ng-blur="inputBlur()" ng-model="value" id="{{::\'searchBox_\'+$id}}" ng-disabled="isDisabled" /><label class="ms-SearchBox-label" for="{{::\'searchBox_\'+$id}}" ng-hide="isLabelHidden"><i class="ms-SearchBox-icon ms-Icon ms-Icon--search" ></i> {{placeholder}}</label><button class="ms-SearchBox-closeButton" ng-mousedown="btnMousedown()" type="button"><i class="ms-Icon ms-Icon--x"></i></button></div>',this.scope={placeholder:"=?",value:"=?"}}return e.factory=function(){var t=function(){return new e};return t},e.prototype.link=function(e,t,i){e.isFocus=!1,e.isCancel=!1,e.isLabelHidden=!1,e.isActive=!1,e.inputFocus=function(){e.isFocus=!0,e.isLabelHidden=!0,e.isActive=!0},e.inputBlur=function(){e.isCancel&&(e.value="",e.isLabelHidden=!1),e.isActive=!1,"undefined"!=typeof e.value&&""!==e.value||(e.isLabelHidden=!1),e.isFocus=e.isCancel=!1},e.btnMousedown=function(){e.isCancel=!0},e.$watch("value",function(t){e.isFocus||(t&&""!==t?e.isLabelHidden=!0:e.isLabelHidden=!1,e.value=t)}),e.$watch("placeholder",function(t){e.placeholder=t}),i.$observe("disabled",function(t){e.isDisabled=!!t})},e}();t.SearchBoxDirective=r,t.module=n.module("officeuifabric.components.searchbox",["officeuifabric.components"]).directive("uifSearchbox",r.factory())},function(e,t,i){"use strict";var n=i(2),r=i(51),o=function(){function e(){this.restrict="E",this.transclude=!0,this.replace=!0,this.template='<div class="ms-Spinner"></div>',this.controller=s,this.scope={ngShow:"=",uifSize:"@"}}return e.factory=function(){var t=function(){return new e};return t},e.prototype.link=function(e,t,i,o,s){n.isDefined(i.uifSize)&&(n.isUndefined(r.SpinnerSize[i.uifSize])&&o.$log.error("Error [ngOfficeUiFabric] officeuifabric.components.spinner - Unsupported size: Spinner size ('"+i.uifSize+"') is not supported by the Office UI Fabric."),r.SpinnerSize[i.uifSize]===r.SpinnerSize.large&&t.addClass("ms-Spinner--large")),null!=i.ngShow?e.$watch("ngShow",function(e,t,i){e?i.start():i.stop()}):e.start(),s(function(e){if(e.length>0){var i=n.element("<div></div>");i.addClass("ms-Spinner-label").append(e),t.append(i)}}),e.init()},e}();t.SpinnerDirective=o;var s=function(){function e(e,t,i,n){var o=this;this.$scope=e,this.$element=t,this.$interval=i,this.$log=n,this._offsetSize=.179,this._numCircles=8,this._animationSpeed=90,this._circles=[],e.init=function(){o._parentSize=r.SpinnerSize[o.$scope.uifSize]===r.SpinnerSize.large?28:20,o.createCirclesAndArrange(),o.setInitialOpacity()},e.start=function(){o._animationInterval=i(function(){for(var e=o._circles.length;e--;)o.fadeCircle(o._circles[e])},o._animationSpeed)},e.stop=function(){i.cancel(o._animationInterval)}}return e.prototype.createCirclesAndArrange=function(){for(var e=0,t=this._parentSize*this._offsetSize,i=2*Math.PI/this._numCircles,n=this._numCircles,r=.5*(this._parentSize-t);n--;){var o=this.createCircle(),s=Math.round(.5*this._parentSize+r*Math.cos(e)-.5*o[0].clientWidth)-.5*t,c=Math.round(.5*this._parentSize+r*Math.sin(e)-.5*o[0].clientHeight)-.5*t;this.$element.append(o),o.css("left",s+"px"),o.css("top",c+"px"),e+=i;var l=new a(o,n);this._circles.push(l)}},e.prototype.createCircle=function(){var e=n.element("<div></div>"),t=this._parentSize*this._offsetSize+"px";return e.addClass("ms-Spinner-circle").css("width",t).css("height",t),e},e.prototype.setInitialOpacity=function(){var e,t=this;this._fadeIncrement=1/this._numCircles,this._circles.forEach(function(i,n){e=t._fadeIncrement*(n+1),i.opacity=e})},e.prototype.fadeCircle=function(e){var t=e.opacity-this._fadeIncrement;t<=0&&(t=1),e.opacity=t},e.$inject=["$scope","$element","$interval","$log"],e}(),a=function(){function e(e,t){this.circleElement=e,this.circleIndex=t}return Object.defineProperty(e.prototype,"opacity",{get:function(){return+this.circleElement.css("opacity")},set:function(e){this.circleElement.css("opacity",e)},enumerable:!0,configurable:!0}),e}();t.module=n.module("officeuifabric.components.spinner",["officeuifabric.components"]).directive("uifSpinner",o.factory())},function(e,t){"use strict";!function(e){e[e.small=0]="small",e[e.large=1]="large"}(t.SpinnerSize||(t.SpinnerSize={}));t.SpinnerSize},function(e,t,i){"use strict";var n=i(2),r=i(53),o=i(54),s=function(){function e(e,t){this.$scope=e,this.$log=t,this.$scope.orderBy=null,this.$scope.orderAsc=!0,this.$scope.rows=[]}return Object.defineProperty(e.prototype,"orderBy",{get:function(){return this.$scope.orderBy},set:function(e){this.$scope.orderBy=e,this.$scope.$digest()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"orderAsc",{get:function(){return this.$scope.orderAsc},set:function(e){this.$scope.orderAsc=e,this.$scope.$digest()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"rowSelectMode",{get:function(){return this.$scope.rowSelectMode},set:function(e){void 0===r.TableRowSelectModeEnum[e]&&this.$log.error("Error [ngOfficeUiFabric] officeuifabric.components.table. '"+e+"' is not a valid option for 'uif-row-select-mode'. Valid options are none|single|multiple."),this.$scope.rowSelectMode=e,this.$scope.$digest()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"rows",{get:function(){return this.$scope.rows},set:function(e){this.$scope.rows=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"selectedItems",{get:function(){for(var e=[],t=0;t<this.rows.length;t++)this.rows[t].selected===!0&&e.push(this.rows[t].item);return e},enumerable:!0,configurable:!0}),e.$inject=["$scope","$log"],e}(),a=function(){function e(){this.restrict="E",this.transclude=!0,this.replace=!0,this.template="<table ng-class=\"['ms-Table', tableTypeClass]\" ng-transclude></table>",this.controller=s,this.controllerAs="table"}return e.factory=function(){var t=function(){return new e};return t},e.prototype.link=function(e,t,i,n){void 0!==i.uifRowSelectMode&&null!==i.uifRowSelectMode&&(void 0===r.TableRowSelectModeEnum[i.uifRowSelectMode]?n.$log.error("Error [ngOfficeUiFabric] officeuifabric.components.table. '"+i.uifRowSelectMode+"' is not a valid option for 'uif-row-select-mode'. Valid options are none|single|multiple."):e.rowSelectMode=i.uifRowSelectMode),void 0===e.rowSelectMode&&(e.rowSelectMode=r.TableRowSelectModeEnum[r.TableRowSelectModeEnum.none]),void 0!==i.uifTableType&&null!==i.uifTableType&&(void 0===o.TableTypeEnum[i.uifTableType]?n.$log.error("Error [ngOfficeUiFabric] officeuifabric.components.table. '"+i.uifTableType+"' is not a valid option for 'uif-table-type'. Valid options are fixed|fluid."):e.tableType=i.uifTableType),void 0===e.tableType&&(e.tableType=o.TableTypeEnum[o.TableTypeEnum.fluid]),e.tableType===o.TableTypeEnum[o.TableTypeEnum.fixed]&&(e.tableTypeClass="ms-Table--fixed")},e}();t.TableDirective=a;var c=function(){function e(e,t){this.$scope=e,this.$log=t}return Object.defineProperty(e.prototype,"item",{get:function(){return this.$scope.item},set:function(e){this.$scope.item=e,this.$scope.$digest()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"selected",{get:function(){return this.$scope.selected},set:function(e){this.$scope.selected=e,this.$scope.$digest()},enumerable:!0,configurable:!0}),e.$inject=["$scope","$log"],e}(),l=function(){function e(){this.restrict="E",this.transclude=!0,this.replace=!0,this.template="<tr ng-transclude></tr>",this.require="^uifTable",this.scope={item:"=uifItem"},this.controller=c}return e.factory=function(){var t=function(){return new e};return t},e.prototype.link=function(e,t,i,n){if(void 0!==i.uifSelected&&null!==i.uifSelected){var o=i.uifSelected.toLowerCase();"true"!==o&&"false"!==o?n.$log.error("Error [ngOfficeUiFabric] officeuifabric.components.table. '"+i.uifSelected+"' is not a valid boolean value. Valid options are true|false."):"true"===o&&(e.selected=!0)}void 0!==e.item&&n.rows.push(e),e.rowClick=function(t){e.selected=!e.selected,e.$apply()},e.$watch("selected",function(e,i,o){if(e===!0){if(n.rowSelectMode===r.TableRowSelectModeEnum[r.TableRowSelectModeEnum.single]&&n.rows)for(var s=0;s<n.rows.length;s++)n.rows[s]!==o&&(n.rows[s].selected=!1);t.addClass("is-selected")}else t.removeClass("is-selected")}),n.rowSelectMode!==r.TableRowSelectModeEnum[r.TableRowSelectModeEnum.none]&&void 0!==e.item&&t.on("click",e.rowClick),n.rowSelectMode===r.TableRowSelectModeEnum[r.TableRowSelectModeEnum.none]&&t.css("cursor","default")},e}();t.TableRowDirective=l;var u=function(){function e(){this.restrict="E",this.template='<td class="ms-Table-rowCheck"></td>',this.replace=!0,this.require=["^uifTable","?^uifTableHead","^uifTableRow"]}return e.factory=function(){var t=function(){return new e};return t},e.prototype.link=function(e,t,i,n){var o=n[1];o&&t.replaceWith('<th class="ms-Table-rowCheck"></th>'),e.rowSelectClick=function(t){var i=n[0],o=n[2];if(i.rowSelectMode===r.TableRowSelectModeEnum[r.TableRowSelectModeEnum.multiple]&&(void 0===o.item||null===o.item)){for(var s=!1,a=0;a<i.rows.length;a++)if(i.rows[a].selected!==!0){s=!0;break}for(var a=0;a<i.rows.length;a++)i.rows[a].selected!==s&&(i.rows[a].selected=s);e.$apply()}},t.on("click",e.rowSelectClick)},e}();t.TableRowSelectDirective=u;var d=function(){function e(){this.restrict="E",this.transclude=!0,this.template="<td ng-transclude></td>",this.replace=!0}return e.factory=function(){var t=function(){return new e};return t},e}();t.TableCellDirective=d;var f=function(){function e(){this.restrict="E",this.transclude=!0,this.replace=!0,this.template="<th ng-transclude></th>",this.require="^uifTable"}return e.factory=function(){var t=function(){return new e};return t},e.prototype.link=function(e,t,i,n){e.headerClick=function(e){n.orderBy===i.uifOrderBy?n.orderAsc=!n.orderAsc:(n.orderBy=i.uifOrderBy,n.orderAsc=!0)},e.$watch("table.orderBy",function(e,n,r){if(n!==e&&e===i.uifOrderBy){for(var o=t.parent().children(),s=0;s<o.length;s++)2===o.eq(s).children().length&&o.eq(s).children().eq(1).remove();t.append('<span class="uif-sort-order">&nbsp;\t <i class="ms-Icon ms-Icon--caretDown" aria-hidden="true"></i></span>')}}),e.$watch("table.orderAsc",function(e,i,n){if(2===t.children().length){var r=i?"ms-Icon--caretDown":"ms-Icon--caretUp",o=e?"ms-Icon--caretDown":"ms-Icon--caretUp";t.children().eq(1).children().eq(0).removeClass(r).addClass(o)}}),"uifOrderBy"in i&&t.on("click",e.headerClick)},e}();t.TableHeaderDirective=f;var p=function(){function e(){}return e}(),m=function(){function e(){this.restrict="E",this.transclude=!0,this.template="<thead ng-transclude></thead>",this.replace=!0,this.controller=p}return e.factory=function(){var t=function(){return new e};return t},e}();t.TableHeadDirective=m;var h=function(){function e(){this.restrict="E",this.transclude=!0,this.template="<tbody ng-transclude></tbody>",this.replace=!0}return e.factory=function(){var t=function(){return new e};return t},e}();t.TableBodyDirective=h,t.module=n.module("officeuifabric.components.table",["officeuifabric.components"]).directive("uifTable",a.factory()).directive("uifTableRow",l.factory()).directive("uifTableRowSelect",u.factory()).directive("uifTableCell",d.factory()).directive("uifTableHeader",f.factory()).directive("uifTableHead",m.factory()).directive("uifTableBody",h.factory())},function(e,t){"use strict";!function(e){e[e.none=0]="none",e[e.single=1]="single",e[e.multiple=2]="multiple"}(t.TableRowSelectModeEnum||(t.TableRowSelectModeEnum={}));t.TableRowSelectModeEnum},function(e,t){"use strict";!function(e){e[e.fluid=0]="fluid",e[e.fixed=1]="fixed"}(t.TableTypeEnum||(t.TableTypeEnum={}));t.TableTypeEnum},function(e,t,i){"use strict";var n=i(2),r=i(56),o=function(){function e(e){this.$log=e}return e.$inject=["$log"],e}(),s=function(){function e(){this.controller=o,this.template="<div ng-class=\"{'is-active': isActive, 'ms-TextField': true, 'ms-TextField--underlined': uifUnderlined, 'ms-TextField--placeholder': placeholder, 'is-required': required, 'is-disabled': disabled, 'ms-TextField--multiline' : uifMultiline }\">"+'<label ng-show="labelShown" class="ms-Label" ng-click="labelClick()">{{uifLabel || placeholder}}</label><input ng-model="ngModel" ng-change="ngChange" ng-blur="inputBlur()" ng-focus="inputFocus()" ng-click="inputClick()" class="ms-TextField-field" ng-show="!uifMultiline" ng-disabled="disabled" type="{{uifType}}"min="{{min}}" max="{{max}}" step="{{step}}" /><textarea ng-model="ngModel" ng-blur="inputBlur()" ng-focus="inputFocus()" ng-click="inputClick()" class="ms-TextField-field" ng-show="uifMultiline" ng-disabled="disabled"></textarea><span class="ms-TextField-description">{{uifDescription}}</span></div>',this.scope={max:"@",min:"@",ngChange:"=?",ngModel:"=?",placeholder:"@",step:"@",uifDescription:"@",uifLabel:"@"},this.require=["uifTextfield","?ngModel"],this.restrict="E"}return e.factory=function(){var t=function(){return new e};return t},e.prototype.link=function(e,t,i,n){var o=n[0],s=n[1];e.disabled="disabled"in i,e.$watch(function(){return t.attr("disabled")},function(t){e.disabled="undefined"!=typeof t}),e.labelShown=!0,e.required="required"in i,e.uifMultiline="true"===i.uifMultiline,e.uifType=i.uifType,e.$watch("uifType",function(t,i){"undefined"!=typeof t?void 0===r.InputTypeEnum[t]&&o.$log.error("Error [ngOfficeUiFabric] officeuifabric.components.textfield - Unsupported type: The type ('"+e.uifType+"') is not supported by the Office UI Fabric. Supported options are listed here: https://github.com/ngOfficeUIFabric/ng-officeuifabric/blob/master/src/components/textfield/uifTypeEnum.ts"):e.uifType=r.InputTypeEnum.text}),e.uifUnderlined="uifUnderlined"in i,e.inputFocus=function(t){e.placeholder&&(e.labelShown=!1), e.isActive=!0},e.inputBlur=function(i){var n=t.find("input");e.placeholder&&0===n.val().length&&(e.labelShown=!0),e.isActive=!1},e.labelClick=function(i){if(e.placeholder){var n=e.uifMultiline?t.find("textarea"):t.find("input");n[0].focus()}},null!=s&&(s.$render=function(){e.placeholder&&(e.labelShown=!s.$viewValue)})},e}();t.TextFieldDirective=s,t.module=n.module("officeuifabric.components.textfield",["officeuifabric.components"]).directive("uifTextfield",s.factory())},function(e,t){"use strict";!function(e){e[e.text=0]="text",e[e.password=1]="password",e[e.email=2]="email",e[e.url=3]="url",e[e.tel=4]="tel",e[e.range=5]="range",e[e.number=6]="number"}(t.InputTypeEnum||(t.InputTypeEnum={}));t.InputTypeEnum},function(e,t,i){"use strict";var n=i(2),r=function(){function e(){this.template='<div ng-class="[\'ms-Toggle\', textLocation, {\'is-disabled\': disabled}]"><span class="ms-Toggle-description"><ng-transclude/></span><input type="checkbox" id="{{::$id}}" class="ms-Toggle-input" ng-model="ngModel" ng-change="ngChange()" ng-disabled="disabled" ng-attr-ng-true-value="{{ngTrueValue || undefined}}" ng-attr-ng-false-value="{{ngFalseValue || undefined}}" /><label for="{{::$id}}" class="ms-Toggle-field"><span class="ms-Label ms-Label--off">{{uifLabelOff}}</span><span class="ms-Label ms-Label--on">{{uifLabelOn}}</span></label></div>',this.restrict="E",this.transclude=!0,this.scope={ngChange:"&?",ngFalseValue:"@?",ngModel:"=?",ngTrueValue:"@?",uifLabelOff:"@",uifLabelOn:"@",uifTextLocation:"@"}}return e.factory=function(){var t=function(){return new e};return t},e.prototype.link=function(e,t,i){if(e.uifTextLocation){var n=e.uifTextLocation;n=n.charAt(0).toUpperCase()+n.slice(1),e.textLocation=" ms-Toggle--text"+n}e.$watch(function(){return t.attr("disabled")},function(t){e.disabled="undefined"!=typeof t}),e.disabled="disabled"in i},e}();t.ToggleDirective=r,t.module=n.module("officeuifabric.components.toggle",["officeuifabric.components"]).directive("uifToggle",r.factory())},function(e,t,i){"use strict";var n=i(2),r=i(59),o=i(60),s=i(61),a=function(){function e(e,t){this.$scope=e,this.$log=t,this.$scope.selectMode=null,this.$scope.items=[]}return Object.defineProperty(e.prototype,"items",{get:function(){return this.$scope.items},set:function(e){this.$scope.items=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"selectedItems",{get:function(){return this.$scope.selectedItems},set:function(e){this.$scope.selectedItems=e},enumerable:!0,configurable:!0}),e.$inject=["$scope","$log"],e}(),c=function(){function e(){this.restrict="E",this.transclude=!0,this.replace=!0,this.template='<div class="ms-OrgChart" ng-transclude ></div>',this.controller=a,this.scope={selectedItems:"=?uifSelectedItems"}}return e.factory=function(){var t=function(){return new e};return t},e.prototype.link=function(e,t,i,n){if(i.uifSelectMode)switch(s.OrgChartSelectModeEnum[i.uifSelectMode]){case s.OrgChartSelectModeEnum.single:case s.OrgChartSelectModeEnum.multiple:n.selectMode=s.OrgChartSelectModeEnum[i.uifSelectMode];break;default:n.$log.error("Error [ngOfficeUIFabric] officeuifabric.components.orgchart - Unsupported select-mode: The select-mode ('"+i.uifSelectMode+") is not supperted. Supported options are: single, multiple")}},e}();t.OrgChartDirective=c;var l=function(){function e(){this.restrict="E",this.transclude=!0,this.replace=!0,this.template='<div class="ms-OrgChart-group" ng-transclude ></div>'}return e.factory=function(){var t=function(){return new e};return t},e}();t.OrgChartGroupDirective=l;var u=function(){function e(){this.restrict="E",this.transclude=!0,this.replace=!0,this.template='<div class="ms-OrgChart-groupTitle" ng-transclude ></div>'}return e.factory=function(){var t=function(){return new e};return t},e}();t.OrgChartGroupTitleDirective=u;var d=function(){function e(){this.restrict="E",this.transclude=!0,this.replace=!0,this.template='<ul class="ms-OrgChart-list" ng-transclude ></ul>'}return e.factory=function(){var t=function(){return new e};return t},e}();t.OrgChartListDirective=d;var f=function(){function e(e){this.$log=e,this.restrict="E",this.transclude=!0,this.replace=!0,this.template='<li class="ms-OrgChart-listItem"><div class="ms-Persona" ng-transclude ></div></li>',this.require="^uifOrgChart",this.scope={item:"=?uifItem",presence:"=?uifPresence",selected:"=?uifSelected"}}return e.factory=function(){var t=function(t){return new e(t)};return t.$inject=["$log"],t},e.prototype.compile=function(e,t,i){return{post:this.postLink}},e.prototype.postLink=function(e,t,i,n,a){if(void 0===e.selected&&(e.selected=!1),e.presence)switch(r.OrgChartPresenceEnum[e.presence]){case r.OrgChartPresenceEnum.available:t.children().eq(0).addClass("ms-Persona--available");break;case r.OrgChartPresenceEnum.busy:t.children().eq(0).addClass("ms-Persona--busy");break;case r.OrgChartPresenceEnum.away:t.children().eq(0).addClass("ms-Persona--away");break;case r.OrgChartPresenceEnum.blocked:t.children().eq(0).addClass("ms-Persona--blocked");break;case r.OrgChartPresenceEnum.dnd:t.children().eq(0).addClass("ms-Persona--dnd");break;case r.OrgChartPresenceEnum.offline:t.children().eq(0).addClass("ms-Persona--offline");break;default:n.$log.error("Error [ngOfficeUIFabric] officeuifabric.components.orgchart - Unsupported presence: The presence ('"+e.presence+"') is not supperted by the Office UI Fabric. Supported options are: available, busy, away, blocked, dnd, offline.")}if(i.uifStyle)switch(o.OrgChartStyleEnum[i.uifStyle]){case o.OrgChartStyleEnum.square:t.children().eq(0).addClass("ms-Persona--square");break;case o.OrgChartStyleEnum.standard:break;default:n.$log.error("Error [ngOfficeUIFabric] officeuifabric.components.orgchart - Unsupported style: The style ('"+i.uifStyle+") is not supperted by the Office UI Fabric. Supported options are: standard(default), square")}if(void 0!==n.selectMode&&t.children().eq(0).addClass("ms-Persona--selectable"),e.$watch("selected",function(e,i){void 0!==n.selectMode&&(e===!0?t.children().eq(0).addClass("is-selected"):t.children().eq(0).removeClass("is-selected"))}),e.item&&n.items.push(e),(n.selectMode===s.OrgChartSelectModeEnum.single||n.selectMode===s.OrgChartSelectModeEnum.multiple)&&e.selected){if(n.selectMode===s.OrgChartSelectModeEnum.single){n.selectedItems&&(n.selectedItems=[]);for(var c=0;c<n.items.length;c++)n.items[c]!==e&&(n.items[c].selected=!1)}t.children().eq(0).addClass("is-selected"),n.selectedItems&&n.selectedItems.push(e.item)}e.personaClick=function(i){if(e.selected=!e.selected,e.selected){if(n.selectMode===s.OrgChartSelectModeEnum.single){if(n.items)for(var r=0;r<n.items.length;r++)n.items[r]!==e&&(n.items[r].selected=!1);t.children().eq(0).addClass("is-selected"),n.selectedItems=[],n.selectedItems.push(e.item)}n.selectMode===s.OrgChartSelectModeEnum.multiple&&(t.children().eq(0).addClass("is-selected"),n.selectedItems&&n.selectedItems.push(e.item))}else if(t.children().eq(0).removeClass("is-selected"),n.selectedItems){var o=n.selectedItems.indexOf(e.item);o>-1&&n.selectedItems.splice(o,1)}e.$apply()},n.selectMode!==s.OrgChartSelectModeEnum.single&&n.selectMode!==s.OrgChartSelectModeEnum.multiple||!e.item||t.children().eq(0).on("click",e.personaClick)},e}();t.OrgChartPersonaDirective=f;var p=function(){function e(){this.restrict="E",this.replace=!0,this.template='\n <div class="ms-Persona-imageArea">\n <i class="ms-Persona-placeholder ms-Icon ms-Icon--person"></i>\n <img class="ms-Persona-image" ng-src="{{ngSrc}}" />\n </div>\n ',this.scope={ngSrc:"="}}return e.factory=function(){var t=function(){return new e};return t},e}();t.OrgChartImageDirective=p;var m=function(){function e(){this.restrict="E",this.replace=!0,this.template='<div class="ms-Persona-presence" ></div>'}return e.factory=function(){var t=function(){return new e};return t},e.prototype.link=function(e,t,i,n){e.$parent.presence||t.css("display","none")},e}();t.OrgChartPresenceDirective=m;var h=function(){function e(){this.restrict="E",this.transclude=!0,this.replace=!0,this.template='<div class="ms-Persona-details" ng-transclude ></div>'}return e.factory=function(){var t=function(){return new e};return t},e}();t.OrgChartDetailsDirective=h;var v=function(){function e(){this.restrict="E",this.transclude=!0,this.replace=!0,this.template='<div class="ms-Persona-primaryText" ng-transclude ></div>'}return e.factory=function(){var t=function(){return new e};return t},e}();t.OrgChartPrimaryTextDirective=v;var g=function(){function e(){this.restrict="E",this.transclude=!0,this.replace=!0,this.template='<div class="ms-Persona-secondaryText" ng-transclude ></div>'}return e.factory=function(){var t=function(){return new e};return t},e}();t.OrgChartSecondaryTextDirective=g;var y=function(){function e(){}return e.factory=function(){return function(e,t){var i=[];if(e){for(var n=0;n<e.length;n++){var r=e[n][t];i.indexOf(r)===-1&&i.push(r)}return i}}},e}();t.OrgChartGroupByFilter=y,t.module=n.module("officeuifabric.components.orgchart",["officeuifabric.components"]).directive("uifOrgChart",c.factory()).directive("uifOrgChartGroup",l.factory()).directive("uifOrgChartGroupTitle",u.factory()).directive("uifOrgChartList",d.factory()).directive("uifOrgChartPersona",f.factory()).directive("uifOrgChartImage",p.factory()).directive("uifOrgChartPresence",m.factory()).directive("uifOrgChartDetails",h.factory()).directive("uifOrgChartPrimaryText",v.factory()).directive("uifOrgChartSecondaryText",g.factory()).filter("uifOrgChartGroupBy",y.factory)},function(e,t){"use strict";!function(e){e[e.available=0]="available",e[e.busy=1]="busy",e[e.away=2]="away",e[e.blocked=3]="blocked",e[e.dnd=4]="dnd",e[e.offline=5]="offline"}(t.OrgChartPresenceEnum||(t.OrgChartPresenceEnum={}));t.OrgChartPresenceEnum},function(e,t){"use strict";!function(e){e[e.standard=0]="standard",e[e.square=1]="square"}(t.OrgChartStyleEnum||(t.OrgChartStyleEnum={}));t.OrgChartStyleEnum},function(e,t){"use strict";!function(e){e[e.single=0]="single",e[e.multiple=1]="multiple"}(t.OrgChartSelectModeEnum||(t.OrgChartSelectModeEnum={}));t.OrgChartSelectModeEnum},function(e,t,i){"use strict";var n=i(2),r=i(40),o=i(44),s=i(22),a="uif-people-search",c=function(){function e(){this.people=[]}return e}();t.GroupedPeopleData=c;var l=function(){function e(e,t,i){this.$scope=e,this.$filter=t,this.$element=i}return e.prototype.getSelectedPersons=function(){return this.$scope.selectedPersons},e.prototype.pickerType=function(){var e=this.$scope.type;return n.isUndefined(e)?u[u.grouped]:this.$scope.type},e.prototype.searchQuery=function(){return this.$scope.searchQuery},e.prototype.search=function(){this.bindPeople(this.$scope.searchQuery),this.$scope.$broadcast(a,this.searchQuery())},e.prototype.bindPeople=function(e){var t=this,i=this.$scope.peopleCallback()(e);if(i=i||[],i instanceof Array)this.$scope.groups=this.createPeopleDataStructure(i);else if("function"==typeof i.then){var n=angular.element(this.$element[0].querySelector(".ms-PeoplePicker-searchMore")).controller(""+m.directiveName);n&&n.isSearching(!0);var r=this;i.then(function(e){r.$scope.groups=t.createPeopleDataStructure(e)})["finally"](function(){n&&n.isSearching(!1)})}},e.prototype.createPeopleDataStructure=function(e){var t=this,i=[];return angular.forEach(e,function(e){var n=t.$filter("filter")(i,{group:e.group}),r=1===n.length;if(r){var o=n[0];o.people.push(e)}else{var s=new c;s.group=e.group,s.people.push(e),i.push(s)}}),i},e.$inject=["$scope","$filter","$element"],e}();t.PeoplePickerController=l;var u;!function(e){e[e.grouped=0]="grouped",e[e.compact=1]="compact",e[e.memberList=2]="memberList",e[e.facePile=3]="facePile"}(u||(u={}));var d=function(){function e(t,i,a,c){var d=this;this.$document=t,this.$timeout=i,this.$log=a,this.$window=c,this.replace=!0,this.require=["ngModel",""+e.directiveName],this.restrict="E",this.transclude=!0,this.controller=l,this.scope={delay:"@uifSearchDelay",facePileHeader:"@?uifFacepileHeader",ngDisabled:"=?",ngModel:"=",onSelectedPersonClick:"&?uifSelectedPersonClick",peopleCallback:"&uifPeople",placeholder:"@?",type:"@?uifType"},this.templateTypes={},this.template=function(e,t){var i=t.uifType;if(n.isUndefined(i))return d.templateTypes[u.grouped];if(void 0===u[i])throw d.$log.error("Error [ngOfficeUiFabric] officeuifabric.components.peoplepicker - unsupported people picker type:\nthe type '"+i+"' is not supported by ng-Office UI Fabric as valid type for people picker.Supported types can be found under PeoplePickerTypes enum here:\nhttps://github.com/ngOfficeUIFabric/ng-officeuifabric/blob/master/src/components/peoplepicker/peoplePickerDirective.ts"),"[ngOfficeUiFabric] - Error";return d.templateTypes[u[i]]},this.link=function(e,t,i,n,r){var o=n[0],s=n[1];d.initDisabledState(t,e,i),e.facePileHeader=e.facePileHeader||"Suggested contacts",e.$watchCollection("selectedPersons",function(e,i,n){d.resizeSearchField(t)}),o.$render=function(){o.$viewValue?e.selectedPersons=o.$viewValue:e.selectedPersons=[],d.resizeSearchField(t)},s.search();var a=null;e.onSearchKeyUp=function(i){var n=angular.element(t[0].querySelector(".ms-PeoplePicker-searchMore"));0!==n.length&&(e.searchQuery?t.addClass("is-searching"):t.removeClass("is-searching"),e.searchQuery?n.addClass("is-active"):n.removeClass("is-active"),d.animateSelectedPeople(t)),e.delay&&(null!=a&&d.$timeout.cancel(a),a=d.$timeout(function(){s.search()},e.delay))},e.onPeoplePickerActive=function(i){if(d.smoothScrollTo(t[0]),e.type!==u[u.facePile]){var n=angular.element(t[0].querySelector(".ms-PeoplePicker-results"));n[0].style.width=t[0].clientWidth-2+"px"}else e.type===u[u.facePile]&&d.animateSelectedPeople(t);i.stopPropagation(),t.addClass("is-active")},e.addPersonToSelectedPeople=function(t){e.selectedPersons.indexOf(t)===-1&&(e.selectedPersons.push(t),o.$setViewValue(e.selectedPersons))},e.removePersonFromSelectedPeople=function(t,i){var n=e.selectedPersons.indexOf(t);e.selectedPersons.splice(n,1),o.$setViewValue(e.selectedPersons),i.stopPropagation()},e.removePersonFromSearchResults=function(e,t,i){i.stopPropagation();var n=e.indexOf(t);e.splice(n,1)},d.$document.on("click",function(){t.removeClass("is-active")}),e.type===u[u.facePile]&&r(function(i){d.insertFacePileHeader(i,e,t),d.insertFacePileSearchMore(i,e,t)})},this.templateTypes[u.grouped]='<div class="ms-PeoplePicker">\n <div class="ms-PeoplePicker-searchBox">\n <div class="ms-PeoplePicker-persona" ng-repeat="person in selectedPersons track by $index">\n <uif-persona ng-click="onSelectedPersonClick()(person)"\n uif-style="'+r.PersonaStyleEnum[r.PersonaStyleEnum.square]+'"\n uif-size="'+o.PersonaSize[o.PersonaSize.xsmall]+'"\n uif-presence="{{person.presence}}"\n uif-image-url="{{person.icon}}">\n <uif-persona-initials uif-color="{{person.color}}">{{person.initials}}</uif-persona-initials>\n <uif-persona-primary-text>{{person.primaryText}}</uif-persona-primary-text>\n </uif-persona>\n <button type="button" ng-click="removePersonFromSelectedPeople(person, $event)" class="ms-PeoplePicker-personaRemove">\n <uif-icon uif-type="'+s.IconEnum[s.IconEnum.x]+'"></uif-icon>\n </button>\n </div>\n <input ng-click="onPeoplePickerActive($event)"\n placeholder="{{placeholder}}"\n ng-model="searchQuery"\n class="ms-PeoplePicker-searchField"\n ng-focus="onPeoplePickerActive($event)"\n ng-keyup="onSearchKeyUp($event)"\n type="text">\n </div>\n <div class="ms-PeoplePicker-results">\n <div class="ms-PeoplePicker-resultGroups">\n <div class="ms-PeoplePicker-resultGroup" ng-repeat="groupData in groups | orderBy:\'-order\'">\n <div class="ms-PeoplePicker-resultGroupTitle">{{groupData.group.name}}</div>\n <uif-people-picker-result-list\n ng-model="groupData.people"\n uif-person-click="addPersonToSelectedPeople"\n uif-person-close-click="removePersonFromSearchResults"\n uif-style="'+r.PersonaStyleEnum[r.PersonaStyleEnum.square]+'"\n uif-size="'+o.PersonaSize[o.PersonaSize.medium]+'"></uif-people-picker-result-list>\n </div>\n </div>\n <ng-transclude />\n </div>\n </div>',this.templateTypes[u.compact]='<div class="ms-PeoplePicker ms-PeoplePicker--compact">\n <div class="ms-PeoplePicker-searchBox">\n <div class="ms-PeoplePicker-persona" ng-repeat="person in selectedPersons track by $index">\n <uif-persona ng-click="onSelectedPersonClick()(person)"\n uif-style="'+r.PersonaStyleEnum[r.PersonaStyleEnum.square]+'"\n uif-size="'+o.PersonaSize[o.PersonaSize.xsmall]+'"\n uif-presence="{{person.presence}}"\n uif-image-url="{{person.icon}}">\n <uif-persona-initials uif-color="{{person.color}}">{{person.initials}}</uif-persona-initials>\n <uif-persona-primary-text>{{person.primaryText}}</uif-persona-primary-text>\n </uif-persona>\n <button type="button" ng-click="removePersonFromSelectedPeople(person, $event)" class="ms-PeoplePicker-personaRemove">\n <uif-icon uif-type="'+s.IconEnum[s.IconEnum.x]+'"></uif-icon>\n </button>\n </div>\n <input ng-click="onPeoplePickerActive($event)"\n ng-model="searchQuery"\n placeholder="{{placeholder}}"\n class="ms-PeoplePicker-searchField"\n ng-focus="onPeoplePickerActive($event)"\n ng-keyup="onSearchKeyUp($event)"\n type="text">\n </div>\n <div class="ms-PeoplePicker-results">\n <div class="ms-PeoplePicker-resultGroups">\n <div class="ms-PeoplePicker-resultGroup" ng-repeat="groupData in groups | orderBy:\'-order\'">\n <div class="ms-PeoplePicker-resultGroupTitle">{{groupData.group.name}}</div>\n <uif-people-picker-result-list\n ng-model="groupData.people"\n uif-picker-type="'+u[u.compact]+'"\n uif-person-click="addPersonToSelectedPeople"\n uif-person-close-click="removePersonFromSearchResults"\n uif-style="'+r.PersonaStyleEnum[r.PersonaStyleEnum.square]+'"\n uif-size="'+o.PersonaSize[o.PersonaSize.xsmall]+'"></uif-people-picker-result-list>\n </div>\n </div>\n <ng-transclude />\n </div>\n </div>',this.templateTypes[u.memberList]='\n <div class="ms-PeoplePicker ms-PeoplePicker--membersList">\n <div class="ms-PeoplePicker-searchBox">\n <input ng-click="onPeoplePickerActive($event)"\n placeholder="{{placeholder}}"\n ng-model="searchQuery"\n class="ms-PeoplePicker-searchField"\n ng-focus="onPeoplePickerActive($event)"\n ng-keyup="onSearchKeyUp($event)"\n type="text">\n </div>\n <div class="ms-PeoplePicker-results">\n <div class="ms-PeoplePicker-resultGroups">\n <div class="ms-PeoplePicker-resultGroup" ng-repeat="groupData in groups | orderBy:\'-order\'">\n <uif-people-picker-result-list\n ng-model="groupData.people"\n uif-person-click="addPersonToSelectedPeople"\n uif-style="'+r.PersonaStyleEnum[r.PersonaStyleEnum.round]+'"\n uif-size="'+o.PersonaSize[o.PersonaSize.medium]+'"></uif-people-picker-result-list>\n </div>\n </div>\n </div>\n <uif-people-picker-selected ng-model="selectedPersons"\n uif-selected-person-click="onSelectedPersonClick()"\n uif-person-close="removePersonFromSelectedPeople">\n <ng-transclude></ng-transclude>\n </uif-people-picker-selected>\n </div>',this.templateTypes[u.facePile]='\n <div class="ms-PeoplePicker ms-PeoplePicker--Facepile">\n <div class="ms-PeoplePicker-searchBox">\n <input ng-click="onPeoplePickerActive($event)"\n placeholder="{{placeholder}}"\n ng-model="searchQuery"\n class="ms-PeoplePicker-searchField"\n ng-focus="onPeoplePickerActive($event)"\n ng-keyup="onSearchKeyUp($event)"\n type="text">\n </div>\n <div class="ms-PeoplePicker-results">\n <div class="ms-PeoplePicker-peopleListHeader">\n <span>{{facePileHeader}}</span>\n </div>\n <div ng-repeat="groupData in groups | orderBy:\'-order\'">\n <uif-people-picker-result-list\n ng-model="groupData.people"\n uif-person-click="addPersonToSelectedPeople"\n uif-style="'+r.PersonaStyleEnum[r.PersonaStyleEnum.round]+'"\n uif-size="'+o.PersonaSize[o.PersonaSize.small]+'"></uif-people-picker-result-list>\n </div>\n <div class="uif-search-more"></div>\n </div>\n <uif-people-picker-selected ng-model="selectedPersons"\n uif-selected-person-click="onSelectedPersonClick()"\n uif-person-close="removePersonFromSelectedPeople">\n <div class="uif-people-header"></div>\n </uif-people-picker-selected>\n\n </div>'}return e.factory=function(){var t=function(t,i,n,r){return new e(t,i,n,r)};return t.$inject=["$document","$timeout","$log","$window"],t},e.prototype.initDisabledState=function(e,t,i){var n=angular.element(e[0].querySelector(".ms-PeoplePicker-searchField"));i.$observe("disabled",function(e){e?n.attr("disabled","disabled"):n.removeAttr("disabled")})},e.prototype.animateSelectedPeople=function(e){var t=angular.element(e[0].querySelector(".ms-PeoplePicker-selectedPeople"));t.addClass("ms-u-slideDownIn20"),setTimeout(function(){t.removeClass("ms-u-slideDownIn20")},1e3)},e.prototype.currentYPosition=function(){if(this.$window.pageYOffset)return this.$window.pageYOffset;var e=angular.element(this.$document[0]).find("body")[0];return e.scrollTop?e.scrollTop:0},e.prototype.elmYPosition=function(e){for(var t=e.offsetTop,i=e;i.offsetParent&&i.offsetParent!==document.body;)i=i.offsetParent,t+=i.offsetTop;return t},e.prototype.smoothScrollTo=function(e){var t=this.currentYPosition(),i=this.elmYPosition(e),n=i>t?i-t:t-i;if(n<100)return void window.scrollTo(0,i);var r=Math.round(n/30);r>=20&&(r=20);var o=Math.round(n/25),s=i>t?t+o:t-o,a=0;if(i>t)for(var c=t;c<i;c+=o)!function(e,t){setTimeout(function(){window.scrollTo(0,e)},t*r)}(s,a),s+=o,s>i&&(s=i),a++;else for(var c=t;c>i;c-=o)!function(e,t){setTimeout(function(){window.scrollTo(0,e)},t*r)}(s,a),s-=o,s<i&&(s=i),a++},e.prototype.insertFacePileHeader=function(e,t,i){for(var n=angular.element(i[0].querySelector(".uif-people-header")),r=0;r<e.length;r++){var o=angular.element(e[r]);if(o.hasClass("ms-PeoplePicker-selectedCount")){n.replaceWith(o);break}}},e.prototype.insertFacePileSearchMore=function(e,t,i){for(var n=angular.element(i[0].querySelector(".uif-search-more")),r=0;r<e.length;r++){var o=angular.element(e[r]);if(o.hasClass("ms-PeoplePicker-searchMore")){n.replaceWith(o);break}}},e.prototype.resizeSearchField=function(e){var t=angular.element(e[0].querySelector(".ms-PeoplePicker-searchBox")),i=angular.element(e[0].querySelector(".ms-PeoplePicker-searchField")),n=t.prop("offsetLeft"),r=t[0].clientWidth,o=n+r,s=t[0].querySelectorAll(".ms-PeoplePicker-persona");if(0===s.length)return void(i[0].style.width="100%");var a=angular.element(s[s.length-1]),c=a.prop("offsetLeft"),l=a[0].clientWidth,u=c+l,d=o-u-5;d<100?(d="100%",i[0].style.width="100%"):i[0].style.width=d+"px"},e.directiveName="uifPeoplePicker",e}();t.PeoplePickerDirective=d;var f=function(){function e(){this.replace=!0,this.restrict="E",this.transclude=!0,this.template='\n <ul class="ms-PeoplePicker-resultList">\n <li class="ms-PeoplePicker-result" ng-repeat="person in people track by $index">\n <div role="button" class="ms-PeoplePicker-resultBtn"\n ng-class="{\'ms-PeoplePicker-resultBtn--compact\': pickerType === \'compact\'}" ng-click="onPersonClick()(person)">\n <uif-persona\n uif-style="{{personStyle}}"\n uif-size="{{personSize}}"\n uif-presence="{{person.presence}}"\n uif-image-url="{{person.icon}}">\n <uif-persona-initials uif-color="{{person.color}}">{{person.initials}}</uif-persona-initials>\n <uif-persona-primary-text>{{person.primaryText}}</uif-persona-primary-text>\n <uif-persona-secondary-text>{{person.secondaryText}}</uif-persona-secondary-text>\n </uif-persona>\n <button type="button"\n ng-if="!person.additionalData && onPersonCloseClick()"\n ng-click="onPersonCloseClick()(people, person, $event)"\n class="ms-PeoplePicker-resultAction js-resultRemove">\n <uif-icon uif-type="'+s.IconEnum[s.IconEnum.x]+'"></uif-icon>\n </button>\n <button type="button"\n ng-if="person.additionalData"\n ng-click="expandAdditionalData($event)"\n class="ms-PeoplePicker-resultAction js-resultRemove">\n <uif-icon uif-type="'+s.IconEnum[s.IconEnum.chevronsDown]+'"></uif-icon>\n </button>\n </div>\n <div ng-if="person.additionalData" class="ms-PeoplePicker-resultAdditionalContent">\n <uif-people-picker-result-list\n ng-model="person.additionalData"\n uif-person-click="onPersonClick()"\n uif-person-close-click="onPersonCloseClick()"\n uif-picker-type="{{pickerType}}"\n uif-style="{{personStyle}}"\n uif-size="{{personSize}}"></uif-people-picker-result-list>\n </div>\n </li>\n </ul>',this.scope={onPersonClick:"&uifPersonClick",onPersonCloseClick:"&uifPersonCloseClick",people:"=ngModel",personSize:"@uifSize",personStyle:"@uifStyle",pickerType:"@uifPickerType"},this.link=function(e,t,i,n,r){e.expandAdditionalData=function(e){e.stopPropagation();for(var t=angular.element(e.target),i=0;i<10;i++){var n=t.parent();if(n.hasClass("ms-PeoplePicker-result")){n.toggleClass("is-expanded");break}t=n}}}}return e.factory=function(){var t=function(){return new e};return t},e.directiveName="uifPeoplePickerResultList",e}();t.PeoplePickerResultListDirective=f;var p=function(){function e(e,t){this.$scope=e,this.$element=t,this.searchCallbacks=[]}return e.prototype.isSearching=function(e){this.$scope.processing=e,e?this.$element.addClass("is-searching"):this.$element.removeClass("is-searching")},e.$inject=["$scope","$element"],e}();t.PeopleSearchMoreController=p;var m=function(){function e(){this.replace=!0,this.restrict="E",this.transclude=!0,this.require="^^"+d.directiveName,this.controller=p,this.template='\n <div class="ms-PeoplePicker-searchMore js-searchMore"\n ng-class="{\'ms-PeoplePicker-searchMore--disconnected\': disconnected}">\n <button type="button" ng-if="pickerType === \''+u[u.grouped]+'\' && !disconnected"\n ng-click="onSearch($event)" class="ms-PeoplePicker-searchMoreBtn">\n <div class="ms-PeoplePicker-searchMoreIcon">\n <uif-icon ng-if="!disconnected" uif-type="'+s.IconEnum[s.IconEnum.search]+'"></uif-icon>\n <uif-icon ng-if="disconnected" uif-type="'+s.IconEnum[s.IconEnum.alert]+'"></uif-icon>\n </div>\n <ng-transclude />\n </button>\n <div role="button" ng-if="pickerType === \''+u[u.compact]+'\' && !disconnected"\n ng-click="onSearch($event)" class="ms-PeoplePicker-searchMoreBtn ms-PeoplePicker-searchMoreBtn--compact">\n <div class="ms-PeoplePicker-searchMoreIcon">\n <uif-icon ng-if="!disconnected" uif-type="'+s.IconEnum[s.IconEnum.search]+'"></uif-icon>\n <uif-icon ng-if="disconnected" uif-type="'+s.IconEnum[s.IconEnum.alert]+'"></uif-icon>\n </div>\n <ng-transclude />\n </div>\n <div role="button" ng-if="pickerType === \''+u[u.facePile]+'\' && !disconnected"\n ng-click="onSearch($event)" class="ms-PeoplePicker-searchMoreBtn ms-PeoplePicker-searchMoreBtn--compact">\n <div class="ms-PeoplePicker-searchMoreIcon">\n <uif-icon ng-if="!disconnected" uif-type="'+s.IconEnum[s.IconEnum.search]+'"></uif-icon>\n <uif-icon ng-if="disconnected" uif-type="'+s.IconEnum[s.IconEnum.alert]+'"></uif-icon>\n </div>\n <ng-transclude />\n </div>\n <div role="button" ng-if="disconnected" class="ms-PeoplePicker-searchMoreBtn">\n <div class="ms-PeoplePicker-searchMoreIcon">\n <uif-icon uif-type="'+s.IconEnum[s.IconEnum.alert]+'"></uif-icon>\n </div>\n <ng-transclude />\n </div>\n <uif-spinner ng-show="processing"></uif-spinner>\n </div>',this.scope={disconnected:"=uifDisconnected"},this.link=function(e,t,i,n,r){e.pickerType=n.pickerType(),e.onSearch=function(t){t.stopPropagation(),n.search(),e.$broadcast(a,n.searchQuery())}}}return e.factory=function(){var t=function(){return new e};return t},e.directiveName="uifPeopleSearchMore",e}();t.PeopleSearchMoreDirective=m;var h=function(){function e(e){var t=this;this.$scope=e,this.$scope.$on(a,function(e,i){t.$scope.searchQuery=i})}return e.$inject=["$scope"],e}();t.PrimaryTextController=h;var v=function(){function e(){this.replace=!0,this.restrict="E",this.require=["^^"+m.directiveName,"^^"+d.directiveName],this.transclude=!0,this.controller=h,this.template='\n <div ng-show="!$parent.$parent.disconnected" class="ms-PeoplePicker-searchMorePrimary">\n <div ng-show="$parent.$parent.processing">{{searchingForText}} {{searchQuery}}</div>\n <ng-transclude ng-show="!$parent.$parent.processing"></ng-transclude>\n </div>',this.scope={searchingForText:"@?uifSearchForText"},this.link=function(e,t,i,n,r){e.searchingForText=e.searchingForText||"Searching for"}}return e.factory=function(){var t=function(){return new e};return t},e.directiveName="uifPrimaryText",e}();t.PrimaryTextDirective=v;var g=function(){function e(){this.replace=!0,this.restrict="E",this.transclude=!0,this.template='\n <div ng-show="!$parent.$parent.disconnected" class="ms-PeoplePicker-searchMoreSecondary">\n <ng-transclude></ng-transclude>\n </div>',this.scope=!0}return e.factory=function(){var t=function(){return new e};return t},e.directiveName="uifSecondaryText",e}();t.SecondaryTextDirective=g;var y=function(){function e(){this.replace=!0,this.restrict="E",this.transclude=!0,this.template='\n <div ng-show="$parent.$parent.disconnected" class="ms-PeoplePicker-searchMorePrimary">\n <ng-transclude></ng-transclude>\n </div>',this.scope=!0}return e.factory=function(){var t=function(){return new e};return t},e.directiveName="uifDisconnectedText",e}();t.DisconnectedTextDirective=y;var b=function(){function e(){this.replace=!0,this.restrict="E",this.transclude=!0,this.template='\n <div class="ms-PeoplePicker-selected" ng-class="{\'is-active\': selectedPeople && selectedPeople.length > 0}">\n <div class="ms-PeoplePicker-selectedHeader">\n <ng-transclude></ng-transclude>\n </div>\n <ul class="ms-PeoplePicker-selectedPeople">\n <li class="ms-PeoplePicker-selectedPerson" ng-repeat="person in selectedPeople track by $index">\n <uif-persona ng-click="onSelectedPersonClick()(person)"\n uif-style="'+r.PersonaStyleEnum[r.PersonaStyleEnum.round]+'"\n uif-size="'+o.PersonaSize[o.PersonaSize.small]+'"\n uif-presence="{{person.presence}}"\n uif-image-url="{{person.icon}}">\n <uif-persona-initials uif-color="{{person.color}}">{{person.initials}}</uif-persona-initials>\n <uif-persona-primary-text>{{person.primaryText}}</uif-persona-primary-text>\n <uif-persona-secondary-text>{{person.secondaryText}}</uif-persona-secondary-text>\n </uif-persona>\n <button type="button"\n ng-click="removePersonFromSelectedPeople()(person, $event)"\n class="ms-PeoplePicker-resultAction js-resultRemove">\n <uif-icon uif-type="'+s.IconEnum[s.IconEnum.x]+'"></uif-icon>\n </button>\n </li>\n </ul>\n </div>', this.scope={onSelectedPersonClick:"&?uifSelectedPersonClick",removePersonFromSelectedPeople:"&uifPersonClose",selectedPeople:"=ngModel"}}return e.factory=function(){var t=function(){return new e};return t},e.directiveName="uifPeoplePickerSelected",e}();t.PeoplePickerSelectedDirective=b;var P=function(){function e(){this.require="^^"+d.directiveName,this.replace=!0,this.restrict="E",this.transclude=!0,this.scope=!0,this.template='<span class="ms-PeoplePicker-selectedCount" ng-transclude></span>',this.link=function(e,t,i,n,r){e.selectedPersons=n.getSelectedPersons()}}return e.factory=function(){var t=function(){return new e};return t},e.directiveName="uifSelectedPeopleHeader",e}();t.SelectedPeopleHeaderDirective=P,t.module=n.module("officeuifabric.components.peoplepicker",["officeuifabric.components"]).directive(d.directiveName,d.factory()).directive(v.directiveName,v.factory()).directive(g.directiveName,g.factory()).directive(f.directiveName,f.factory()).directive(y.directiveName,y.factory()).directive(b.directiveName,b.factory()).directive(P.directiveName,P.factory()).directive(m.directiveName,m.factory())}])});
src/svg-icons/notification/confirmation-number.js
ngbrown/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationConfirmationNumber = (props) => ( <SvgIcon {...props}> <path d="M22 10V6c0-1.11-.9-2-2-2H4c-1.1 0-1.99.89-1.99 2v4c1.1 0 1.99.9 1.99 2s-.89 2-2 2v4c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2v-4c-1.1 0-2-.9-2-2s.9-2 2-2zm-9 7.5h-2v-2h2v2zm0-4.5h-2v-2h2v2zm0-4.5h-2v-2h2v2z"/> </SvgIcon> ); NotificationConfirmationNumber = pure(NotificationConfirmationNumber); NotificationConfirmationNumber.displayName = 'NotificationConfirmationNumber'; NotificationConfirmationNumber.muiName = 'SvgIcon'; export default NotificationConfirmationNumber;
demos/sliders/demos/disabled.js
isogon/styled-mdl-website
import React from 'react' import { Slider } from 'styled-mdl' const demo = () => <Slider min={0} max={100} defaultValue={60} disabled /> const caption = 'Disabled' const code = '<Slider min={0} max={100} defaultValue={60} disabled />' export default { demo, caption, code }
test/helpers/shallowRenderHelper.js
jiebianng/react-gallery
/** * Function to get the shallow output for a given component * As we are using phantom.js, we also need to include the fn.proto.bind shim! * * @see http://simonsmith.io/unit-testing-react-components-without-a-dom/ * @author somonsmith */ import React from 'react'; import TestUtils from 'react-addons-test-utils'; /** * Get the shallow rendered component * * @param {Object} component The component to return the output for * @param {Object} props [optional] The components properties * @param {Mixed} ...children [optional] List of children * @return {Object} Shallow rendered output */ export default function createComponent(component, props = {}, ...children) { const shallowRenderer = TestUtils.createRenderer(); shallowRenderer.render(React.createElement(component, props, children.length > 1 ? children : children[0])); return shallowRenderer.getRenderOutput(); }
Libraries/CustomComponents/ListView/ListView.js
ljhsai/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 ListView */ 'use strict'; var ListViewDataSource = require('ListViewDataSource'); var React = require('React'); var RCTUIManager = require('NativeModules').UIManager; var RCTScrollViewManager = require('NativeModules').ScrollViewManager; var ScrollView = require('ScrollView'); var ScrollResponder = require('ScrollResponder'); var StaticRenderer = require('StaticRenderer'); var TimerMixin = require('react-timer-mixin'); var isEmpty = require('isEmpty'); var logError = require('logError'); var merge = require('merge'); var PropTypes = React.PropTypes; var DEFAULT_PAGE_SIZE = 1; var DEFAULT_INITIAL_ROWS = 10; var DEFAULT_SCROLL_RENDER_AHEAD = 1000; var DEFAULT_END_REACHED_THRESHOLD = 1000; var DEFAULT_SCROLL_CALLBACK_THROTTLE = 50; var SCROLLVIEW_REF = 'listviewscroll'; /** * ListView - A core component designed for efficient display of vertically * scrolling lists of changing data. The minimal API is to create a * `ListView.DataSource`, populate it with a simple array of data blobs, and * instantiate a `ListView` component with that data source and a `renderRow` * callback which takes a blob from the data array and returns a renderable * component. * * Minimal example: * * ``` * getInitialState: function() { * var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); * return { * dataSource: ds.cloneWithRows(['row 1', 'row 2']), * }; * }, * * render: function() { * return ( * <ListView * dataSource={this.state.dataSource} * renderRow={(rowData) => <Text>{rowData}</Text>} * /> * ); * }, * ``` * * ListView also supports more advanced features, including sections with sticky * section headers, header and footer support, callbacks on reaching the end of * the available data (`onEndReached`) and on the set of rows that are visible * in the device viewport change (`onChangeVisibleRows`), and several * performance optimizations. * * There are a few performance operations designed to make ListView scroll * smoothly while dynamically loading potentially very large (or conceptually * infinite) data sets: * * * Only re-render changed rows - the rowHasChanged function provided to the * data source tells the ListView if it needs to re-render a row because the * source data has changed - see ListViewDataSource for more details. * * * Rate-limited row rendering - By default, only one row is rendered per * event-loop (customizable with the `pageSize` prop). This breaks up the * work into smaller chunks to reduce the chance of dropping frames while * rendering rows. */ var ListView = React.createClass({ mixins: [ScrollResponder.Mixin, TimerMixin], statics: { DataSource: ListViewDataSource, }, /** * You must provide a renderRow function. If you omit any of the other render * functions, ListView will simply skip rendering them. * * - renderRow(rowData, sectionID, rowID, highlightRow); * - renderSectionHeader(sectionData, sectionID); */ propTypes: { ...ScrollView.propTypes, dataSource: PropTypes.instanceOf(ListViewDataSource).isRequired, /** * (sectionID, rowID, adjacentRowHighlighted) => renderable * If provided, a renderable component to be rendered as the separator * below each row but not the last row if there is a section header below. * Take a sectionID and rowID of the row above and whether its adjacent row * is highlighted. */ renderSeparator: PropTypes.func, /** * (rowData, sectionID, rowID, highlightRow) => renderable * Takes a data entry from the data source and its ids and should return * a renderable component to be rendered as the row. By default the data * is exactly what was put into the data source, but it's also possible to * provide custom extractors. ListView can be notified when a row is * being highlighted by calling highlightRow function. The separators above and * below will be hidden when a row is highlighted. The highlighted state of * a row can be reset by calling highlightRow(null). */ renderRow: PropTypes.func.isRequired, /** * How many rows to render on initial component mount. Use this to make * it so that the first screen worth of data apears at one time instead of * over the course of multiple frames. */ initialListSize: PropTypes.number, /** * Called when all rows have been rendered and the list has been scrolled * to within onEndReachedThreshold of the bottom. The native scroll * event is provided. */ onEndReached: PropTypes.func, /** * Threshold in pixels for onEndReached. */ onEndReachedThreshold: PropTypes.number, /** * Number of rows to render per event loop. */ pageSize: PropTypes.number, /** * () => renderable * * The header and footer are always rendered (if these props are provided) * on every render pass. If they are expensive to re-render, wrap them * in StaticContainer or other mechanism as appropriate. Footer is always * at the bottom of the list, and header at the top, on every render pass. */ renderFooter: PropTypes.func, renderHeader: PropTypes.func, /** * (sectionData, sectionID) => renderable * * If provided, a sticky header is rendered for this section. The sticky * behavior means that it will scroll with the content at the top of the * section until it reaches the top of the screen, at which point it will * stick to the top until it is pushed off the screen by the next section * header. */ renderSectionHeader: PropTypes.func, /** * (props) => renderable * * A function that returns the scrollable component in which the list rows * are rendered. Defaults to returning a ScrollView with the given props. */ renderScrollComponent: React.PropTypes.func.isRequired, /** * How early to start rendering rows before they come on screen, in * pixels. */ scrollRenderAheadDistance: React.PropTypes.number, /** * (visibleRows, changedRows) => void * * Called when the set of visible rows changes. `visibleRows` maps * { sectionID: { rowID: true }} for all the visible rows, and * `changedRows` maps { sectionID: { rowID: true | false }} for the rows * that have changed their visibility, with true indicating visible, and * false indicating the view has moved out of view. */ onChangeVisibleRows: React.PropTypes.func, /** * An experimental performance optimization for improving scroll perf of * large lists, used in conjunction with overflow: 'hidden' on the row * containers. Use at your own risk. */ removeClippedSubviews: React.PropTypes.bool, }, /** * Exports some data, e.g. for perf investigations or analytics. */ getMetrics: function() { return { contentLength: this.scrollProperties.contentLength, totalRows: this.props.dataSource.getRowCount(), renderedRows: this.state.curRenderedRowsCount, visibleRows: Object.keys(this._visibleRows).length, }; }, /** * Provides a handle to the underlying scroll responder to support operations * such as scrollTo. */ getScrollResponder: function() { return this.refs[SCROLLVIEW_REF] && this.refs[SCROLLVIEW_REF].getScrollResponder && this.refs[SCROLLVIEW_REF].getScrollResponder(); }, setNativeProps: function(props) { this.refs[SCROLLVIEW_REF].setNativeProps(props); }, /** * React life cycle hooks. */ getDefaultProps: function() { return { initialListSize: DEFAULT_INITIAL_ROWS, pageSize: DEFAULT_PAGE_SIZE, renderScrollComponent: props => <ScrollView {...props} />, scrollRenderAheadDistance: DEFAULT_SCROLL_RENDER_AHEAD, onEndReachedThreshold: DEFAULT_END_REACHED_THRESHOLD, }; }, getInitialState: function() { return { curRenderedRowsCount: this.props.initialListSize, prevRenderedRowsCount: 0, highlightedRow: {}, }; }, getInnerViewNode: function() { return this.refs[SCROLLVIEW_REF].getInnerViewNode(); }, componentWillMount: function() { // this data should never trigger a render pass, so don't put in state this.scrollProperties = { visibleLength: null, contentLength: null, offset: 0 }; this._childFrames = []; this._visibleRows = {}; }, componentDidMount: function() { // do this in animation frame until componentDidMount actually runs after // the component is laid out this.requestAnimationFrame(() => { this._measureAndUpdateScrollProps(); }); }, componentWillReceiveProps: function(nextProps) { if (this.props.dataSource !== nextProps.dataSource) { this.setState((state, props) => { var rowsToRender = Math.min( state.curRenderedRowsCount + props.pageSize, props.dataSource.getRowCount() ); return { prevRenderedRowsCount: 0, curRenderedRowsCount: rowsToRender, }; }); } }, componentDidUpdate: function() { this.requestAnimationFrame(() => { this._measureAndUpdateScrollProps(); }); }, onRowHighlighted: function(sectionID, rowID) { this.setState({highlightedRow: {sectionID, rowID}}); }, render: function() { var bodyComponents = []; var dataSource = this.props.dataSource; var allRowIDs = dataSource.rowIdentities; var rowCount = 0; var sectionHeaderIndices = []; var header = this.props.renderHeader && this.props.renderHeader(); var footer = this.props.renderFooter && this.props.renderFooter(); var totalIndex = header ? 1 : 0; for (var sectionIdx = 0; sectionIdx < allRowIDs.length; sectionIdx++) { var sectionID = dataSource.sectionIdentities[sectionIdx]; var rowIDs = allRowIDs[sectionIdx]; if (rowIDs.length === 0) { continue; } if (this.props.renderSectionHeader) { var shouldUpdateHeader = rowCount >= this.state.prevRenderedRowsCount && dataSource.sectionHeaderShouldUpdate(sectionIdx); bodyComponents.push( <StaticRenderer key={'s_' + sectionID} shouldUpdate={!!shouldUpdateHeader} render={this.props.renderSectionHeader.bind( null, dataSource.getSectionHeaderData(sectionIdx), sectionID )} /> ); sectionHeaderIndices.push(totalIndex++); } for (var rowIdx = 0; rowIdx < rowIDs.length; rowIdx++) { var rowID = rowIDs[rowIdx]; var comboID = sectionID + rowID; var shouldUpdateRow = rowCount >= this.state.prevRenderedRowsCount && dataSource.rowShouldUpdate(sectionIdx, rowIdx); var row = <StaticRenderer key={'r_' + comboID} shouldUpdate={!!shouldUpdateRow} render={this.props.renderRow.bind( null, dataSource.getRowData(sectionIdx, rowIdx), sectionID, rowID, this.onRowHighlighted )} />; bodyComponents.push(row); totalIndex++; if (this.props.renderSeparator && (rowIdx !== rowIDs.length - 1 || sectionIdx === allRowIDs.length - 1)) { var adjacentRowHighlighted = this.state.highlightedRow.sectionID === sectionID && ( this.state.highlightedRow.rowID === rowID || this.state.highlightedRow.rowID === rowIDs[rowIdx + 1] ); var separator = this.props.renderSeparator( sectionID, rowID, adjacentRowHighlighted ); bodyComponents.push(separator); totalIndex++; } if (++rowCount === this.state.curRenderedRowsCount) { break; } } if (rowCount >= this.state.curRenderedRowsCount) { break; } } var { renderScrollComponent, ...props, } = this.props; if (!props.scrollEventThrottle) { props.scrollEventThrottle = DEFAULT_SCROLL_CALLBACK_THROTTLE; } Object.assign(props, { onScroll: this._onScroll, stickyHeaderIndices: sectionHeaderIndices, // Do not pass these events downstream to ScrollView since they will be // registered in ListView's own ScrollResponder.Mixin onKeyboardWillShow: undefined, onKeyboardWillHide: undefined, onKeyboardDidShow: undefined, onKeyboardDidHide: undefined, }); // TODO(ide): Use function refs so we can compose with the scroll // component's original ref instead of clobbering it return React.cloneElement(renderScrollComponent(props), { ref: SCROLLVIEW_REF, }, header, bodyComponents, footer); }, /** * Private methods */ _measureAndUpdateScrollProps: function() { var scrollComponent = this.getScrollResponder(); if (!scrollComponent || !scrollComponent.getInnerViewNode) { return; } RCTUIManager.measureLayout( scrollComponent.getInnerViewNode(), React.findNodeHandle(scrollComponent), logError, this._setScrollContentLength ); RCTUIManager.measureLayoutRelativeToParent( React.findNodeHandle(scrollComponent), logError, this._setScrollVisibleLength ); // RCTScrollViewManager.calculateChildFrames is not available on // every platform RCTScrollViewManager && RCTScrollViewManager.calculateChildFrames && RCTScrollViewManager.calculateChildFrames( React.findNodeHandle(scrollComponent), this._updateChildFrames, ); }, _setScrollContentLength: function(left, top, width, height) { this.scrollProperties.contentLength = !this.props.horizontal ? height : width; }, _setScrollVisibleLength: function(left, top, width, height) { this.scrollProperties.visibleLength = !this.props.horizontal ? height : width; this._updateVisibleRows(); this._renderMoreRowsIfNeeded(); }, _updateChildFrames: function(childFrames) { this._updateVisibleRows(childFrames); }, _renderMoreRowsIfNeeded: function() { if (this.scrollProperties.contentLength === null || this.scrollProperties.visibleLength === null || this.state.curRenderedRowsCount === this.props.dataSource.getRowCount()) { return; } var distanceFromEnd = this._getDistanceFromEnd(this.scrollProperties); if (distanceFromEnd < this.props.scrollRenderAheadDistance) { this._pageInNewRows(); } }, _pageInNewRows: function() { this.setState((state, props) => { var rowsToRender = Math.min( state.curRenderedRowsCount + props.pageSize, props.dataSource.getRowCount() ); return { prevRenderedRowsCount: state.curRenderedRowsCount, curRenderedRowsCount: rowsToRender }; }, () => { this._measureAndUpdateScrollProps(); this.setState(state => ({ prevRenderedRowsCount: state.curRenderedRowsCount, })); }); }, _getDistanceFromEnd: function(scrollProperties) { return scrollProperties.contentLength - scrollProperties.visibleLength - scrollProperties.offset; }, _updateVisibleRows: function(updatedFrames) { if (!this.props.onChangeVisibleRows) { return; // No need to compute visible rows if there is no callback } if (updatedFrames) { updatedFrames.forEach((newFrame) => { this._childFrames[newFrame.index] = merge(newFrame); }); } var isVertical = !this.props.horizontal; var dataSource = this.props.dataSource; var visibleMin = this.scrollProperties.offset; var visibleMax = visibleMin + this.scrollProperties.visibleLength; var allRowIDs = dataSource.rowIdentities; var header = this.props.renderHeader && this.props.renderHeader(); var totalIndex = header ? 1 : 0; var visibilityChanged = false; var changedRows = {}; for (var sectionIdx = 0; sectionIdx < allRowIDs.length; sectionIdx++) { var rowIDs = allRowIDs[sectionIdx]; if (rowIDs.length === 0) { continue; } var sectionID = dataSource.sectionIdentities[sectionIdx]; if (this.props.renderSectionHeader) { totalIndex++; } var visibleSection = this._visibleRows[sectionID]; if (!visibleSection) { visibleSection = {}; } for (var rowIdx = 0; rowIdx < rowIDs.length; rowIdx++) { var rowID = rowIDs[rowIdx]; var frame = this._childFrames[totalIndex]; totalIndex++; if (!frame) { break; } var rowVisible = visibleSection[rowID]; var min = isVertical ? frame.y : frame.x; var max = min + (isVertical ? frame.height : frame.width); if (min > visibleMax || max < visibleMin) { if (rowVisible) { visibilityChanged = true; delete visibleSection[rowID]; if (!changedRows[sectionID]) { changedRows[sectionID] = {}; } changedRows[sectionID][rowID] = false; } } else if (!rowVisible) { visibilityChanged = true; visibleSection[rowID] = true; if (!changedRows[sectionID]) { changedRows[sectionID] = {}; } changedRows[sectionID][rowID] = true; } } if (!isEmpty(visibleSection)) { this._visibleRows[sectionID] = visibleSection; } else if (this._visibleRows[sectionID]) { delete this._visibleRows[sectionID]; } } visibilityChanged && this.props.onChangeVisibleRows(this._visibleRows, changedRows); }, _onScroll: function(e) { var isVertical = !this.props.horizontal; this.scrollProperties.visibleLength = e.nativeEvent.layoutMeasurement[ isVertical ? 'height' : 'width' ]; this.scrollProperties.contentLength = e.nativeEvent.contentSize[ isVertical ? 'height' : 'width' ]; this.scrollProperties.offset = e.nativeEvent.contentOffset[ isVertical ? 'y' : 'x' ]; this._updateVisibleRows(e.nativeEvent.updatedChildFrames); var nearEnd = this._getDistanceFromEnd(this.scrollProperties) < this.props.onEndReachedThreshold; if (nearEnd && this.props.onEndReached && this.scrollProperties.contentLength !== this._sentEndForContentLength && this.state.curRenderedRowsCount === this.props.dataSource.getRowCount()) { this._sentEndForContentLength = this.scrollProperties.contentLength; this.props.onEndReached(e); } else { this._renderMoreRowsIfNeeded(); } this.props.onScroll && this.props.onScroll(e); }, }); module.exports = ListView;
client/analytics/components/partials/indicators/AssetStatusHistoryBar/AssetStatusHistoryBar.js
Haaarp/geo
import React from 'react'; import Label from 'konux/common/components/Label'; import FormWrap from 'konux/common/components/FormWrap'; import Title from 'konux/common/components/Title'; import StatusListContainer from './StatusListContainer'; import { translate } from 'react-i18next'; class AssetStatusHistoryBar extends React.Component { render() { let {t} = this.props; return ( <FormWrap className="full-width"> <FormWrap className="full-width status-history"> <Title> <Label className="lbl-4">{t('status history')}</Label> </Title> </FormWrap> <StatusListContainer data={this.props.data} healthStatuses={this.props.healthStatuses} /> </FormWrap> ); } } export default translate(['common'])(AssetStatusHistoryBar);
src/pages/plugins.js
getinsomnia/website
import React from 'react'; import { graphql } from 'gatsby'; import InfiniteScroll from 'react-infinite-scroll-component'; import Plugin from '../lib/plugin'; import SocialCards from '../components/social-cards'; import iconPluginDefault from '../assets/icons/plugins-default-icon.svg'; function Header() { // We use function-style for SocialCards to avoid recursive deep-equals check issue // https://github.com/nfl/react-helmet/issues/373 return ( <React.Fragment> {SocialCards({ key: 'plugin-hub', title: 'Plugin Hub', summary: 'Discover and install Insomnia plugins' })} <header className="plugins-header text-center"> <div className="row"> <div className="col-12"> <h1>Plugin Hub</h1> <p>Extend Insomnia with Powerful Plugins</p> <p className="text-sm"> <PluginDocsLink /> </p> </div> </div> </header> </React.Fragment> ); } function Loader() { return ( <div style={{ textAlign: 'center' }} className="container mt-5"> <div className="row"> <div className="col-12"> <h4>Loading...</h4> </div> </div> </div> ); } function NoMoreResults(numResults) { return ( <div style={{ textAlign: 'center' }} className="container mt-5"> <div className="row"> <div className="col-12"> <p> {numResults ? "No more results. Don't see your plugin?" : 'No matches found'} <br /> <a href="https://support.insomnia.rest/article/26-plugins"> Create a Plugin </a> </p> </div> </div> </div> ); } function PluginBox(pkg, period, sortBy, sortOrder) { let plugin = new Plugin(pkg); return ( <div className="plugin-wrapper d-flex" key={pkg.name + sortBy + sortOrder}> <div className="plugin w-100"> <div className="plugin-header d-flex w-100"> <div className="plugin-logo"> <img src={plugin.icon || iconPluginDefault} className="icon" alt="Logo" /> </div> <div className="plugin-name"> <a href={plugin.hubLink}>{plugin.displayName}</a> </div> <div className="plugin-info"> <span className="plugin-author">{plugin.authorName}</span> </div> </div> <p className="plugin-content d-block text-overflow text-small text-secondary" title={plugin.description}> {plugin.description} </p> <div className="plugin-footer d-flex text-small text-secondary"> <div className="plugin-version pr-3 pl-3 pt-2 pb-2" title="Plugin Version"> <i className="las la-code-branch" /> {plugin.version} </div> <div className="plugin-downloads pr-3 pl-3 pt-2 pb-2" title="Plugin Downloads"> <i className="las la-download" /> {plugin.downloads(period)} </div> </div> </div> </div> ); } function PluginDocsLink() { return ( <a href="https://support.insomnia.rest/article/26-plugins" className="create-plugin-link"> Interested in making your own? <span className="emoji-swap default" role="img" aria-label="smirk"> 😏 </span> <span className="emoji-swap on-hover" role="img" aria-label="heart eyes"> 😍 </span> </a> ); } function PluginSearchInput({ onChange }) { return ( <div class="plugins-search"> <input className="br-3 d-block pr-2 pt-2 pb-2" placeholder="Search Insomnia plugins..." onChange={onChange} /> <span class="icon"> <i class="la la-search" /> </span> </div> ); } function PluginOrderByDropdown({ onChange, defaultValue }) { return ( <label className="mr-3"> Order{' '} <select onChange={onChange} defaultValue={defaultValue === -1 ? 'asc' : 'desc'}> <option value="asc">Asc</option> <option value="desc">Desc</option> </select> </label> ); } function PluginSortByDropdown({ onChange, defaultValue, options }) { return ( <label> Sort By{' '} <select onChange={onChange} defaultValue={defaultValue}> {Object.keys(options).map((value, index) => { return ( <option value={value} key={value}> {options[value]} </option> ); })} </select> </label> ); } function Plugins( plugins, { sortOptions, sortBy, sortOrder, hasMore, onNext, onSearch, onSort, onOrderChange } ) { return ( <div className="plugins"> <div className="container fluid"> <div className="row"> <div className="col-6"> <PluginSearchInput onChange={onSearch} /> </div> <div className="col-6 pt-2"> <div className="action-bar flex justify-end text-right text-xs"> <PluginOrderByDropdown onChange={onOrderChange} defaultValue={sortOrder} /> <PluginSortByDropdown onChange={onSort} defaultValue={sortBy} options={sortOptions} /> </div> </div> </div> <div className="row"> <div className="col-12"> <InfiniteScroll dataLength={plugins.length} next={onNext} hasMore={hasMore} hasChildren={plugins.length > 0} loader={Loader()} endMessage={NoMoreResults(plugins.length)}> {plugins.map(plugin => PluginBox(plugin, 'lastYear', sortBy, sortOrder) )} </InfiniteScroll> </div> </div> </div> </div> ); } export default class Component extends React.Component { constructor() { super(); this.plugins = []; this.state = { plugins: [], total: 0, offset: 0, sortOrder: 1, sortBy: 'downloadsLastYear', sortOptions: { downloadsLastYear: 'Downloads', name: 'Name', releaseDate: 'Release Date' }, trendingBy: 'lastWeek', hasMore: true, perScroll: 25 }; } componentDidMount() { const { allNpmPackage: { edges } } = this.props.data; this.plugins = edges.map(({ node: plugin }) => plugin); this.setState({ total: this.plugins.length, hasMore: this.plugins.length > 0 }); this.sort(); this.loadMore(); } reset() { this.setState({ plugins: [], offset: 0, hasMore: false }); } search(evt) { let query = evt.target.value; if (!query) { this.reset(); setTimeout(() => { this.loadMore(); }, 1); return; } query = query.toLowerCase(); this.setState({ offset: 0, hasMore: false, plugins: this.plugins.filter(plugin => { return new Plugin(plugin).displayName.toLowerCase().indexOf(query) > -1; }) }); } sortByName() { this.plugins = this.plugins.sort((a, b) => { let an = new Plugin(a).displayName; let bn = new Plugin(b).displayName; return -an.localeCompare(bn); }); } sortByReleaseDate() { this.plugins = this.plugins.sort((a, b) => { let x = new Date(a.npm.released); let y = new Date(b.npm.released); if (this.sortOrder === 1) { return x - y; } else { return y - x; } }); } sortByDownloads(period) { this.plugins = this.plugins.sort((a, b) => { if (a.downloads[period] < b.downloads[period]) { return 1; } else if (a.downloads[period] > b.downloads[period]) { return -1; } else { return 0; } }); } sort() { const { sortBy, sortOrder } = this.state; switch (sortBy) { case 'downloadsLastYear': this.sortByDownloads('lastYear'); break; case 'name': this.sortByName(); break; case 'releaseDate': this.sortByReleaseDate(); break; } if (sortOrder === -1) { this.plugins = this.plugins.reverse(); } } loadMore() { let { offset, plugins, perScroll, loading } = this.state; let nextOffset = offset + perScroll; let nextSet = this.plugins.slice(offset, nextOffset); if (loading) return; this.setState({ loading: true }); setTimeout(() => { this.setState({ plugins: plugins.concat(nextSet), offset: nextOffset, hasMore: this.state.total > nextOffset, loading: false }); }, Math.random() * 100); } onSort({ target: { value } }) { this.setState({ sortBy: value }); this.reset(); setTimeout(() => { this.sort(); setTimeout(() => this.loadMore(), 20); }, 1); } onOrderChange({ target: { value } }) { let order = value === 'asc' ? -1 : 1; this.setState({ sortOrder: order }); this.reset(); setTimeout(() => { this.sort(); this.loadMore(); }, 20); } render() { return ( <React.Fragment> {Header()} {Plugins(this.state.plugins, { sortOptions: this.state.sortOptions, sortBy: this.state.sortBy, sortOrder: this.state.sortOrder, hasMore: this.state.hasMore, onNext: this.loadMore.bind(this), onSearch: this.search.bind(this), onSort: this.onSort.bind(this), onOrderChange: this.onOrderChange.bind(this) })} </React.Fragment> ); } } export const pageQuery = graphql` query myQuery { allNpmPackage( filter: { meta: { unlisted: { eq: false }, core: { eq: false } } } ) { edges { node { name downloads { lastYear lastMonth lastWeek lastDay } meta { name displayName description bundle unlisted deprecated categories publisher { name icon } applications { cli core designer } images { icon cover } } npm { description version released author { name } publisher { name } readme } } } } } `;
packages/material-ui-icons/src/Looks5Rounded.js
Kagami/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-5 6h-3v2h2c1.1 0 2 .9 2 2v2c0 1.11-.9 2-2 2h-3c-.55 0-1-.45-1-1s.45-1 1-1h3v-2h-3c-.55 0-1-.45-1-1V8c0-.55.45-1 1-1h4c.55 0 1 .45 1 1s-.45 1-1 1z" /></g></React.Fragment> , 'Looks5Rounded');
examples/star-wars/js/app.js
almasakchabayev/relay
/** * This file provided by Facebook is 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 NONINFRINGEMENT. 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. */ import 'babel/polyfill'; import React from 'react'; import ReactDOM from 'react-dom'; import Relay from 'react-relay'; import StarWarsApp from './components/StarWarsApp'; import StarWarsAppHomeRoute from './routes/StarWarsAppHomeRoute'; ReactDOM.render( <Relay.RootContainer Component={StarWarsApp} route={new StarWarsAppHomeRoute({ factionNames: ['empire', 'rebels'] })} />, document.getElementById('root') );
src/parser/deathknight/blood/modules/features/DeathStrikeTiming.js
sMteX/WoWAnalyzer
import React from 'react'; import SelfHealTimingGraph from 'parser/shared/modules/features/SelfHealTimingGraph'; import SPELLS from 'common/SPELLS'; class DeathStrikeTiming extends SelfHealTimingGraph { constructor(...args) { super(...args); this.selfHealSpell = SPELLS.DEATH_STRIKE_HEAL; this.tabTitle = "Death Strike Timing"; this.tabURL = "death-strike-timings"; } render() { return ( <SelfHealTimingGraph /> ); } } export default DeathStrikeTiming;
packages/views/shared/components/Errors/NotFound/index.js
isbasex/blog-engine
import React from 'react' import { Route } from 'react-router-dom' const Status = ({ code, children }) => ( <Route render={({ staticContext }) => { if (staticContext) staticContext.status = code return children }} /> ) const NotFound = () => ( <Status code={404}> <div className="main-container">Not Found</div> </Status> ) export default NotFound
src/Songrow.js
rweekers/voornameninliedjes-frontend
import React, { Component } from 'react'; import { Link } from "react-router-dom"; import './Songrow.css'; class Songrow extends Component { render() { const song = this.props; return ( <div className="Songrow"> <Link to={'/song/' + song.id}><p>{song.artist} - {song.title}</p></Link>{' '} </div> ); } } export default Songrow;
src/index.js
TodayTix/tt-react-calendar
import React from 'react'; import PropTypes from 'prop-types'; import _ from 'lodash'; import fp from 'lodash/fp'; import moment from 'moment'; import { day as dayType } from './proptypes'; import CalendarDayHeaders from './day-headers'; import CalendarMonth from './month'; /** * Turns a moment instance into a serialized string that's unique for a month * and the object's locale's first day of the week. This ensures that the range * of months only regenerates if the locale changes, or different months are * passed in for the start and end dates, maximizing efficiency for re-renders. * @param {moment} day * @return {string} */ const monthKey = (day) => `${day.localeData().firstDayOfWeek()}${day.format('YYYYMMZZ')}`; /** * Takes two inclusive endpoints and returns an array of moment objects for the * first of each month between those endpoints. * @param {moment} firstDay * @param {moment} lastDay * @return {Array.<moment>} */ const getMonthsInRange = _.memoize( _.flow( // Wrap in an array to more easily have multiple values flow through these // functions. (firstDay, lastDay) => [firstDay, lastDay], // Move both days to the start of their months so the math is more // consistent. fp.map(day => day.clone().startOf('month')), // Actually generate the moment objects for each month. ([firstDay, lastDay]) => _.times( lastDay.diff(firstDay, 'months') + 1, (n) => firstDay.clone().add(n, 'months') ) ), // memoize key function (firstDay, lastDay) => `${monthKey(firstDay)}-${monthKey(lastDay)}` ); const DayHeaderStyles = { AboveFirstMonth: 'above-first', InEveryMonth: 'in-every', InFirstMonth: 'in-first', }; export default function Calendar(props) { const { className, compactMonths, dayAbbrevs, dayHeaderClassName, dayHeaderStyle, firstRenderedDay, gutterWidth, lastRenderedDay, monthClassName, monthHeaderClassName, monthHeaderFormat, renderDay, renderMonthHeader, weekClassName, } = props; const firstDay = moment(firstRenderedDay); const lastDay = moment(lastRenderedDay); const months = (compactMonths ? [firstDay] : getMonthsInRange(firstDay, lastDay) ); const firstWeekday = firstDay.localeData().firstDayOfWeek(); return ( <div className={className}> { dayHeaderStyle === DayHeaderStyles.AboveFirstMonth ? <CalendarDayHeaders className={dayHeaderClassName} dayAbbrevs={dayAbbrevs} firstWeekday={firstWeekday} gutterWidth={gutterWidth} /> : null } {months.map((firstOfMonth, idx) => ( <CalendarMonth className={monthClassName} dayAbbrevs={dayAbbrevs} dayHeaderClassName={dayHeaderClassName} firstDay={moment.max( firstOfMonth, firstDay )} firstWeekday={firstWeekday} gutterWidth={gutterWidth} headerClassName={monthHeaderClassName} headerInsideDay={compactMonths} headerFormat={monthHeaderFormat} includeDayHeaders={ dayHeaderStyle === DayHeaderStyles.InEveryMonth || (dayHeaderStyle === DayHeaderStyles.InFirstMonth && idx === 0) } key={firstOfMonth.format('YYYYMM')} lastDay={compactMonths ? lastDay : moment.min( firstOfMonth.clone().endOf('month'), lastDay ) } renderDay={renderDay} renderHeader={renderMonthHeader} weekClassName={weekClassName} /> ))} </div> ); } Calendar.propTypes = { className: PropTypes.string, compactMonths: PropTypes.bool.isRequired, // Array of 7 strings to use as column headers for days. Start with Sunday. dayAbbrevs: PropTypes.arrayOf(PropTypes.string).isRequired, dayHeaderClassName: PropTypes.string, dayHeaderStyle: PropTypes.oneOf(_.values(DayHeaderStyles)), firstRenderedDay: dayType.isRequired, gutterWidth: PropTypes.string, lastRenderedDay: dayType.isRequired, monthClassName: PropTypes.string, monthHeaderClassName: PropTypes.string, monthHeaderFormat: PropTypes.string, // Function that takes a moment instance and returns a single ReactElement. renderDay: PropTypes.func.isRequired, renderMonthHeader: PropTypes.func.isRequired, weekClassName: PropTypes.string, }; Calendar.defaultProps = { compactMonths: false, dayAbbrevs: ['Su', 'M', 'T', 'W', 'Th', 'F', 'Sa'], dayHeaderStyle: DayHeaderStyles.InFirstMonth, monthHeaderFormat: 'MMMM YYYY', renderDay: (day) => <div>{day.format('YYYY-MM-DD')}</div>, renderMonthHeader: (day, format) => day.format(format), }; Calendar.DayHeaderStyles = DayHeaderStyles;
app/javascript/mastodon/components/display_name.js
ebihara99999/mastodon
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import escapeTextContentForBrowser from 'escape-html'; import emojify from '../emoji'; class DisplayName extends React.PureComponent { static propTypes = { account: ImmutablePropTypes.map.isRequired, }; render () { const displayName = this.props.account.get('display_name').length === 0 ? this.props.account.get('username') : this.props.account.get('display_name'); const displayNameHTML = { __html: emojify(escapeTextContentForBrowser(displayName)) }; return ( <span className='display-name'> <strong className='display-name__html' dangerouslySetInnerHTML={displayNameHTML} /> <span className='display-name__account'>@{this.props.account.get('acct')}</span> </span> ); } } export default DisplayName;
mlflow/server/js/src/model-registry/components/CompareModelVersionsPage.js
mlflow/mlflow
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import qs from 'qs'; import { connect } from 'react-redux'; import { getRunApi } from '../../experiment-tracking/actions'; import { getUUID } from '../../common/utils/ActionUtils'; import { getRegisteredModelApi, getModelVersionApi, getModelVersionArtifactApi, parseMlModelFile, } from '../actions'; import RequestStateWrapper from '../../common/components/RequestStateWrapper'; import { CompareModelVersionsView } from './CompareModelVersionsView'; import _ from 'lodash'; import { PageContainer } from '../../common/components/PageContainer'; // TODO: Write integration tests for this component export class CompareModelVersionsPageImpl extends Component { static propTypes = { modelName: PropTypes.string.isRequired, versionsToRuns: PropTypes.object.isRequired, getRunApi: PropTypes.func.isRequired, getRegisteredModelApi: PropTypes.func.isRequired, getModelVersionApi: PropTypes.func.isRequired, getModelVersionArtifactApi: PropTypes.func.isRequired, parseMlModelFile: PropTypes.func.isRequired, }; registeredModelRequestId = getUUID(); versionRequestId = getUUID(); runRequestId = getUUID(); getMlModelFileRequestId = getUUID(); state = { requestIds: [ // requests that must be fulfilled before rendering this.registeredModelRequestId, this.runRequestId, this.versionRequestId, this.getMlModelFileRequestId, ], requestIdsWith404ErrorsToIgnore: [this.runRequestId, this.getMlModelFileRequestId], }; removeRunRequestId() { this.setState((prevState) => ({ requestIds: _.without(prevState.requestIds, this.runRequestId), })); } componentDidMount() { this.props.getRegisteredModelApi(this.props.modelName, this.registeredModelRequestId); for (const modelVersion in this.props.versionsToRuns) { if ({}.hasOwnProperty.call(this.props.versionsToRuns, modelVersion)) { const runID = this.props.versionsToRuns[modelVersion]; if (runID) { this.props.getRunApi(runID, this.runRequestId).catch(() => { // Failure of this call should not block the page. Here we remove // `runRequestId` from `requestIds` to unblock RequestStateWrapper // from rendering its content this.removeRunRequestId(); }); } else { this.removeRunRequestId(); } const { modelName } = this.props; this.props.getModelVersionApi(modelName, modelVersion, this.versionRequestId); this.props .getModelVersionArtifactApi(modelName, modelVersion) .then((content) => this.props.parseMlModelFile( modelName, modelVersion, content.value, this.getMlModelFileRequestId, ), ) .catch(() => { // Failure of this call chain should not block the page. Here we remove // `getMlModelFileRequestId` from `requestIds` to unblock RequestStateWrapper // from rendering its content this.setState((prevState) => ({ requestIds: _.without(prevState.requestIds, this.getMlModelFileRequestId), })); }); } } } render() { return ( <PageContainer> <RequestStateWrapper requestIds={this.state.requestIds} requestIdsWith404sToIgnore={this.state.requestIdsWith404ErrorsToIgnore} > <CompareModelVersionsView modelName={this.props.modelName} versionsToRuns={this.props.versionsToRuns} /> </RequestStateWrapper> </PageContainer> ); } } const mapStateToProps = (state, ownProps) => { const { location } = ownProps; const searchValues = qs.parse(location.search); const modelName = decodeURIComponent(JSON.parse(searchValues['?name'])); const versionsToRuns = JSON.parse(searchValues['runs']); return { modelName, versionsToRuns }; }; const mapDispatchToProps = { getRunApi, getRegisteredModelApi, getModelVersionApi, getModelVersionArtifactApi, parseMlModelFile, }; export const CompareModelVersionsPage = connect( mapStateToProps, mapDispatchToProps, )(CompareModelVersionsPageImpl);
jest-preprocessor.js
hirokai/MicroManagerViewer
var ReactTools = require('react-tools'); module.exports = { process: function(src) { return ReactTools.transform(src,{harmony:true}); } };
src/components/receiptUpload/ReceiptUpload.js
lukebelliveau/aclu-matchers
import React from 'react'; import ACLUCloudWok from './ACLUCloudwok'; import Instructions from './Instructions'; export default () => ( <div> <Instructions/> <ACLUCloudWok /> </div> );
ajax/libs/forerunnerdb/1.3.773/fdb-legacy.js
him2him2/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 {Object} data The data / document to use for lookups. * @param {Object} options An options object. * @param {Operation} op An optional operation instance. Pass undefined * if not being used. * @param {Array=} resultArr The results passed between recursive calls. * Do not pass anything into this argument when calling externally. * @returns {*|Array} */ BinaryTree.prototype.lookup = function (data, options, op, resultArr) { var result = this._compareFunc(this._data, data); resultArr = resultArr || []; if (result === 0) { if (this._left) { this._left.lookup(data, options, op, resultArr); } resultArr.push(this._data); if (this._right) { this._right.lookup(data, options, op, resultArr); } } if (result === -1) { if (this._right) { this._right.lookup(data, options, op, resultArr); } } if (result === 1) { if (this._left) { this._left.lookup(data, options, op, resultArr); } } return resultArr; }; /** * Returns the entire binary tree ordered. * @param {String} type * @param resultArr * @returns {*|Array} */ BinaryTree.prototype.inOrder = function (type, resultArr) { resultArr = resultArr || []; if (this._left) { this._left.inOrder(type, resultArr); } switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } if (this._right) { this._right.inOrder(type, resultArr); } return resultArr; }; /** * Searches the binary tree for all matching documents based on the regular * expression passed. * @param path * @param val * @param regex * @param {Array=} resultArr The results passed between recursive calls. * Do not pass anything into this argument when calling externally. * @returns {*|Array} */ BinaryTree.prototype.startsWith = function (path, val, regex, resultArr) { var reTest, thisDataPathVal = sharedPathSolver.get(this._data, path), thisDataPathValSubStr = thisDataPathVal.substr(0, val.length), result; //regex = regex || new RegExp('^' + val); resultArr = resultArr || []; if (resultArr._visitedCount === undefined) { resultArr._visitedCount = 0; } resultArr._visitedCount++; resultArr._visitedNodes = resultArr._visitedNodes || []; resultArr._visitedNodes.push(thisDataPathVal); result = this.sortAsc(thisDataPathValSubStr, val); reTest = thisDataPathValSubStr === val; if (result === 0) { if (this._left) { this._left.startsWith(path, val, regex, resultArr); } if (reTest) { resultArr.push(this._data); } if (this._right) { this._right.startsWith(path, val, regex, resultArr); } } if (result === -1) { if (reTest) { resultArr.push(this._data); } if (this._right) { this._right.startsWith(path, val, regex, resultArr); } } if (result === 1) { if (this._left) { this._left.startsWith(path, val, regex, resultArr); } if (reTest) { resultArr.push(this._data); } } return resultArr; }; /*BinaryTree.prototype.find = function (type, search, resultArr) { resultArr = resultArr || []; if (this._left) { this._left.find(type, search, resultArr); } // Check if this node's data is greater or less than the from value var fromResult = this.sortAsc(this._data[key], from), toResult = this.sortAsc(this._data[key], to); if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) { // This data node is greater than or equal to the from value, // and less than or equal to the to value so include it switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } } if (this._right) { this._right.find(type, search, resultArr); } return resultArr; };*/ /** * * @param {String} type * @param {String} key The data key / path to range search against. * @param {Number} from Range search from this value (inclusive) * @param {Number} to Range search to this value (inclusive) * @param {Array=} resultArr Leave undefined when calling (internal use), * passes the result array between recursive calls to be returned when * the recursion chain completes. * @param {Path=} pathResolver Leave undefined when calling (internal use), * caches the path resolver instance for performance. * @returns {Array} Array of matching document objects */ BinaryTree.prototype.findRange = function (type, key, from, to, resultArr, pathResolver) { resultArr = resultArr || []; pathResolver = pathResolver || new Path(key); if (this._left) { this._left.findRange(type, key, from, to, resultArr, pathResolver); } // Check if this node's data is greater or less than the from value var pathVal = pathResolver.value(this._data), fromResult = this.sortAsc(pathVal, from), toResult = this.sortAsc(pathVal, to); if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) { // This data node is greater than or equal to the from value, // and less than or equal to the to value so include it switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } } if (this._right) { this._right.findRange(type, key, from, to, resultArr, pathResolver); } return resultArr; }; /*BinaryTree.prototype.findRegExp = function (type, key, pattern, resultArr) { resultArr = resultArr || []; if (this._left) { this._left.findRegExp(type, key, pattern, resultArr); } // Check if this node's data is greater or less than the from value var fromResult = this.sortAsc(this._data[key], from), toResult = this.sortAsc(this._data[key], to); if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) { // This data node is greater than or equal to the from value, // and less than or equal to the to value so include it switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } } if (this._right) { this._right.findRegExp(type, key, pattern, resultArr); } return resultArr; };*/ /** * Determines if the passed query and options object will be served * by this index successfully or not and gives a score so that the * DB search system can determine how useful this index is in comparison * to other indexes on the same collection. * @param query * @param queryOptions * @param matchOptions * @returns {{matchedKeys: Array, totalKeyCount: Number, score: number}} */ BinaryTree.prototype.match = function (query, queryOptions, matchOptions) { // Check if the passed query has data in the keys our index // operates on and if so, is the query sort matching our order var indexKeyArr, queryArr, matchedKeys = [], matchedKeyCount = 0, i; indexKeyArr = sharedPathSolver.parseArr(this._index, { verbose: true }); queryArr = sharedPathSolver.parseArr(query, matchOptions && matchOptions.pathOptions ? matchOptions.pathOptions : { ignore:/\$/, verbose: true }); // Loop the query array and check the order of keys against the // index key array to see if this index can be used for (i = 0; i < indexKeyArr.length; i++) { if (queryArr[i] === indexKeyArr[i]) { matchedKeyCount++; matchedKeys.push(queryArr[i]); } } return { matchedKeys: matchedKeys, totalKeyCount: queryArr.length, score: matchedKeyCount }; //return sharedPathSolver.countObjectPaths(this._keys, query); }; Shared.finishModule('BinaryTree'); module.exports = BinaryTree; },{"./Path":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. * @param {Object=} val The data to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'metaData'); /** * Gets / sets boolean to determine if the collection should be * capped or not. * @param {Boolean=} val The value to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'capped'); /** * Gets / sets capped collection size. This is the maximum number * of records that the capped collection will store. * @param {Number=} val The value to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'cappedSize'); /** * Adds a job id to the async queue to signal to other parts * of the application that some async work is currently being * done. * @param {String} key The id of the async job. * @private */ Collection.prototype._asyncPending = function (key) { this._deferQueue.async.push(key); }; /** * Removes a job id from the async queue to signal to other * parts of the application that some async work has been * completed. If no further async jobs exist on the queue then * the "ready" event is emitted from this collection instance. * @param {String} key The id of the async job. * @private */ Collection.prototype._asyncComplete = function (key) { // Remove async flag for this type var index = this._deferQueue.async.indexOf(key); while (index > -1) { this._deferQueue.async.splice(index, 1); index = this._deferQueue.async.indexOf(key); } if (this._deferQueue.async.length === 0) { this.deferEmit('ready'); } }; /** * Get the data array that represents the collection's data. * This data is returned by reference and should not be altered outside * of the provided CRUD functionality of the collection as doing so * may cause unstable index behaviour within the collection. * @returns {Array} */ Collection.prototype.data = function () { return this._data; }; /** * Drops a collection and all it's stored data from the database. * @param {Function=} callback A callback method to call once the * operation has completed. * @returns {boolean} True on success, false on failure. */ Collection.prototype.drop = function (callback) { var key; if (!this.isDropped()) { if (this._db && this._db._collection && this._name) { if (this.debug()) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; this.emit('drop', this); delete this._db._collection[this._name]; // Remove any reactor IO chain links if (this._collate) { for (key in this._collate) { if (this._collate.hasOwnProperty(key)) { this.collateRemove(key); } } } delete this._primaryKey; delete this._primaryIndex; delete this._primaryCrc; delete this._crcLookup; delete this._data; delete this._metrics; delete this._listeners; if (callback) { callback.call(this, false, true); } return true; } } else { if (callback) { callback.call(this, false, true); } return true; } if (callback) { callback.call(this, false, true); } return false; }; /** * Gets / sets the primary key for this collection. * @param {String=} keyName The name of the primary key. * @returns {*} */ Collection.prototype.primaryKey = function (keyName) { if (keyName !== undefined) { if (this._primaryKey !== keyName) { var oldKey = this._primaryKey; this._primaryKey = keyName; // Set the primary key index primary key this._primaryIndex.primaryKey(keyName); // Rebuild the primary key index this.rebuildPrimaryKeyIndex(); // Propagate change down the chain this.chainSend('primaryKey', { keyName: keyName, oldData: oldKey }); } return this; } return this._primaryKey; }; /** * Handles insert events and routes changes to binds and views as required. * @param {Array} inserted An array of inserted documents. * @param {Array} failed An array of documents that failed to insert. * @private */ Collection.prototype._onInsert = function (inserted, failed) { this.emit('insert', inserted, failed); }; /** * Handles update events and routes changes to binds and views as required. * @param {Array} items An array of updated documents. * @private */ Collection.prototype._onUpdate = function (items) { this.emit('update', items); }; /** * Handles remove events and routes changes to binds and views as required. * @param {Array} items An array of removed documents. * @private */ Collection.prototype._onRemove = function (items) { this.emit('remove', items); }; /** * Handles any change to the collection by updating the * lastChange timestamp on the collection's metaData. This * only happens if the changeTimestamp option is enabled * on the collection (it is disabled by default). * @private */ Collection.prototype._onChange = function () { if (this._options.changeTimestamp) { // Record the last change timestamp this._metaData.lastChange = this.serialiser.convert(new Date()); } }; /** * Gets / sets the db instance this class instance belongs to. * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(Collection.prototype, 'db', function (db) { if (db) { if (this.primaryKey() === '_id') { // Set primary key to the db's key by default this.primaryKey(db.primaryKey()); // Apply the same debug settings this.debug(db.debug()); } } return this.$super.apply(this, arguments); }); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Collection.prototype, 'mongoEmulation'); Collection.prototype.setData = new Overload('Collection.prototype.setData', { /** * Sets the collection's data to the array / documents passed. If any * data already exists in the collection it will be removed before the * new data is set via the remove() method, and the remove event will * fire as well. * @name setData * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. */ '*': function (data) { return this.$main.call(this, data, {}); }, /** * Sets the collection's data to the array / documents passed. If any * data already exists in the collection it will be removed before the * new data is set via the remove() method, and the remove event will * fire as well. * @name setData * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. * @param {Object} options Optional options object. */ '*, object': function (data, options) { return this.$main.call(this, data, options); }, /** * Sets the collection's data to the array / documents passed. If any * data already exists in the collection it will be removed before the * new data is set via the remove() method, and the remove event will * fire as well. * @name setData * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. * @param {Function} callback Optional callback function. */ '*, function': function (data, callback) { return this.$main.call(this, data, {}, callback); }, /** * Sets the collection's data to the array / documents passed. If any * data already exists in the collection it will be removed before the * new data is set via the remove() method, and the remove event will * fire as well. * @name setData * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. * @param {*} options Optional options object. * @param {Function} callback Optional callback function. */ '*, *, function': function (data, options, callback) { return this.$main.call(this, data, options, callback); }, /** * Sets the collection's data to the array / documents passed. If any * data already exists in the collection it will be removed before the * new data is set via the remove() method, and the remove event will * fire as well. * @name setData * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. * @param {*} options Optional options object. * @param {*} callback Optional callback function. */ '*, *, *': function (data, options, callback) { return this.$main.call(this, data, options, callback); }, /** * Sets the collection's data to the array / documents passed. If any * data already exists in the collection it will be removed before the * new data is set via the remove() method, and the remove event will * fire as well. * @name setData * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. * @param {Object} options Optional options object. * @param {Function} callback Optional callback function. */ '$main': function (data, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (data) { var deferredSetting = this.deferredCalls(), oldData = [].concat(this._data); // Switch off deferred calls since setData should be // a synchronous call this.deferredCalls(false); options = this.options(options); if (options.$decouple) { data = this.decouple(data); } if (!(data instanceof Array)) { data = [data]; } // Remove all items from the collection this.remove({}); // Insert the new data this.insert(data); // Switch deferred calls back to previous settings this.deferredCalls(deferredSetting); this._onChange(); this.emit('setData', this._data, oldData); } if (callback) { callback.call(this); } return this; } }); /** * Drops and rebuilds the primary key index for all documents * in the collection. * @param {Object=} options An optional options object. * @private */ Collection.prototype.rebuildPrimaryKeyIndex = function (options) { options = options || { $ensureKeys: undefined, $violationCheck: undefined }; var ensureKeys = options && options.$ensureKeys !== undefined ? options.$ensureKeys : true, violationCheck = options && options.$violationCheck !== undefined ? options.$violationCheck : true, arr, arrCount, arrItem, pIndex = this._primaryIndex, crcIndex = this._primaryCrc, crcLookup = this._crcLookup, pKey = this._primaryKey, jString; // Drop the existing primary index pIndex.truncate(); crcIndex.truncate(); crcLookup.truncate(); // Loop the data and check for a primary key in each object arr = this._data; arrCount = arr.length; while (arrCount--) { arrItem = arr[arrCount]; if (ensureKeys) { // Make sure the item has a primary key this.ensurePrimaryKey(arrItem); } if (violationCheck) { // Check for primary key violation if (!pIndex.uniqueSet(arrItem[pKey], arrItem)) { // Primary key violation throw(this.logIdentifier() + ' Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: ' + arrItem[this._primaryKey]); } } else { pIndex.set(arrItem[pKey], arrItem); } // Generate a hash string jString = this.hash(arrItem); crcIndex.set(arrItem[pKey], jString); crcLookup.set(jString, arrItem); } }; /** * Checks for a primary key on the document and assigns one if none * currently exists. * @param {Object} obj The object to check a primary key against. * @private */ Collection.prototype.ensurePrimaryKey = function (obj) { if (obj[this._primaryKey] === undefined) { // Assign a primary key automatically obj[this._primaryKey] = this.objectId(); } }; /** * Clears all data from the collection. * @returns {Collection} */ Collection.prototype.truncate = function () { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // TODO: This should use remove so that chain reactor events are properly // TODO: handled, but ensure that chunking is switched off this.emit('truncate', this._data); // Clear all the data from the collection this._data.length = 0; // Re-create the primary index data this._primaryIndex = new KeyValueStore('primary'); this._primaryCrc = new KeyValueStore('primaryCrc'); this._crcLookup = new KeyValueStore('crcLookup'); this._onChange(); this.emit('immediateChange', {type: 'truncate'}); this.deferEmit('change', {type: 'truncate'}); return this; }; /** * Inserts a new document or updates an existing document in a * collection depending on if a matching primary key exists in * the collection already or not. * * If the document contains a primary key field (based on the * collections's primary key) then the database will search for * an existing document with a matching id. If a matching * document is found, the document will be updated. Any keys that * match keys on the existing document will be overwritten with * new data. Any keys that do not currently exist on the document * will be added to the document. * * If the document does not contain an id or the id passed does * not match an existing document, an insert is performed instead. * If no id is present a new primary key id is provided for the * document and the document is inserted. * * @param {Object} obj The document object to upsert or an array * containing documents to upsert. * @param {Function=} callback Optional callback method. * @returns {Object} An object containing two keys, "op" contains * either "insert" or "update" depending on the type of operation * that was performed and "result" contains the return data from * the operation used. */ Collection.prototype.upsert = function (obj, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (obj) { var queue = this._deferQueue.upsert, deferThreshold = this._deferThreshold.upsert, returnData = {}, query, i; // Determine if the object passed is an array or not if (obj instanceof Array) { if (this._deferredCalls && obj.length > deferThreshold) { // Break up upsert into blocks this._deferQueue.upsert = queue.concat(obj); this._asyncPending('upsert'); // Fire off the insert queue handler this.processQueue('upsert', callback); return {}; } else { // Loop the array and upsert each item returnData = []; for (i = 0; i < obj.length; i++) { returnData.push(this.upsert(obj[i])); } if (callback) { callback.call(this); } return returnData; } } // Determine if the operation is an insert or an update if (obj[this._primaryKey]) { // Check if an object with this primary key already exists query = {}; query[this._primaryKey] = obj[this._primaryKey]; if (this._primaryIndex.lookup(query)[0]) { // The document already exists with this id, this operation is an update returnData.op = 'update'; } else { // No document with this id exists, this operation is an insert returnData.op = 'insert'; } } else { // The document passed does not contain an id, this operation is an insert returnData.op = 'insert'; } switch (returnData.op) { case 'insert': returnData.result = this.insert(obj, callback); break; case 'update': returnData.result = this.update(query, obj, {}, callback); break; default: break; } return returnData; } else { if (callback) { callback.call(this); } } return {}; }; /** * Executes a method against each document that matches query and returns an * array of documents that may have been modified by the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the results. * @param {Object=} options Optional options object. * @returns {Array} */ Collection.prototype.filter = function (query, func, options) { return (this.find(query, options)).filter(func); }; /** * Executes a method against each document that matches query and then executes * an update based on the return data of the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the update. * @param {Object=} options Optional options object passed to the initial find call. * @returns {Array} */ Collection.prototype.filterUpdate = function (query, func, options) { var items = this.find(query, options), results = [], singleItem, singleQuery, singleUpdate, pk = this.primaryKey(), i; for (i = 0; i < items.length; i++) { singleItem = items[i]; singleUpdate = func(singleItem); if (singleUpdate) { singleQuery = {}; singleQuery[pk] = singleItem[pk]; results.push(this.update(singleQuery, singleUpdate)); } } return results; }; /** * Modifies an existing document or documents in a collection. * This will update all matches for 'query' with the data held * in 'update'. It will not overwrite the matched documents * with the update document. * * @param {Object} query The query that must be matched for a * document to be operated on. * @param {Object} update The object containing updated * key/values. Any keys that match keys on the existing document * will be overwritten with this data. Any keys that do not * currently exist on the document will be added to the document. * @param {Object=} options An options object. * @param {Function=} callback The callback method to call when * the update is complete. * @returns {Array} The items that were updated. */ Collection.prototype.update = function (query, update, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); this.convertToFdb(update); } else { // Decouple the update data update = this.decouple(update); } // Handle transform update = this.transformIn(update); return this._handleUpdate(query, update, options, callback); }; /** * Handles the update operation that was initiated by a call to update(). * @param {Object} query The query that must be matched for a * document to be operated on. * @param {Object} update The object containing updated * key/values. Any keys that match keys on the existing document * will be overwritten with this data. Any keys that do not * currently exist on the document will be added to the document. * @param {Object=} options An options object. * @param {Function=} callback The callback method to call when * the update is complete. * @returns {Array} The items that were updated. * @private */ Collection.prototype._handleUpdate = function (query, update, options, callback) { var self = this, op = this._metrics.create('update'), dataSet, updated, updateCall = function (referencedDoc) { var oldDoc = self.decouple(referencedDoc), newDoc, triggerOperation, result; if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) { newDoc = self.decouple(referencedDoc); triggerOperation = { type: 'update', query: self.decouple(query), update: self.decouple(update), options: self.decouple(options), op: op }; // Update newDoc with the update criteria so we know what the data will look // like AFTER the update is processed result = self.updateObject(newDoc, triggerOperation.update, triggerOperation.query, triggerOperation.options, ''); if (self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_BEFORE, referencedDoc, newDoc) !== false) { // No triggers complained so let's execute the replacement of the existing // object with the new one 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. It does this by removing existing keys * from the base object and then adding the passed object's keys to * the existing base object, thereby maintaining any references to * the existing base object but effectively replacing the object with * the new one. * @param {Object} currentObj The base object to alter. * @param {Object} newObj The new object to overwrite the existing one * with. * @returns {*} Chain. * @private */ Collection.prototype._replaceObj = function (currentObj, newObj) { var i; // Check if the new document has a different primary key value from the existing one // Remove item from indexes this._removeFromIndexes(currentObj); // Remove existing keys from current object for (i in currentObj) { if (currentObj.hasOwnProperty(i)) { delete currentObj[i]; } } // Add new keys to current object for (i in newObj) { if (newObj.hasOwnProperty(i)) { currentObj[i] = newObj[i]; } } // Update the item in the primary index if (!this._insertIntoIndexes(currentObj)) { throw(this.logIdentifier() + ' Primary key violation in update! Key violated: ' + currentObj[this._primaryKey]); } // Update the object in the collection data //this._data.splice(this._data.indexOf(currentObj), 1, newObj); return this; }; /** * Helper method to update a document via it's id. * @param {String} id The id of the document. * @param {Object} update The object containing the key/values to * update to. * @returns {Object} The document that was updated or undefined * if no document was updated. */ Collection.prototype.updateById = function (id, update) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.update(searchObj, update)[0]; }; /** * Internal method for document updating. * @param {Object} doc The document to update. * @param {Object} update The object with key/value pairs to update * the document with. * @param {Object} query The query object that we need to match to * perform an update. * @param {Object} options An options object. * @param {String} path The current recursive path. * @param {String} opType The type of update operation to perform, * if none is specified default is to set new data against matching * fields. * @returns {Boolean} True if the document was updated with new / * changed data or false if it was not updated because the data was * the same. * @private */ Collection.prototype.updateObject = function (doc, update, query, options, path, opType) { // TODO: This method is long, try to break it into smaller pieces update = this.decouple(update); // Clear leading dots from path path = path || ''; if (path.substr(0, 1) === '.') { path = path.substr(1, path.length -1); } //var oldDoc = this.decouple(doc), var updated = false, recurseUpdated = false, operation, tmpArray, tmpIndex, tmpCount, tempIndex, tempKey, replaceObj, pk, pathInstance, sourceIsArray, updateIsArray, i; // 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 {Collection~insertCallback=} callback Optional callback called * once the insert is complete. */ Collection.prototype.insert = function (data, index, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (typeof(index) === 'function') { callback = index; index = this._data.length; } else if (index === undefined) { index = this._data.length; } data = this.transformIn(data); return this._insertHandle(data, index, callback); }; /** * The insert operation's callback. * @callback Collection~insertCallback * @param {Object} result The result object will contain two arrays (inserted * and failed) which represent the documents that did get inserted and those * that didn't for some reason (usually index violation). Failed items also * contain a reason. Inspect the failed array for further information. * * A third field called "deferred" is a boolean value to indicate if the * insert operation was deferred across more than one CPU cycle (to avoid * blocking the main thread). */ /** * Inserts a document or array of documents into the collection. * @param {Object|Array} data Either a document object or array of document * @param {Number=} index Optional index to insert the record at. * @param {Collection~insertCallback=} callback Optional callback called * once the insert is complete. */ Collection.prototype._insertHandle = function (data, index, callback) { var //self = this, queue = this._deferQueue.insert, deferThreshold = this._deferThreshold.insert, //deferTime = this._deferTime.insert, inserted = [], failed = [], insertResult, resultObj, i; if (data instanceof Array) { // Check if there are more insert items than the insert defer // threshold, if so, break up inserts so we don't tie up the // ui or thread if (this._deferredCalls && data.length > deferThreshold) { // Break up insert into blocks this._deferQueue.insert = queue.concat(data); this._asyncPending('insert'); // Fire off the insert queue handler this.processQueue('insert', callback); return; } else { // Loop the array and add items for (i = 0; i < data.length; i++) { insertResult = this._insert(data[i], index + i); if (insertResult === true) { inserted.push(data[i]); } else { failed.push({ doc: data[i], reason: insertResult }); } } } } else { // Store the data item insertResult = this._insert(data, index); if (insertResult === true) { inserted.push(data); } else { failed.push({ doc: data, reason: insertResult }); } } resultObj = { deferred: false, inserted: inserted, failed: failed }; this._onInsert(inserted, failed); if (callback) { callback.call(this, resultObj); } this._onChange(); this.emit('immediateChange', {type: 'insert', data: inserted}); 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 {String} search The string to search for. Case sensitive. * @param {Object=} options A standard find() options object. * @returns {Array} An array of documents that matched the search string. */ Collection.prototype.peek = function (search, options) { // Loop all items var arr = this._data, arrCount = arr.length, arrIndex, arrItem, tempColl = new Collection(), typeOfSearch = typeof search; if (typeOfSearch === 'string') { for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { // Get json representation of object arrItem = this.jStringify(arr[arrIndex]); // Check if string exists in object json if (arrItem.indexOf(search) > -1) { // Add this item to the temp collection tempColl.insert(arr[arrIndex]); } } return tempColl.find({}, options); } else { return this.find(search, options); } }; /** * Provides a query plan / operations log for a query. * @param {Object} query The query to execute. * @param {Object=} options Optional options object. * @returns {Object} The query plan. */ Collection.prototype.explain = function (query, options) { var result = this.find(query, options); return result.__fdbOp._data; }; /** * Generates an options object with default values or adds default * values to a passed object if those values are not currently set * to anything. * @param {object=} obj Optional options object to modify. * @returns {object} The options object. */ Collection.prototype.options = function (obj) { obj = obj || {}; obj.$decouple = obj.$decouple !== undefined ? obj.$decouple : true; obj.$explain = obj.$explain !== undefined ? obj.$explain : false; return obj; }; /** * Queries the collection based on the query object passed. * @param {Object} query The query key/values that a document must match in * order for it to be returned in the result array. * @param {Object=} options An optional options object. * @param {Function=} callback !! DO NOT USE, THIS IS NON-OPERATIONAL !! * Optional callback. If specified the find process * will not return a value and will assume that you wish to operate under an * async mode. This will break up large find requests into smaller chunks and * process them in a non-blocking fashion allowing large datasets to be queried * without causing the browser UI to pause. Results from this type of operation * will be passed back to the callback once completed. * * @returns {Array} The results array from the find operation, containing all * documents that matched the query. */ Collection.prototype.find = function (query, options, callback) { // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); } if (callback) { // Check the size of the collection's data array // Split operation into smaller tasks and callback when complete callback.call(this, 'Callbacks for the find() operation are not yet implemented!', []); return []; } return this._find.call(this, query, options, callback); }; Collection.prototype._find = function (query, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // TODO: This method is quite long, break into smaller pieces query = query || {}; var op = this._metrics.create('find'), pk = this.primaryKey(), self = this, analysis, scanLength, requiresTableScan = true, resultArr, joinIndex, joinSource = {}, joinQuery, joinPath, joinSourceKey, joinSourceType, joinSourceIdentifier, joinSourceData, resultRemove = [], i, j, k, fieldListOn = [], fieldListOff = [], elemMatchPathSolver, elemMatchSubArr, elemMatchSpliceArr, matcherTmpOptions = {}, result, cursor = {}, pathSolver, waterfallCollection, matcher; if (!(options instanceof Array)) { options = this.options(options); } matcher = function (doc) { return self._match(doc, query, options, 'and', matcherTmpOptions); }; op.start(); if (query) { // Check if the query is an array (multi-operation waterfall query) if (query instanceof Array) { waterfallCollection = this; // Loop the query operations for (i = 0; i < query.length; i++) { // Execute each operation and pass the result into the next // query operation waterfallCollection = waterfallCollection.subset(query[i], options && options[i] ? options[i] : {}); } return waterfallCollection.find(); } // Pre-process any data-changing query operators first if (query.$findSub) { // Check we have all the parts we need if (!query.$findSub.$path) { throw('$findSub missing $path property!'); } return this.findSub( query.$findSub.$query, query.$findSub.$path, query.$findSub.$subQuery, query.$findSub.$subOptions ); } if (query.$findSubOne) { // Check we have all the parts we need if (!query.$findSubOne.$path) { throw('$findSubOne missing $path property!'); } return this.findSubOne( query.$findSubOne.$query, query.$findSubOne.$path, query.$findSubOne.$subQuery, query.$findSubOne.$subOptions ); } // Get query analysis to execute best optimised code path op.time('analyseQuery'); analysis = this._analyseQuery(self.decouple(query), options, op); op.time('analyseQuery'); op.data('analysis', analysis); // Check if the query tries to limit by data that would only exist after // the join operation has been completed if (analysis.hasJoin && analysis.queriesJoin) { // The query has a join and tries to limit by it's joined data // Get references to the join sources op.time('joinReferences'); for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) { joinSourceData = analysis.joinsOn[joinIndex]; joinSourceKey = joinSourceData.key; joinSourceType = joinSourceData.type; joinSourceIdentifier = joinSourceData.id; joinPath = new Path(analysis.joinQueries[joinSourceKey]); joinQuery = joinPath.value(query)[0]; joinSource[joinSourceIdentifier] = this._db[joinSourceType](joinSourceKey).subset(joinQuery); // Remove join clause from main query delete query[analysis.joinQueries[joinSourceKey]]; } op.time('joinReferences'); } // Check if an index lookup can be used to return this result if (analysis.indexMatch.length && (!options || (options && !options.$skipIndex))) { op.data('index.potential', analysis.indexMatch); op.data('index.used', analysis.indexMatch[0].index); // Get the data from the index op.time('indexLookup'); resultArr = analysis.indexMatch[0].lookup || []; op.time('indexLookup'); // Check if the index coverage is all keys, if not we still need to table scan it if (analysis.indexMatch[0].keyData.totalKeyCount === analysis.indexMatch[0].keyData.score) { // Don't require a table scan to find relevant documents requiresTableScan = false; } } else { op.flag('usedIndex', false); } if (requiresTableScan) { if (resultArr && resultArr.length) { scanLength = resultArr.length; op.time('tableScan: ' + scanLength); // Filter the source data and return the result resultArr = resultArr.filter(matcher); } else { // Filter the source data and return the result scanLength = this._data.length; op.time('tableScan: ' + scanLength); resultArr = this._data.filter(matcher); } op.time('tableScan: ' + scanLength); } // Order the array if we were passed a sort clause if (options.$orderBy) { op.time('sort'); resultArr = this.sort(options.$orderBy, resultArr); op.time('sort'); } if (options.$page !== undefined && options.$limit !== undefined) { // Record paging data cursor.page = options.$page; cursor.pages = Math.ceil(resultArr.length / options.$limit); cursor.records = resultArr.length; // Check if we actually need to apply the paging logic if (options.$page && options.$limit > 0) { op.data('cursor', cursor); // Skip to the page specified based on limit resultArr.splice(0, options.$page * options.$limit); } } if (options.$skip) { cursor.skip = options.$skip; // Skip past the number of records specified resultArr.splice(0, options.$skip); op.data('skip', options.$skip); } if (options.$limit && resultArr && resultArr.length > options.$limit) { cursor.limit = options.$limit; resultArr.length = options.$limit; op.data('limit', options.$limit); } if (options.$decouple) { // Now decouple the data from the original objects op.time('decouple'); resultArr = this.decouple(resultArr); op.time('decouple'); op.data('flag.decouple', true); } // Now process any joins on the final data if (options.$join) { resultRemove = resultRemove.concat(this.applyJoin(resultArr, options.$join, joinSource)); op.data('flag.join', true); } // Process removal queue if (resultRemove.length) { op.time('removalQueue'); this.spliceArrayByIndexList(resultArr, resultRemove); op.time('removalQueue'); } if (options.$transform) { op.time('transform'); for (i = 0; i < resultArr.length; i++) { resultArr.splice(i, 1, options.$transform(resultArr[i])); } op.time('transform'); op.data('flag.transform', true); } // Process transforms if (this._transformEnabled && this._transformOut) { op.time('transformOut'); resultArr = this.transformOut(resultArr); op.time('transformOut'); } op.data('results', resultArr.length); } else { resultArr = []; } // Check for an $as operator in the options object and if it exists // iterate over the fields and generate a rename function that will // operate over the entire returned data array and rename each object's // fields to their new names // TODO: Enable $as in collection find to allow renaming fields /*if (options.$as) { renameFieldPath = new Path(); renameFieldMethod = function (obj, oldFieldPath, newFieldName) { renameFieldPath.path(oldFieldPath); renameFieldPath.rename(newFieldName); }; for (i in options.$as) { if (options.$as.hasOwnProperty(i)) { } } }*/ if (!options.$aggregate) { // Generate a list of fields to limit data by // Each property starts off being enabled by default (= 1) then // if any property is explicitly specified as 1 then all switch to // zero except _id. // // Any that are explicitly set to zero are switched off. op.time('scanFields'); for (i in options) { if (options.hasOwnProperty(i) && i.indexOf('$') !== 0) { if (options[i] === 1) { fieldListOn.push(i); } else if (options[i] === 0) { fieldListOff.push(i); } } } op.time('scanFields'); // Limit returned fields by the options data if (fieldListOn.length || fieldListOff.length) { op.data('flag.limitFields', true); op.data('limitFields.on', fieldListOn); op.data('limitFields.off', fieldListOff); op.time('limitFields'); // We have explicit fields switched on or off for (i = 0; i < resultArr.length; i++) { result = resultArr[i]; for (j in result) { if (result.hasOwnProperty(j)) { if (fieldListOn.length) { // We have explicit fields switched on so remove all fields // that are not explicitly switched on // Check if the field name is not the primary key if (j !== pk) { if (fieldListOn.indexOf(j) === -1) { // This field is not in the on list, remove it delete result[j]; } } } if (fieldListOff.length) { // We have explicit fields switched off so remove fields // that are explicitly switched off if (fieldListOff.indexOf(j) > -1) { // This field is in the off list, remove it delete result[j]; } } } } } op.time('limitFields'); } // Now run any projections on the data required if (options.$elemMatch) { op.data('flag.elemMatch', true); op.time('projection-elemMatch'); for (i in options.$elemMatch) { if (options.$elemMatch.hasOwnProperty(i)) { elemMatchPathSolver = new Path(i); // Loop the results array for (j = 0; j < resultArr.length; j++) { elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0]; // Check we have a sub-array to loop if (elemMatchSubArr && elemMatchSubArr.length) { // Loop the sub-array and check for projection query matches for (k = 0; k < elemMatchSubArr.length; k++) { // Check if the current item in the sub-array matches the projection query if (self._match(elemMatchSubArr[k], options.$elemMatch[i], options, '', {})) { // The item matches the projection query so set the sub-array // to an array that ONLY contains the matching item and then // exit the loop since we only want to match the first item elemMatchPathSolver.set(resultArr[j], i, [elemMatchSubArr[k]]); break; } } } } } } op.time('projection-elemMatch'); } if (options.$elemsMatch) { op.data('flag.elemsMatch', true); op.time('projection-elemsMatch'); for (i in options.$elemsMatch) { if (options.$elemsMatch.hasOwnProperty(i)) { elemMatchPathSolver = new Path(i); // Loop the results array for (j = 0; j < resultArr.length; j++) { elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0]; // Check we have a sub-array to loop if (elemMatchSubArr && elemMatchSubArr.length) { elemMatchSpliceArr = []; // Loop the sub-array and check for projection query matches for (k = 0; k < elemMatchSubArr.length; k++) { // Check if the current item in the sub-array matches the projection query if (self._match(elemMatchSubArr[k], options.$elemsMatch[i], options, '', {})) { // The item matches the projection query so add it to the final array elemMatchSpliceArr.push(elemMatchSubArr[k]); } } // Now set the final sub-array to the matched items elemMatchPathSolver.set(resultArr[j], i, elemMatchSpliceArr); } } } } op.time('projection-elemsMatch'); } } // Process aggregation if (options.$aggregate) { op.data('flag.aggregate', true); op.time('aggregate'); pathSolver = new Path(options.$aggregate); resultArr = pathSolver.value(resultArr); op.time('aggregate'); } // Now process any $groupBy clause if (options.$groupBy) { op.data('flag.group', true); op.time('group'); resultArr = this.group(options.$groupBy, resultArr); op.time('group'); } op.stop(); resultArr.__fdbOp = op; resultArr.$cursor = cursor; return resultArr; }; /** * Returns one document that satisfies the specified query criteria. If multiple * documents satisfy the query, this method returns the first document to match * the query. * @returns {*} */ Collection.prototype.findOne = function () { return (this.find.apply(this, arguments))[0]; }; /** * Gets the index in the collection data array of the first item matched by * the passed query object. * @param {Object} query The query to run to find the item to return the index of. * @param {Object=} options An options object. * @returns {Number} */ Collection.prototype.indexOf = function (query, options) { var item = this.find(query, {$decouple: false})[0], sortedData; if (item) { if (!options || options && !options.$orderBy) { // Basic lookup from order of insert return this._data.indexOf(item); } else { // Trying to locate index based on query with sort order options.$decouple = false; sortedData = this.find(query, options); return sortedData.indexOf(item); } } return -1; }; /** * Returns the index of the document identified by the passed item's primary key. * @param {*} itemLookup The document whose primary key should be used to lookup * or the id to lookup. * @param {Object=} options An options object. * @returns {Number} The index the item with the matching primary key is occupying. */ Collection.prototype.indexOfDocById = function (itemLookup, options) { var item, sortedData; if (typeof itemLookup !== 'object') { item = this._primaryIndex.get(itemLookup); } else { item = this._primaryIndex.get(itemLookup[this._primaryKey]); } if (item) { if (!options || options && !options.$orderBy) { // Basic lookup return this._data.indexOf(item); } else { // Sorted lookup options.$decouple = false; sortedData = this.find({}, options); return sortedData.indexOf(item); } } return -1; }; /** * Removes a document from the collection by it's index in the collection's * data array. * @param {Number} index The index of the document to remove. * @returns {Object} The document that has been removed or false if none was * removed. */ Collection.prototype.removeByIndex = function (index) { var doc, docId; doc = this._data[index]; if (doc !== undefined) { doc = this.decouple(doc); docId = doc[this.primaryKey()]; return this.removeById(docId); } return false; }; /** * Gets / sets the collection transform options. * @param {Object} obj A collection transform options object. * @returns {*} */ Collection.prototype.transform = function (obj) { if (obj !== undefined) { if (typeof obj === "object") { if (obj.enabled !== undefined) { this._transformEnabled = obj.enabled; } if (obj.dataIn !== undefined) { this._transformIn = obj.dataIn; } if (obj.dataOut !== undefined) { this._transformOut = obj.dataOut; } } else { this._transformEnabled = obj !== false; } return this; } return { enabled: this._transformEnabled, dataIn: this._transformIn, dataOut: this._transformOut }; }; /** * Transforms data using the set transformIn method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformIn = function (data) { if (this._transformEnabled && this._transformIn) { if (data instanceof Array) { var finalArr = [], transformResult, i; for (i = 0; i < data.length; i++) { transformResult = this._transformIn(data[i]); // Support transforms returning multiple items if (transformResult instanceof Array) { finalArr = finalArr.concat(transformResult); } else { finalArr.push(transformResult); } } return finalArr; } else { return this._transformIn(data); } } return data; }; /** * Transforms data using the set transformOut method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformOut = function (data) { if (this._transformEnabled && this._transformOut) { if (data instanceof Array) { var finalArr = [], transformResult, i; for (i = 0; i < data.length; i++) { transformResult = this._transformOut(data[i]); // Support transforms returning multiple items if (transformResult instanceof Array) { finalArr = finalArr.concat(transformResult); } else { finalArr.push(transformResult); } } return finalArr; } else { return this._transformOut(data); } } return data; }; /** * Sorts an array of documents by the given sort path. * @param {*} sortObj The keys and orders the array objects should be sorted by. * @param {Array} arr The array of documents to sort. * @returns {Array} */ Collection.prototype.sort = function (sortObj, arr) { // Convert the index object to an array of key val objects var self = this, keys = sharedPathSolver.parse(sortObj, true); if (keys.length) { // Execute sort arr.sort(function (a, b) { // Loop the index array var i, indexData, result = 0; for (i = 0; i < keys.length; i++) { indexData = keys[i]; if (indexData.value === 1) { result = self.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } else if (indexData.value === -1) { result = self.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } if (result !== 0) { return result; } } return result; }); } return arr; }; /** * Groups an array of documents into multiple array fields, named by the value * of the given group path. * @param {*} groupObj The key path the array objects should be grouped by. * @param {Array} arr The array of documents to group. * @returns {Object} */ Collection.prototype.group = function (groupObj, arr) { // Convert the index object to an array of key val objects var keys = sharedPathSolver.parse(groupObj, true), groupPathSolver = new Path(), groupValue, groupResult = {}, keyIndex, i; if (keys.length) { for (keyIndex = 0; keyIndex < keys.length; keyIndex++) { groupPathSolver.path(keys[keyIndex].path); // Execute group for (i = 0; i < arr.length; i++) { groupValue = groupPathSolver.get(arr[i]); groupResult[groupValue] = groupResult[groupValue] || []; groupResult[groupValue].push(arr[i]); } } } return groupResult; }; // Commented as we have a new method that was originally implemented for binary trees. // This old method actually has problems with nested sort objects /*Collection.prototype.sortold = function (sortObj, arr) { // Make sure we have an array object arr = arr || []; var sortArr = [], sortKey, sortSingleObj; for (sortKey in sortObj) { if (sortObj.hasOwnProperty(sortKey)) { sortSingleObj = {}; sortSingleObj[sortKey] = sortObj[sortKey]; sortSingleObj.___fdbKey = String(sortKey); sortArr.push(sortSingleObj); } } if (sortArr.length < 2) { // There is only one sort criteria, do a simple sort and return it return this._sort(sortObj, arr); } else { return this._bucketSort(sortArr, arr); } };*/ /** * REMOVED AS SUPERCEDED BY BETTER SORT SYSTEMS * Takes array of sort paths and sorts them into buckets before returning final * array fully sorted by multi-keys. * @param keyArr * @param arr * @returns {*} * @private */ /*Collection.prototype._bucketSort = function (keyArr, arr) { var keyObj = keyArr.shift(), arrCopy, bucketData, bucketOrder, bucketKey, buckets, i, finalArr = []; if (keyArr.length > 0) { // Sort array by bucket key arr = this._sort(keyObj, arr); // Split items into buckets bucketData = this.bucket(keyObj.___fdbKey, arr); bucketOrder = bucketData.order; buckets = bucketData.buckets; // Loop buckets and sort contents for (i = 0; i < bucketOrder.length; i++) { bucketKey = bucketOrder[i]; arrCopy = [].concat(keyArr); finalArr = finalArr.concat(this._bucketSort(arrCopy, buckets[bucketKey])); } return finalArr; } else { return this._sort(keyObj, arr); } };*/ /** * Takes an array of objects and returns a new object with the array items * split into buckets by the passed key. * @param {String} key The key to split the array into buckets by. * @param {Array} arr An array of objects. * @returns {Object} */ /*Collection.prototype.bucket = function (key, arr) { var i, oldField, field, fieldArr = [], buckets = {}; for (i = 0; i < arr.length; i++) { field = String(arr[i][key]); if (oldField !== field) { fieldArr.push(field); oldField = field; } buckets[field] = buckets[field] || []; buckets[field].push(arr[i]); } return { buckets: buckets, order: fieldArr }; };*/ /** * Sorts array by individual sort path. * @param {String} key The path to sort by. * @param {Array} arr The array of objects to sort. * @returns {Array|*} * @private */ Collection.prototype._sort = function (key, arr) { var self = this, sorterMethod, pathSolver = new Path(), dataPath = pathSolver.parse(key, true)[0]; pathSolver.path(dataPath.path); if (dataPath.value === 1) { // Sort ascending sorterMethod = function (a, b) { var valA = pathSolver.value(a)[0], valB = pathSolver.value(b)[0]; return self.sortAsc(valA, valB); }; } else if (dataPath.value === -1) { // Sort descending sorterMethod = function (a, b) { var valA = pathSolver.value(a)[0], valB = pathSolver.value(b)[0]; return self.sortDesc(valA, valB); }; } else { throw(this.logIdentifier() + ' $orderBy clause has invalid direction: ' + dataPath.value + ', accepted values are 1 or -1 for ascending or descending!'); } return arr.sort(sorterMethod); }; /** * Internal method that takes a search query and options and * returns an object containing details about the query which * can be used to optimise the search. * * @param {Object} query The search query to analyse. * @param {Object} options The query options object. * @param {Operation} op The instance of the Operation class that * this operation is using to track things like performance and steps * taken etc. * @returns {Object} * @private */ Collection.prototype._analyseQuery = function (query, options, op) { var analysis = { queriesOn: [{id: '$collection.' + this._name, type: 'colletion', key: this._name}], indexMatch: [], hasJoin: false, queriesJoin: false, joinQueries: {}, query: query, options: options }, joinSourceIndex, joinSourceKey, joinSourceType, joinSourceIdentifier, joinMatch, joinSources = [], joinSourceReferences = [], queryPath, index, indexMatchData, indexRef, indexRefName, indexLookup, pathSolver, queryKeyCount, pkQueryType, lookupResult, i; // Check if the query is a primary key lookup op.time('checkIndexes'); pathSolver = new Path(); queryKeyCount = pathSolver.parseArr(query, { ignore:/\$/, verbose: true }).length; if (queryKeyCount) { if (query[this._primaryKey] !== undefined) { // Check suitability of querying key value index pkQueryType = typeof query[this._primaryKey]; if (pkQueryType === 'string' || pkQueryType === 'number' || query[this._primaryKey] instanceof Array) { // Return item via primary key possible op.time('checkIndexMatch: Primary Key'); lookupResult = this._primaryIndex.lookup(query, options, op); analysis.indexMatch.push({ lookup: lookupResult, keyData: { matchedKeys: [this._primaryKey], totalKeyCount: queryKeyCount, score: 1 }, index: this._primaryIndex }); op.time('checkIndexMatch: Primary Key'); } } // Check if an index can speed up the query for (i in this._indexById) { if (this._indexById.hasOwnProperty(i)) { indexRef = this._indexById[i]; indexRefName = indexRef.name(); op.time('checkIndexMatch: ' + indexRefName); indexMatchData = indexRef.match(query, options); if (indexMatchData.score > 0) { // This index can be used, store it indexLookup = indexRef.lookup(query, options, op); analysis.indexMatch.push({ lookup: indexLookup, keyData: indexMatchData, index: indexRef }); } op.time('checkIndexMatch: ' + indexRefName); if (indexMatchData.score === queryKeyCount) { // Found an optimal index, do not check for any more break; } } } op.time('checkIndexes'); // Sort array descending on index key count (effectively a measure of relevance to the query) if (analysis.indexMatch.length > 1) { op.time('findOptimalIndex'); analysis.indexMatch.sort(function (a, b) { if (a.keyData.score > b.keyData.score) { // This index has a higher score than the other return -1; } if (a.keyData.score < b.keyData.score) { // This index has a lower score than the other return 1; } // The indexes have the same score but can still be compared by the number of records // they return from the query. The fewer records they return the better so order by // record count if (a.keyData.score === b.keyData.score) { return a.lookup.length - b.lookup.length; } }); op.time('findOptimalIndex'); } } // Check for join data if (options.$join) { analysis.hasJoin = true; // Loop all join operations for (joinSourceIndex = 0; joinSourceIndex < options.$join.length; joinSourceIndex++) { // Loop the join sources and keep a reference to them for (joinSourceKey in options.$join[joinSourceIndex]) { if (options.$join[joinSourceIndex].hasOwnProperty(joinSourceKey)) { joinMatch = options.$join[joinSourceIndex][joinSourceKey]; joinSourceType = joinMatch.$sourceType || 'collection'; joinSourceIdentifier = '$' + joinSourceType + '.' + joinSourceKey; joinSources.push({ id: joinSourceIdentifier, type: joinSourceType, key: joinSourceKey }); // Check if the join uses an $as operator if (options.$join[joinSourceIndex][joinSourceKey].$as !== undefined) { joinSourceReferences.push(options.$join[joinSourceIndex][joinSourceKey].$as); } else { joinSourceReferences.push(joinSourceKey); } } } } // Loop the join source references and determine if the query references // any of the sources that are used in the join. If there no queries against // joined sources the find method can use a code path optimised for this. // Queries against joined sources requires the joined sources to be filtered // first and then joined so requires a little more work. for (index = 0; index < joinSourceReferences.length; index++) { // Check if the query references any source data that the join will create queryPath = this._queryReferencesSource(query, joinSourceReferences[index], ''); if (queryPath) { analysis.joinQueries[joinSources[index].key] = queryPath; analysis.queriesJoin = true; } } analysis.joinsOn = joinSources; analysis.queriesOn = analysis.queriesOn.concat(joinSources); } return analysis; }; /** * Checks if the passed query references a source object (such * as a collection) by name. * @param {Object} query The query object to scan. * @param {String} sourceName The source name to scan for in the query. * @param {String=} path The path to scan from. * @returns {*} * @private */ Collection.prototype._queryReferencesSource = function (query, sourceName, path) { var i; for (i in query) { if (query.hasOwnProperty(i)) { // Check if this key is a reference match if (i === sourceName) { if (path) { path += '.'; } return path + i; } else { if (typeof(query[i]) === 'object') { // Recurse if (path) { path += '.'; } path += i; return this._queryReferencesSource(query[i], sourceName, path); } } } } return false; }; /** * Returns the number of documents currently in the collection. * @returns {Number} */ Collection.prototype.count = function (query, options) { if (!query) { return this._data.length; } else { // Run query and return count return this.find(query, options).length; } }; /** * Finds sub-documents from the collection's documents. * @param {Object} match The query object to use when matching * parent documents from which the sub-documents are queried. * @param {String} path The path string used to identify the * key in which sub-documents are stored in parent documents. * @param {Object=} subDocQuery The query to use when matching * which sub-documents to return. * @param {Object=} subDocOptions The options object to use * when querying for sub-documents. * @returns {*} */ Collection.prototype.findSub = function (match, path, subDocQuery, subDocOptions) { return this._findSub(this.find(match), path, subDocQuery, subDocOptions); }; Collection.prototype._findSub = function (docArr, path, subDocQuery, subDocOptions) { var pathHandler = new Path(path), docCount = docArr.length, docIndex, subDocArr, subDocCollection = new Collection('__FDB_temp_' + this.objectId()).db(this._db), subDocResults, resultObj = { parents: docCount, subDocTotal: 0, subDocs: [], pathFound: false, err: '' }; subDocOptions = subDocOptions || {}; for (docIndex = 0; docIndex < docCount; docIndex++) { subDocArr = pathHandler.value(docArr[docIndex])[0]; if (subDocArr) { subDocCollection.setData(subDocArr); subDocResults = subDocCollection.find(subDocQuery, subDocOptions); if (subDocOptions.returnFirst && subDocResults.length) { return subDocResults[0]; } if (subDocOptions.$split) { resultObj.subDocs.push(subDocResults); } else { resultObj.subDocs = resultObj.subDocs.concat(subDocResults); } resultObj.subDocTotal += subDocResults.length; resultObj.pathFound = true; } } // Drop the sub-document collection subDocCollection.drop(); if (!resultObj.pathFound) { resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path; } // Check if the call should not return stats, if so return only subDocs array if (subDocOptions.$stats) { return resultObj; } else { return resultObj.subDocs; } }; /** * Finds the first sub-document from the collection's documents * that matches the subDocQuery parameter. * @param {Object} match The query object to use when matching * parent documents from which the sub-documents are queried. * @param {String} path The path string used to identify the * key in which sub-documents are stored in parent documents. * @param {Object=} subDocQuery The query to use when matching * which sub-documents to return. * @param {Object=} subDocOptions The options object to use * when querying for sub-documents. * @returns {Object} */ Collection.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) { return this.findSub(match, path, subDocQuery, subDocOptions)[0]; }; /** * Checks that the passed document will not violate any index rules if * inserted into the collection. * @param {Object} doc The document to check indexes against. * @returns {Boolean} Either false (no violation occurred) or true if * a violation was detected. */ Collection.prototype.insertIndexViolation = function (doc) { var indexViolated, arr = this._indexByName, arrIndex, arrItem; // Check the item's primary key is not already in use if (this._primaryIndex.get(doc[this._primaryKey])) { indexViolated = this._primaryIndex; } else { // Check violations of other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arrItem = arr[arrIndex]; if (arrItem.unique()) { if (arrItem.violation(doc)) { indexViolated = arrItem; break; } } } } } return indexViolated ? indexViolated.name() : false; }; /** * Creates an index on the specified keys. * @param {Object} keys The object containing keys to index. * @param {Object} options An options object. * @returns {*} */ Collection.prototype.ensureIndex = function (keys, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } this._indexByName = this._indexByName || {}; this._indexById = this._indexById || {}; var index, time = { start: new Date().getTime() }; if (options) { if (options.type) { // Check if the specified type is available if (Shared.index[options.type]) { // We found the type, generate it index = new Shared.index[options.type](keys, options, this); } else { throw(this.logIdentifier() + ' Cannot create index of type "' + options.type + '", type not found in the index type register (Shared.index)'); } } else { // Create default index type index = new IndexHashMap(keys, options, this); } } else { // Default index = new IndexHashMap(keys, options, this); } // Check the index does not already exist if (this._indexByName[index.name()]) { // Index already exists return { err: 'Index with that name already exists' }; } /*if (this._indexById[index.id()]) { // Index already exists return { err: 'Index with those keys already exists' }; }*/ // Create the index index.rebuild(); // Add the index this._indexByName[index.name()] = index; this._indexById[index.id()] = index; time.end = new Date().getTime(); time.total = time.end - time.start; this._lastOp = { type: 'ensureIndex', stats: { time: time } }; return { index: index, id: index.id(), name: index.name(), state: index.state() }; }; /** * Gets an index by it's name. * @param {String} name The name of the index to retreive. * @returns {*} */ Collection.prototype.index = function (name) { if (this._indexByName) { return this._indexByName[name]; } }; /** * Gets the last reporting operation's details such as run time. * @returns {Object} */ Collection.prototype.lastOp = function () { return this._metrics.list(); }; /** * Generates a difference object that contains insert, update and remove arrays * representing the operations to execute to make this collection have the same * data as the one passed. * @param {Collection} collection The collection to diff against. * @returns {{}} */ Collection.prototype.diff = function (collection) { var diff = { insert: [], update: [], remove: [] }; var pk = this.primaryKey(), arr, arrIndex, arrItem, arrCount; // Check if the primary key index of each collection can be utilised if (pk !== collection.primaryKey()) { throw(this.logIdentifier() + ' Diffing requires that both collections have the same primary key!'); } // Use the collection primary key index to do the diff (super-fast) arr = collection._data; // Check if we have an array or another collection while (arr && !(arr instanceof Array)) { // We don't have an array, assign collection and get data collection = arr; arr = collection._data; } arrCount = arr.length; // Loop the collection's data array and check for matching items for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = arr[arrIndex]; // Check for a matching item in this collection if (this._primaryIndex.get(arrItem[pk])) { // Matching item exists, check if the data is the same if (this._primaryCrc.get(arrItem[pk]) !== collection._primaryCrc.get(arrItem[pk])) { // The documents exist in both collections but data differs, update required diff.update.push(arrItem); } } else { // The document is missing from this collection, insert required diff.insert.push(arrItem); } } // Now loop this collection's data and check for matching items arr = this._data; arrCount = arr.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = arr[arrIndex]; if (!collection._primaryIndex.get(arrItem[pk])) { // The document does not exist in the other collection, remove required diff.remove.push(arrItem); } } return diff; }; Collection.prototype.collateAdd = new Overload('Collection.prototype.collateAdd', { /** * Adds a data source to collate data from and specifies the * key name to collate data to. * @func collateAdd * @memberof Collection * @param {Collection} collection The collection to collate data from. * @param {String=} keyName Optional name of the key to collate data to. * If none is provided the record CRUD is operated on the root collection * data. */ 'object, string': function (collection, keyName) { var self = this; self.collateAdd(collection, function (packet) { var obj1, obj2; switch (packet.type) { case 'insert': if (keyName) { obj1 = { $push: {} }; obj1.$push[keyName] = self.decouple(packet.data.dataSet); self.update({}, obj1); } else { self.insert(packet.data.dataSet); } break; case 'update': if (keyName) { obj1 = {}; obj2 = {}; obj1[keyName] = packet.data.query; obj2[keyName + '.$'] = packet.data.update; self.update(obj1, obj2); } else { self.update(packet.data.query, packet.data.update); } break; case 'remove': if (keyName) { obj1 = { $pull: {} }; obj1.$pull[keyName] = {}; obj1.$pull[keyName][self.primaryKey()] = packet.data.dataSet[0][collection.primaryKey()]; self.update({}, obj1); } else { self.remove(packet.data.dataSet); } break; default: } }); }, /** * Adds a data source to collate data from and specifies a process * method that will handle the collation functionality (for custom * collation). * @func collateAdd * @memberof Collection * @param {Collection} collection The collection to collate data from. * @param {Function} process The process method. */ 'object, function': function (collection, process) { if (typeof collection === 'string') { // The collection passed is a name, not a reference so get // the reference from the name collection = this._db.collection(collection, { autoCreate: false, throwError: false }); } if (collection) { this._collate = this._collate || {}; this._collate[collection.name()] = new ReactorIO(collection, this, process); return this; } else { throw('Cannot collate from a non-existent collection!'); } } }); Collection.prototype.collateRemove = function (collection) { if (typeof collection === 'object') { // We need to have the name of the collection to remove it collection = collection.name(); } if (collection) { // Drop the reactor IO chain node this._collate[collection].drop(); // Remove the collection data from the collate object delete this._collate[collection]; return this; } else { throw('No collection name passed to collateRemove() or collection not found!'); } }; 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 a longitude/latitude array. * The array contains three latitudes and three longitudes. The * first of each is the lower extent of the geohash bounding box, * the second is the upper extent and the third is the center * of the geohash bounding box. * @param {String} geohash The hash to decode. * @returns {Object} */ GeoHash.prototype.decode = function (geohash) { var isEven = 1, lat = [], lon = [], i, c, cd, j, mask, latErr, lonErr; lat[0] = -90.0; lat[1] = 90.0; lon[0] = -180.0; lon[1] = 180.0; latErr = 90.0; lonErr = 180.0; for (i = 0; i < geohash.length; i++) { c = geohash[i]; cd = base32.indexOf(c); for (j = 0; j < 5; j++) { mask = bits[j]; if (isEven) { lonErr /= 2; this.refineInterval(lon, cd, mask); } else { latErr /= 2; this.refineInterval(lat, cd, mask); } isEven = !isEven; } } lat[2] = (lat[0] + lat[1]) / 2; lon[2] = (lon[0] + lon[1]) / 2; return { 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; }; typeof module !== 'undefined' ? 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, onFilterSourceChange, filterQuery, filterView = self._db.view('tmpGridFilter_' + self._id + '_' + filterField); filterSort[filterField] = 1; filterQuery = { $distinct: filterSort }; filterView .query(filterQuery) .orderBy(filterSort) .from(self._from._from); onFilterSourceChange = function () { filterView.refresh(); }; // Listen for changes on the filter source and update // the filters if changes occur self._from._from.on('change', onFilterSourceChange); // This bit of commented code can filter other filter // views so that only items that match other filter // selections show in the other filters, but this can // be confusing to the user. The best possible way to // use this would be to "grey out" the selections that // cannot be used because they would return zero results // when used in conjuctions with other filter selections. /*self._from.on('change', function () { if (self._from && self._from instanceof View) { var query = self._from.query(); query.$distinct = filterSort; delete query[filterField]; filterView .query(query); console.log(self._from._from.find(query)); } });*/ // Listen for the grid being dropped and remove listener // for changes on filter source self.on('drop', function () { if (self._from && self._from._from) { self._from._from.off('change', onFilterSourceChange); } }); 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>&nbsp;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">&nbsp;{^{:' + 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]); }; /** * Looks up records that match the passed query and options. * @param query The query to execute. * @param options A query options object. * @param {Operation=} op Optional operation instance that allows * us to provide operation diagnostics and analytics back to the * main calling instance as the process is running. * @returns {*} */ Index2d.prototype.lookup = function (query, options, op) { // Loop the indexed keys and determine if the query has any operators // that we want to handle differently from a standard lookup var keys = this._btree.keys(), pathStr, pathVal, results, i; for (i = 0; i < keys.length; i++) { pathStr = keys[i].path; pathVal = sharedPathSolver.get(query, pathStr); if (typeof pathVal === 'object') { if (pathVal.$near) { results = []; // Do a near point lookup results = results.concat(this.near(pathStr, pathVal.$near, options, op)); } if (pathVal.$geoWithin) { results = []; // Do a geoWithin shape lookup results = results.concat(this.geoWithin(pathStr, pathVal.$geoWithin, options, op)); } return results; } } return this._btree.lookup(query, options); }; Index2d.prototype.near = function (pathStr, query, options, op) { var self = this, geoHash, neighbours, visitedCount, visitedNodes, visitedData, search, results, finalResults = [], precision, maxDistanceKm, distance, distCache, latLng, pk = this._collection.primaryKey(), i; // Calculate the required precision to encapsulate the distance // TODO: Instead of opting for the "one size larger" than the distance boxes, // TODO: we should calculate closest divisible box size as a multiple and then // TODO: scan neighbours until we have covered the area otherwise we risk // TODO: opening the results up to vastly more information as the box size // TODO: increases dramatically between the geohash precisions if (query.$distanceUnits === 'km') { maxDistanceKm = query.$maxDistance; for (i = 0; i < geoHashDistance.length; i++) { if (maxDistanceKm > geoHashDistance[i]) { precision = i; break; } } } 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 if (op) { op.time('index2d.calculateNeighbours'); } neighbours = sharedGeoHashSolver.calculateNeighbours(geoHash, {type: 'array'}); if (op) { op.time('index2d.calculateNeighbours'); } if (op) { op.data('index2d.near.precision', precision); op.data('index2d.near.neighbours', neighbours); op.data('index2d.near.maxDistanceKm', maxDistanceKm); op.data('index2d.near.centerPointCoords', [query.$point[0], query.$point[1]]); op.data('index2d.near.centerPointGeoHash', geoHash); } // Lookup all matching co-ordinates from the btree results = []; visitedCount = 0; visitedData = {}; visitedNodes = []; if (op) { op.time('index2d.near.neighbourSearch'); } for (i = 0; i < 9; i++) { search = this._btree.startsWith(pathStr, neighbours[i]); visitedData[neighbours[i]] = search; visitedCount += search._visitedCount; visitedNodes = visitedNodes.concat(search._visitedNodes); results = results.concat(search); } if (op) { op.time('index2d.near.neighbourSearch'); op.data('index2d.near.startsWith', visitedData); op.data('index2d.near.visitedTreeNodes', visitedNodes); } // Work with original data if (op) { op.time('index2d.near.primaryIndexLookup'); } results = this._collection._primaryIndex.lookup(results); if (op) { op.time('index2d.near.primaryIndexLookup'); } if (query.$distanceField) { // Decouple the results before we modify them results = this.decouple(results); } if (results.length) { distance = {}; if (op) { op.time('index2d.near.calculateDistanceFromCenter'); } // Loop the results and calculate distance for (i = 0; i < results.length; i++) { latLng = sharedPathSolver.get(results[i], pathStr); distCache = distance[results[i][pk]] = this.distanceBetweenPoints(query.$point[0], query.$point[1], latLng[0], latLng[1]); if (distCache <= maxDistanceKm) { if (query.$distanceField) { // Options specify a field to add the distance data to // so add it now sharedPathSolver.set(results[i], query.$distanceField, query.$distanceUnits === 'km' ? distCache : Math.round(distCache * 0.621371)); } if (query.$geoHashField) { // Options specify a field to add the distance data to // so add it now sharedPathSolver.set(results[i], query.$geoHashField, sharedGeoHashSolver.encode(latLng[0], latLng[1], precision)); } // Add item as it is inside radius distance finalResults.push(results[i]); //console.log('Accepted', results[i].name, query.$distanceUnits === 'km' ? distCache : Math.round(distCache * 0.621371), '<=', maxDistanceKm, query.$distanceUnits); } else { //console.log('REJECTED', results[i].name, query.$distanceUnits === 'km' ? distCache : Math.round(distCache * 0.621371), '<=', maxDistanceKm, query.$distanceUnits); } } if (op) { op.time('index2d.near.calculateDistanceFromCenter'); } // Sort by distance from center if (op) { op.time('index2d.near.sortResultsByDistance'); } finalResults.sort(function (a, b) { return self.sortAsc(distance[a[pk]], distance[b[pk]]); }); if (op) { op.time('index2d.near.sortResultsByDistance'); } } // Return data return finalResults; }; Index2d.prototype.geoWithin = function (pathStr, query, options) { 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, op) { return this._btree.lookup(query, options, op); }; IndexBinaryTree.prototype.match = function (query, options) { return this._btree.match(query, options); }; IndexBinaryTree.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; IndexBinaryTree.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; IndexBinaryTree.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; // Register this index on the shared object Shared.index.btree = IndexBinaryTree; Shared.finishModule('IndexBinaryTree'); module.exports = IndexBinaryTree; },{"./BinaryTree":3,"./Path":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) { self.triggerStack = {}; // The trigger does not exist, create it self._trigger = self._trigger || {}; self._trigger[type] = self._trigger[type] || {}; self._trigger[type][phase] = self._trigger[type][phase] || []; self._trigger[type][phase].push({ id: id, method: method, enabled: true }); return true; } return false; }, /** * * @param {String} id The id of the trigger to remove. * @param {Number} type The type of operation to remove the trigger from. See * Mixin.Constants for constants to use. * @param {Number} phase The phase of the operation to remove the trigger from. * See Mixin.Constants for constants to use. * @returns {boolean} True if removed successfully, false if not. */ removeTrigger: function (id, type, phase) { var self = this, triggerIndex; // Check if the trigger already exists triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // The trigger exists, remove it self._trigger[type][phase].splice(triggerIndex, 1); } return false; }, /** * Tells the current instance to fire or ignore all triggers whether they * are enabled or not. * @param {Boolean} val Set to true to ignore triggers or false to not * ignore them. * @returns {*} */ ignoreTriggers: function (val) { if (val !== undefined) { this._ignoreTriggers = val; return this; } return this._ignoreTriggers; }, /** * Generates triggers that fire in the after phase for all CRUD ops * that automatically transform data back and forth and keep both * import and export collections in sync with each other. * @param {String} id The unique id for this link IO. * @param {Object} ioData The settings for the link IO. */ addLinkIO: function (id, ioData) { var self = this, matchAll, exportData, importData, exportTriggerMethod, importTriggerMethod, exportTo, importFrom, allTypes, i; // Store the linkIO self._linkIO = self._linkIO || {}; self._linkIO[id] = ioData; exportData = ioData['export']; importData = ioData['import']; if (exportData) { exportTo = self.db().collection(exportData.to); } if (importData) { importFrom = self.db().collection(importData.from); } allTypes = [ self.TYPE_INSERT, self.TYPE_UPDATE, self.TYPE_REMOVE ]; matchAll = function (data, callback) { // Match all callback(false, true); }; if (exportData) { // Check for export match method if (!exportData.match) { // No match method found, use the match all method exportData.match = matchAll; } // Check for export types if (!exportData.types) { exportData.types = allTypes; } exportTriggerMethod = function (operation, oldDoc, newDoc) { // Check if we should execute against this data exportData.match(newDoc, function (err, doExport) { if (!err && doExport) { // Get data to upsert (if any) exportData.data(newDoc, operation.type, function (err, data, callback) { if (!err && data) { // Disable all currently enabled triggers so that we // don't go into a trigger loop exportTo.ignoreTriggers(true); if (operation.type !== 'remove') { // Do upsert exportTo.upsert(data, callback); } else { // Do remove exportTo.remove(data, callback); } // Re-enable the previous triggers exportTo.ignoreTriggers(false); } }); } }); }; } if (importData) { // Check for import match method if (!importData.match) { // No match method found, use the match all method importData.match = matchAll; } // Check for import types if (!importData.types) { importData.types = allTypes; } importTriggerMethod = function (operation, oldDoc, newDoc) { // Check if we should execute against this data importData.match(newDoc, function (err, doExport) { if (!err && doExport) { // Get data to upsert (if any) importData.data(newDoc, operation.type, function (err, data, callback) { if (!err && data) { // Disable all currently enabled triggers so that we // don't go into a trigger loop exportTo.ignoreTriggers(true); if (operation.type !== 'remove') { // Do upsert self.upsert(data, callback); } else { // Do remove self.remove(data, callback); } // Re-enable the previous triggers exportTo.ignoreTriggers(false); } }); } }); }; } if (exportData) { for (i = 0; i < exportData.types.length; i++) { self.addTrigger(id + 'export' + exportData.types[i], exportData.types[i], self.PHASE_AFTER, exportTriggerMethod); } } if (importData) { for (i = 0; i < importData.types.length; i++) { importFrom.addTrigger(id + 'import' + importData.types[i], importData.types[i], self.PHASE_AFTER, importTriggerMethod); } } }, /** * Removes a previously added link IO via it's ID. * @param {String} id The id of the link IO to remove. * @returns {boolean} True if successful, false if the link IO * was not found. */ removeLinkIO: function (id) { var self = this, linkIO = self._linkIO[id], exportData, importData, importFrom, i; if (linkIO) { exportData = linkIO['export']; importData = linkIO['import']; if (exportData) { for (i = 0; i < exportData.types.length; i++) { self.removeTrigger(id + 'export' + exportData.types[i], exportData.types[i], self.db.PHASE_AFTER); } } if (importData) { importFrom = self.db().collection(importData.from); for (i = 0; i < importData.types.length; i++) { importFrom.removeTrigger(id + 'import' + importData.types[i], importData.types[i], self.db.PHASE_AFTER); } } delete self._linkIO[id]; return true; } return false; }, enableTrigger: new Overload({ 'string': function (id) { // Alter all triggers of this type var self = this, types = self._trigger, phases, triggers, result = false, i, k, j; if (types) { for (j in types) { if (types.hasOwnProperty(j)) { phases = types[j]; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set enabled flag for (k = 0; k < triggers.length; k++) { if (triggers[k].id === id) { triggers[k].enabled = true; result = true; } } } } } } } } return result; }, 'number': function (type) { // Alter all triggers of this type var self = this, phases = self._trigger[type], triggers, result = false, i, k; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set to enabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = true; result = true; } } } } return result; }, 'number, number': function (type, phase) { // Alter all triggers of this type and phase var self = this, phases = self._trigger[type], triggers, result = false, k; if (phases) { triggers = phases[phase]; if (triggers) { // Loop triggers and set to enabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = true; result = true; } } } return result; }, 'string, number, number': function (id, type, phase) { // Check if the trigger already exists var self = this, triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // Update the trigger self._trigger[type][phase][triggerIndex].enabled = true; return true; } return false; } }), disableTrigger: new Overload({ 'string': function (id) { // Alter all triggers of this type var self = this, types = self._trigger, phases, triggers, result = false, i, k, j; if (types) { for (j in types) { if (types.hasOwnProperty(j)) { phases = types[j]; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set enabled flag for (k = 0; k < triggers.length; k++) { if (triggers[k].id === id) { triggers[k].enabled = false; result = true; } } } } } } } } return result; }, 'number': function (type) { // Alter all triggers of this type var self = this, phases = self._trigger[type], triggers, result = false, i, k; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set to disabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = false; result = true; } } } } return result; }, 'number, number': function (type, phase) { // Alter all triggers of this type and phase var self = this, phases = self._trigger[type], triggers, result = false, k; if (phases) { triggers = phases[phase]; if (triggers) { // Loop triggers and set to disabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = false; result = true; } } } return result; }, 'string, number, number': function (id, type, phase) { // Check if the trigger already exists var self = this, triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // Update the trigger self._trigger[type][phase][triggerIndex].enabled = false; return true; } return false; } }), /** * Checks if a trigger will fire based on the type and phase provided. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @returns {Boolean} True if the trigger will fire, false otherwise. */ willTrigger: function (type, phase) { if (!this._ignoreTriggers && this._trigger && this._trigger[type] && this._trigger[type][phase] && this._trigger[type][phase].length) { // Check if a trigger in this array is enabled var arr = this._trigger[type][phase], i; for (i = 0; i < arr.length; i++) { if (arr[i].enabled) { return true; } } } return false; }, /** * Processes trigger actions based on the operation, type and phase. * @param {Object} operation Operation data to pass to the trigger. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @param {Object} oldDoc The document snapshot before operations are * carried out against the data. * @param {Object} newDoc The document snapshot after operations are * carried out against the data. * @returns {boolean} */ processTrigger: function (operation, type, phase, oldDoc, newDoc) { var self = this, triggerArr, triggerIndex, triggerCount, triggerItem, response, typeName, phaseName; if (!self._ignoreTriggers && self._trigger && self._trigger[type] && self._trigger[type][phase]) { triggerArr = self._trigger[type][phase]; triggerCount = triggerArr.length; for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) { triggerItem = triggerArr[triggerIndex]; // Check if the trigger is enabled if (triggerItem.enabled) { if (self.debug()) { switch (type) { case this.TYPE_INSERT: typeName = 'insert'; break; case this.TYPE_UPDATE: typeName = 'update'; break; case this.TYPE_REMOVE: typeName = 'remove'; break; default: typeName = ''; break; } switch (phase) { case this.PHASE_BEFORE: phaseName = 'before'; break; case this.PHASE_AFTER: phaseName = 'after'; break; default: phaseName = ''; break; } console.log('Triggers: Processing trigger "' + triggerItem.id + '" for ' + typeName + ' in phase "' + phaseName + '"'); } // Check if the trigger is already in the stack, if it is, // don't fire it again (this is so we avoid infinite loops // where a trigger triggers another trigger which calls this // one and so on) if (self.triggerStack && self.triggerStack[type] && self.triggerStack[type][phase] && self.triggerStack[type][phase][triggerItem.id]) { // The trigger is already in the stack, do not fire the trigger again if (self.debug()) { console.log('Triggers: Will not run trigger "' + triggerItem.id + '" for ' + typeName + ' in phase "' + phaseName + '" as it is already in the stack!'); } continue; } // Add the trigger to the stack so we don't go down an endless // trigger loop self.triggerStack = self.triggerStack || {}; self.triggerStack[type] = {}; self.triggerStack[type][phase] = {}; self.triggerStack[type][phase][triggerItem.id] = true; // Run the trigger's method and store the response response = triggerItem.method.call(self, operation, oldDoc, newDoc); // Remove the trigger from the stack self.triggerStack = self.triggerStack || {}; self.triggerStack[type] = {}; self.triggerStack[type][phase] = {}; self.triggerStack[type][phase][triggerItem.id] = false; // Check the response for a non-expected result (anything other than // [undefined, true or false] is considered a throwable error) if (response === false) { // The trigger wants us to cancel operations return false; } if (response !== undefined && response !== true && response !== false) { // Trigger responded with error, throw the error throw('ForerunnerDB.Mixin.Triggers: Trigger error: ' + response); } } } // Triggers all ran without issue, return a success (true) return true; } }, /** * Returns the index of a trigger by id based on type and phase. * @param {String} id The id of the trigger to find the index of. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @returns {number} * @private */ _triggerIndexOf: function (id, type, phase) { var self = this, triggerArr, triggerCount, triggerIndex; if (self._trigger && self._trigger[type] && self._trigger[type][phase]) { triggerArr = self._trigger[type][phase]; triggerCount = triggerArr.length; for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) { if (triggerArr[triggerIndex].id === id) { return triggerIndex; } } } return -1; } }; module.exports = Triggers; },{"./Overload":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.data(); 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.data(); 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) { if (!err) { localforage.setItem(key, data).then(function (data) { if (callback) { callback(false, data, tableStats); } }, function (err) { if (callback) { callback(err); } }); } else { callback(err); } }); break; default: if (callback) { callback('No data handler.'); } break; } }; /** * Loads and decodes data from the passed key. * @param {String} key The key to retrieve data from in the persistent * storage. * @param {Function=} callback The method to call when the load process * has completed. */ Persist.prototype.load = function (key, callback) { var self = this; switch (this.mode()) { case 'localforage': localforage.getItem(key).then(function (val) { self.decode(val, callback); }, function (err) { if (callback) { callback(err); } }); break; default: if (callback) { callback('No data handler or unrecognised data type.'); } break; } }; /** * Deletes data in persistent storage stored under the passed key. * @param {String} key The key to drop data for in the storage. * @param {Function=} callback The method to call when the data is dropped. */ Persist.prototype.drop = function (key, callback) { switch (this.mode()) { case 'localforage': localforage.removeItem(key).then(function () { if (callback) { callback(false); } }, function (err) { if (callback) { callback(err); } }); break; default: if (callback) { callback('No data handler or unrecognised data type.'); } break; } }; // Extend the Collection prototype with persist methods Collection.prototype.drop = new Overload({ /** * Drop collection and persistent storage. */ '': function () { if (!this.isDropped()) { this.drop(true); } }, /** * Drop collection and persistent storage with callback. * @param {Function} callback Callback method. */ 'function': function (callback) { if (!this.isDropped()) { this.drop(true, callback); } }, /** * Drop collection and optionally drop persistent storage. * @param {Boolean} removePersistent True to drop persistent storage, false to keep it. */ 'boolean': function (removePersistent) { if (!this.isDropped()) { // Remove persistent storage if (removePersistent) { if (this._name) { if (this._db) { // Drop the collection data from storage this._db.persist.drop(this._db._name + '-' + this._name); this._db.persist.drop(this._db._name + '-' + this._name + '-metaData'); } } else { throw('ForerunnerDB.Persist: Cannot drop a collection\'s persistent storage when no name assigned to collection!'); } } // Call the original method CollectionDrop.call(this); } }, /** * Drop collections and optionally drop persistent storage with callback. * @param {Boolean} removePersistent True to drop persistent storage, false to keep it. * @param {Function} callback Callback method. */ 'boolean, function': function (removePersistent, callback) { var self = this; if (!this.isDropped()) { // Remove persistent storage if (removePersistent) { if (this._name) { if (this._db) { // Drop the collection data from storage this._db.persist.drop(this._db._name + '-' + this._name, function () { self._db.persist.drop(self._db._name + '-' + self._name + '-metaData', callback); }); return CollectionDrop.call(this); } else { if (callback) { callback('Cannot drop a collection\'s persistent storage when the collection is not attached to a database!'); } } } else { if (callback) { callback('Cannot drop a collection\'s persistent storage when no name assigned to collection!'); } } } else { // Call the original method return CollectionDrop.call(this, callback); } } } }); /** * Saves an entire collection's data to persistent storage. * @param {Function=} callback The method to call when the save function * has completed. */ Collection.prototype.save = function (callback) { var self = this, processSave; if (self._name) { if (self._db) { processSave = function () { // Save the collection data self._db.persist.save(self._db._name + '-' + self._name, self._data, function (err, tableData, tableStats) { if (!err) { self._db.persist.save(self._db._name + '-' + self._name + '-metaData', self.metaData(), function (err, metaData, metaStats) { if (callback) { callback(err, tableStats, metaStats, { tableData: tableData, metaData: metaData, tableDataName: self._db._name + '-' + self._name, metaDataName: self._db._name + '-' + self._name + '-metaData' }); } }); } else { if (callback) { callback(err); } } }); }; // Check for processing queues if (self.isProcessingQueue()) { // Hook queue complete to process save self.on('queuesComplete', function () { processSave(); }); } else { // Process save immediately processSave(); } } else { if (callback) { callback('Cannot save a collection that is not attached to a database!'); } } } else { if (callback) { callback('Cannot save a collection with no assigned name!'); } } }; /** * Loads an entire collection's data from persistent storage. * @param {Function=} callback The method to call when the load function * has completed. */ Collection.prototype.load = function (callback) { var self = this; if (self._name) { if (self._db) { // Load the collection data self._db.persist.load(self._db._name + '-' + self._name, function (err, data, tableStats) { if (!err) { // Remove all previous data self.remove({}, function () { // Now insert the new data data = data || []; self.insert(data, function () { // Now load the collection's metadata self._db.persist.load(self._db._name + '-' + self._name + '-metaData', function (err, data, metaStats) { if (!err) { if (data) { self.metaData(data); } } if (callback) { callback(err, tableStats, metaStats); } }); }); //self.setData(data); }); } else { if (callback) { callback(err); } } }); } else { if (callback) { callback('Cannot load a collection that is not attached to a database!'); } } } else { if (callback) { callback('Cannot load a collection with no assigned name!'); } } }; /** * Gets the data that represents this collection for easy storage using * a third-party method / plugin instead of using the standard persistent * storage system. * @param {Function} callback The method to call with the data response. */ Collection.prototype.saveCustom = function (callback) { var self = this, myData = {}, processSave; if (self._name) { if (self._db) { processSave = function () { self.encode(self._data, function (err, data, tableStats) { if (!err) { myData.data = { name: self._db._name + '-' + self._name, store: data, tableStats: tableStats }; self.encode(self._data, function (err, data, tableStats) { if (!err) { myData.metaData = { name: self._db._name + '-' + self._name + '-metaData', store: data, tableStats: tableStats }; callback(false, myData); } else { callback(err); } }); } else { callback(err); } }); }; // Check for processing queues if (self.isProcessingQueue()) { // Hook queue complete to process save self.on('queuesComplete', function () { processSave(); }); } else { // Process save immediately processSave(); } } else { if (callback) { callback('Cannot save a collection that is not attached to a database!'); } } } else { if (callback) { callback('Cannot save a collection with no assigned name!'); } } }; /** * Loads custom data loaded by a third-party plugin into the collection. * @param {Object} myData Data object previously saved by using saveCustom() * @param {Function} callback A callback method to receive notification when * data has loaded. */ Collection.prototype.loadCustom = function (myData, callback) { var self = this; if (self._name) { if (self._db) { if (myData.data && myData.data.store) { if (myData.metaData && myData.metaData.store) { self.decode(myData.data.store, function (err, data, tableStats) { if (!err) { if (data) { // Remove all previous data self.remove({}); self.insert(data); self.decode(myData.metaData.store, function (err, data, metaStats) { if (!err) { if (data) { self.metaData(data); if (callback) { callback(err, tableStats, metaStats); } } } else { callback(err); } }); } } else { callback(err); } }); } else { callback('No "metaData" key found in passed object!'); } } else { callback('No "data" key found in passed object!'); } } else { if (callback) { callback('Cannot load a collection that is not attached to a database!'); } } } else { if (callback) { callback('Cannot load a collection with no assigned name!'); } } }; // Override the DB init to instantiate the plugin Db.prototype.init = function () { DbInit.apply(this, arguments); this.persist = new Persist(this); }; Db.prototype.load = new Overload({ /** * Loads an entire database's data from persistent storage. * @param {Function=} callback The method to call when the load function * has completed. */ 'function': function (callback) { this.$main.call(this, {}, callback); }, 'object, function': function (myData, callback) { this.$main.call(this, myData, callback); }, '$main': function (myData, callback) { // Loop the collections in the database var obj = this._collection, keys = obj.keys(), keyCount = keys.length, loadCallback, index; loadCallback = function (err) { if (!err) { keyCount--; if (keyCount === 0) { if (callback) { callback(false); } } } else { if (callback) { callback(err); } } }; for (index in obj) { if (obj.hasOwnProperty(index)) { // Call the collection load method if (!myData) { obj[index].load(loadCallback); } else { obj[index].loadCustom(myData, loadCallback); } } } } }); Db.prototype.save = new Overload({ /** * Saves an entire database's data to persistent storage. * @param {Function=} callback The method to call when the save function * has completed. */ 'function': function (callback) { this.$main.call(this, {}, callback); }, 'object, function': function (options, callback) { this.$main.call(this, options, callback); }, '$main': function (options, callback) { // Loop the collections in the database var obj = this._collection, keys = obj.keys(), keyCount = keys.length, saveCallback, index; saveCallback = function (err) { if (!err) { keyCount--; if (keyCount === 0) { if (callback) { callback(false); } } } else { if (callback) { callback(err); } } }; for (index in obj) { if (obj.hasOwnProperty(index)) { // Call the collection save method if (!options.custom) { obj[index].save(saveCallback); } else { obj[index].saveCustom(saveCallback); } } } } }); Shared.finishModule('Persist'); module.exports = Persist; },{"./Collection":5,"./CollectionGroup":6,"./PersistCompress":35,"./PersistCrypto":36,"./Shared":39,"async":42,"localforage":80}],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":82}],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":51}],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.773', 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.decouple(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.decouple(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; } 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){ // Use the fastest possible means to execute a task in a future turn // of the event loop. // linked list of tasks (single, with head node) var head = {task: void 0, next: null}; var tail = head; var flushing = false; var requestFlush = void 0; var isNodeJS = false; function flush() { /* jshint loopfunc: true */ while (head.next) { head = head.next; var task = head.task; head.task = void 0; var domain = head.domain; if (domain) { head.domain = void 0; domain.enter(); } try { task(); } catch (e) { if (isNodeJS) { // In node, uncaught exceptions are considered fatal errors. // Re-throw them synchronously to interrupt flushing! // Ensure continuation if the uncaught exception is suppressed // listening "uncaughtException" events (as domains does). // Continue in next event to avoid tick recursion. if (domain) { domain.exit(); } setTimeout(flush, 0); if (domain) { domain.enter(); } throw e; } else { // In browsers, uncaught exceptions are not fatal. // Re-throw them asynchronously to avoid slow-downs. setTimeout(function() { throw e; }, 0); } } if (domain) { domain.exit(); } } flushing = false; } if (typeof process !== "undefined" && process.nextTick) { // Node.js before 0.9. Note that some fake-Node environments, like the // Mocha test runner, introduce a `process` global without a `nextTick`. isNodeJS = true; requestFlush = function () { process.nextTick(flush); }; } else if (typeof setImmediate === "function") { // In IE10, Node.js 0.9+, or https://github.com/NobleJS/setImmediate if (typeof window !== "undefined") { requestFlush = setImmediate.bind(window, flush); } else { requestFlush = function () { setImmediate(flush); }; } } else if (typeof MessageChannel !== "undefined") { // modern browsers // http://www.nonblocking.io/2011/06/windownexttick.html var channel = new MessageChannel(); channel.port1.onmessage = flush; requestFlush = function () { channel.port2.postMessage(0); }; } else { // old browsers requestFlush = function () { setTimeout(flush, 0); }; } function asap(task) { tail = tail.next = { task: task, domain: isNodeJS && process.domain, next: null }; if (!flushing) { flushing = true; requestFlush(); } }; module.exports = asap; }).call(this,_dereq_('_process')) },{"_process":98}],42:[function(_dereq_,module,exports){ (function (process,global){ /*! * async * https://github.com/caolan/async * * Copyright 2010-2014 Caolan McMahon * Released under the MIT license */ (function () { var async = {}; function noop() {} function identity(v) { return v; } function toBool(v) { return !!v; } function notId(v) { return !v; } // global on the server, window in the browser var previous_async; // Establish the root object, `window` (`self`) in the browser, `global` // on the server, or `this` in some virtual machines. We use `self` // instead of `window` for `WebWorker` support. var root = typeof self === 'object' && self.self === self && self || typeof global === 'object' && global.global === global && global || this; if (root != null) { previous_async = root.async; } async.noConflict = function () { root.async = previous_async; return async; }; function only_once(fn) { return function() { if (fn === null) throw new Error("Callback was already called."); fn.apply(this, arguments); fn = null; }; } function _once(fn) { return function() { if (fn === null) return; fn.apply(this, arguments); fn = null; }; } //// cross-browser compatiblity functions //// var _toString = Object.prototype.toString; var _isArray = Array.isArray || function (obj) { return _toString.call(obj) === '[object Array]'; }; // Ported from underscore.js isObject var _isObject = function(obj) { var type = typeof obj; return type === 'function' || type === 'object' && !!obj; }; function _isArrayLike(arr) { return _isArray(arr) || ( // has a positive integer length property typeof arr.length === "number" && arr.length >= 0 && arr.length % 1 === 0 ); } function _arrayEach(arr, iterator) { var index = -1, length = arr.length; while (++index < length) { iterator(arr[index], index, arr); } } function _map(arr, iterator) { var index = -1, length = arr.length, result = Array(length); while (++index < length) { result[index] = iterator(arr[index], index, arr); } return result; } function _range(count) { return _map(Array(count), function (v, i) { return i; }); } function _reduce(arr, iterator, memo) { _arrayEach(arr, function (x, i, a) { memo = iterator(memo, x, i, a); }); return memo; } function _forEachOf(object, iterator) { _arrayEach(_keys(object), function (key) { iterator(object[key], key); }); } function _indexOf(arr, item) { for (var i = 0; i < arr.length; i++) { if (arr[i] === item) return i; } return -1; } var _keys = Object.keys || function (obj) { var keys = []; for (var k in obj) { if (obj.hasOwnProperty(k)) { keys.push(k); } } return keys; }; function _keyIterator(coll) { var i = -1; var len; var keys; if (_isArrayLike(coll)) { len = coll.length; return function next() { i++; return i < len ? i : null; }; } else { keys = _keys(coll); len = keys.length; return function next() { i++; return i < len ? keys[i] : null; }; } } // Similar to ES6's rest param (http://ariya.ofilabs.com/2013/03/es6-and-rest-parameter.html) // This accumulates the arguments passed into an array, after a given index. // From underscore.js (https://github.com/jashkenas/underscore/pull/2140). function _restParam(func, startIndex) { startIndex = startIndex == null ? func.length - 1 : +startIndex; return function() { var length = Math.max(arguments.length - startIndex, 0); var rest = Array(length); for (var index = 0; index < length; index++) { rest[index] = arguments[index + startIndex]; } switch (startIndex) { case 0: return func.call(this, rest); case 1: return func.call(this, arguments[0], rest); } // Currently unused but handle cases outside of the switch statement: // var args = Array(startIndex + 1); // for (index = 0; index < startIndex; index++) { // args[index] = arguments[index]; // } // args[startIndex] = rest; // return func.apply(this, args); }; } function _withoutIndex(iterator) { return function (value, index, callback) { return iterator(value, callback); }; } //// exported async module functions //// //// nextTick implementation with browser-compatible fallback //// // capture the global reference to guard against fakeTimer mocks var _setImmediate = typeof setImmediate === 'function' && setImmediate; var _delay = _setImmediate ? function(fn) { // not a direct alias for IE10 compatibility _setImmediate(fn); } : function(fn) { setTimeout(fn, 0); }; if (typeof process === 'object' && typeof process.nextTick === 'function') { async.nextTick = process.nextTick; } else { async.nextTick = _delay; } async.setImmediate = _setImmediate ? _delay : async.nextTick; async.forEach = async.each = function (arr, iterator, callback) { return async.eachOf(arr, _withoutIndex(iterator), callback); }; async.forEachSeries = async.eachSeries = function (arr, iterator, callback) { return async.eachOfSeries(arr, _withoutIndex(iterator), callback); }; async.forEachLimit = async.eachLimit = function (arr, limit, iterator, callback) { return _eachOfLimit(limit)(arr, _withoutIndex(iterator), callback); }; async.forEachOf = async.eachOf = function (object, iterator, callback) { callback = _once(callback || noop); object = object || []; var iter = _keyIterator(object); var key, completed = 0; while ((key = iter()) != null) { completed += 1; iterator(object[key], key, only_once(done)); } if (completed === 0) callback(null); function done(err) { completed--; if (err) { callback(err); } // Check key is null in case iterator isn't exhausted // and done resolved synchronously. else if (key === null && completed <= 0) { callback(null); } } }; async.forEachOfSeries = async.eachOfSeries = function (obj, iterator, callback) { callback = _once(callback || noop); obj = obj || []; var nextKey = _keyIterator(obj); var key = nextKey(); function iterate() { var sync = true; if (key === null) { return callback(null); } iterator(obj[key], key, only_once(function (err) { if (err) { callback(err); } else { key = nextKey(); if (key === null) { return callback(null); } else { if (sync) { async.setImmediate(iterate); } else { iterate(); } } } })); sync = false; } iterate(); }; async.forEachOfLimit = async.eachOfLimit = function (obj, limit, iterator, callback) { _eachOfLimit(limit)(obj, iterator, callback); }; function _eachOfLimit(limit) { return function (obj, iterator, callback) { callback = _once(callback || noop); obj = obj || []; var nextKey = _keyIterator(obj); if (limit <= 0) { return callback(null); } var done = false; var running = 0; var errored = false; (function replenish () { if (done && running <= 0) { return callback(null); } while (running < limit && !errored) { var key = nextKey(); if (key === null) { done = true; if (running <= 0) { callback(null); } return; } running += 1; iterator(obj[key], key, only_once(function (err) { running -= 1; if (err) { callback(err); errored = true; } else { replenish(); } })); } })(); }; } function doParallel(fn) { return function (obj, iterator, callback) { return fn(async.eachOf, obj, iterator, callback); }; } function doParallelLimit(fn) { return function (obj, limit, iterator, callback) { return fn(_eachOfLimit(limit), obj, iterator, callback); }; } function doSeries(fn) { return function (obj, iterator, callback) { return fn(async.eachOfSeries, obj, iterator, callback); }; } function _asyncMap(eachfn, arr, iterator, callback) { callback = _once(callback || noop); arr = arr || []; var results = _isArrayLike(arr) ? [] : {}; eachfn(arr, function (value, index, callback) { iterator(value, function (err, v) { results[index] = v; callback(err); }); }, function (err) { callback(err, results); }); } async.map = doParallel(_asyncMap); async.mapSeries = doSeries(_asyncMap); async.mapLimit = doParallelLimit(_asyncMap); // reduce only has a series version, as doing reduce in parallel won't // work in many situations. async.inject = async.foldl = async.reduce = function (arr, memo, iterator, callback) { async.eachOfSeries(arr, function (x, i, callback) { iterator(memo, x, function (err, v) { memo = v; callback(err); }); }, function (err) { callback(err, memo); }); }; async.foldr = async.reduceRight = function (arr, memo, iterator, callback) { var reversed = _map(arr, identity).reverse(); async.reduce(reversed, memo, iterator, callback); }; async.transform = function (arr, memo, iterator, callback) { if (arguments.length === 3) { callback = iterator; iterator = memo; memo = _isArray(arr) ? [] : {}; } async.eachOf(arr, function(v, k, cb) { iterator(memo, v, k, cb); }, function(err) { callback(err, memo); }); }; function _filter(eachfn, arr, iterator, callback) { var results = []; eachfn(arr, function (x, index, callback) { iterator(x, function (v) { if (v) { results.push({index: index, value: x}); } callback(); }); }, function () { callback(_map(results.sort(function (a, b) { return a.index - b.index; }), function (x) { return x.value; })); }); } async.select = async.filter = doParallel(_filter); async.selectLimit = async.filterLimit = doParallelLimit(_filter); async.selectSeries = async.filterSeries = doSeries(_filter); function _reject(eachfn, arr, iterator, callback) { _filter(eachfn, arr, function(value, cb) { iterator(value, function(v) { cb(!v); }); }, callback); } async.reject = doParallel(_reject); async.rejectLimit = doParallelLimit(_reject); async.rejectSeries = doSeries(_reject); function _createTester(eachfn, check, getResult) { return function(arr, limit, iterator, cb) { function done() { if (cb) cb(getResult(false, void 0)); } function iteratee(x, _, callback) { if (!cb) return callback(); iterator(x, function (v) { if (cb && check(v)) { cb(getResult(true, x)); cb = iterator = false; } callback(); }); } if (arguments.length > 3) { eachfn(arr, limit, iteratee, done); } else { cb = iterator; iterator = limit; eachfn(arr, iteratee, done); } }; } async.any = async.some = _createTester(async.eachOf, toBool, identity); async.someLimit = _createTester(async.eachOfLimit, toBool, identity); async.all = async.every = _createTester(async.eachOf, notId, notId); async.everyLimit = _createTester(async.eachOfLimit, notId, notId); function _findGetResult(v, x) { return x; } async.detect = _createTester(async.eachOf, identity, _findGetResult); async.detectSeries = _createTester(async.eachOfSeries, identity, _findGetResult); async.detectLimit = _createTester(async.eachOfLimit, identity, _findGetResult); async.sortBy = function (arr, iterator, callback) { async.map(arr, function (x, callback) { iterator(x, function (err, criteria) { if (err) { callback(err); } else { callback(null, {value: x, criteria: criteria}); } }); }, function (err, results) { if (err) { return callback(err); } else { callback(null, _map(results.sort(comparator), function (x) { return x.value; })); } }); function comparator(left, right) { var a = left.criteria, b = right.criteria; return a < b ? -1 : a > b ? 1 : 0; } }; async.auto = function (tasks, concurrency, callback) { if (typeof arguments[1] === 'function') { // concurrency is optional, shift the args. callback = concurrency; concurrency = null; } callback = _once(callback || noop); var keys = _keys(tasks); var remainingTasks = keys.length; if (!remainingTasks) { return callback(null); } if (!concurrency) { concurrency = remainingTasks; } var results = {}; var runningTasks = 0; var hasError = false; var listeners = []; function addListener(fn) { listeners.unshift(fn); } function removeListener(fn) { var idx = _indexOf(listeners, fn); if (idx >= 0) listeners.splice(idx, 1); } function taskComplete() { remainingTasks--; _arrayEach(listeners.slice(0), function (fn) { fn(); }); } addListener(function () { if (!remainingTasks) { callback(null, results); } }); _arrayEach(keys, function (k) { if (hasError) return; var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]]; var taskCallback = _restParam(function(err, args) { runningTasks--; if (args.length <= 1) { args = args[0]; } if (err) { var safeResults = {}; _forEachOf(results, function(val, rkey) { safeResults[rkey] = val; }); safeResults[k] = args; hasError = true; callback(err, safeResults); } else { results[k] = args; async.setImmediate(taskComplete); } }); var requires = task.slice(0, task.length - 1); // prevent dead-locks var len = requires.length; var dep; while (len--) { if (!(dep = tasks[requires[len]])) { throw new Error('Has nonexistent dependency in ' + requires.join(', ')); } if (_isArray(dep) && _indexOf(dep, k) >= 0) { throw new Error('Has cyclic dependencies'); } } function ready() { return runningTasks < concurrency && _reduce(requires, function (a, x) { return (a && results.hasOwnProperty(x)); }, true) && !results.hasOwnProperty(k); } if (ready()) { runningTasks++; task[task.length - 1](taskCallback, results); } else { addListener(listener); } function listener() { if (ready()) { runningTasks++; removeListener(listener); task[task.length - 1](taskCallback, results); } } }); }; async.retry = function(times, task, callback) { var DEFAULT_TIMES = 5; var DEFAULT_INTERVAL = 0; var attempts = []; var opts = { times: DEFAULT_TIMES, interval: DEFAULT_INTERVAL }; function parseTimes(acc, t){ if(typeof t === 'number'){ acc.times = parseInt(t, 10) || DEFAULT_TIMES; } else if(typeof t === 'object'){ acc.times = parseInt(t.times, 10) || DEFAULT_TIMES; acc.interval = parseInt(t.interval, 10) || DEFAULT_INTERVAL; } else { throw new Error('Unsupported argument type for \'times\': ' + typeof t); } } var length = arguments.length; if (length < 1 || length > 3) { throw new Error('Invalid arguments - must be either (task), (task, callback), (times, task) or (times, task, callback)'); } else if (length <= 2 && typeof times === 'function') { callback = task; task = times; } if (typeof times !== 'function') { parseTimes(opts, times); } opts.callback = callback; opts.task = task; function wrappedTask(wrappedCallback, wrappedResults) { function retryAttempt(task, finalAttempt) { return function(seriesCallback) { task(function(err, result){ seriesCallback(!err || finalAttempt, {err: err, result: result}); }, wrappedResults); }; } function retryInterval(interval){ return function(seriesCallback){ setTimeout(function(){ seriesCallback(null); }, interval); }; } while (opts.times) { var finalAttempt = !(opts.times-=1); attempts.push(retryAttempt(opts.task, finalAttempt)); if(!finalAttempt && opts.interval > 0){ attempts.push(retryInterval(opts.interval)); } } async.series(attempts, function(done, data){ data = data[data.length - 1]; (wrappedCallback || opts.callback)(data.err, data.result); }); } // If a callback is passed, run this as a controll flow return opts.callback ? wrappedTask() : wrappedTask; }; async.waterfall = function (tasks, callback) { callback = _once(callback || noop); if (!_isArray(tasks)) { var err = new Error('First argument to waterfall must be an array of functions'); return callback(err); } if (!tasks.length) { return callback(); } function wrapIterator(iterator) { return _restParam(function (err, args) { if (err) { callback.apply(null, [err].concat(args)); } else { var next = iterator.next(); if (next) { args.push(wrapIterator(next)); } else { args.push(callback); } ensureAsync(iterator).apply(null, args); } }); } wrapIterator(async.iterator(tasks))(); }; function _parallel(eachfn, tasks, callback) { callback = callback || noop; var results = _isArrayLike(tasks) ? [] : {}; eachfn(tasks, function (task, key, callback) { task(_restParam(function (err, args) { if (args.length <= 1) { args = args[0]; } results[key] = args; callback(err); })); }, function (err) { callback(err, results); }); } async.parallel = function (tasks, callback) { _parallel(async.eachOf, tasks, callback); }; async.parallelLimit = function(tasks, limit, callback) { _parallel(_eachOfLimit(limit), tasks, callback); }; async.series = function(tasks, callback) { _parallel(async.eachOfSeries, tasks, callback); }; async.iterator = function (tasks) { function makeCallback(index) { function fn() { if (tasks.length) { tasks[index].apply(null, arguments); } return fn.next(); } fn.next = function () { return (index < tasks.length - 1) ? makeCallback(index + 1): null; }; return fn; } return makeCallback(0); }; async.apply = _restParam(function (fn, args) { return _restParam(function (callArgs) { return fn.apply( null, args.concat(callArgs) ); }); }); function _concat(eachfn, arr, fn, callback) { var result = []; eachfn(arr, function (x, index, cb) { fn(x, function (err, y) { result = result.concat(y || []); cb(err); }); }, function (err) { callback(err, result); }); } async.concat = doParallel(_concat); async.concatSeries = doSeries(_concat); async.whilst = function (test, iterator, callback) { callback = callback || noop; if (test()) { var next = _restParam(function(err, args) { if (err) { callback(err); } else if (test.apply(this, args)) { iterator(next); } else { callback.apply(null, [null].concat(args)); } }); iterator(next); } else { callback(null); } }; async.doWhilst = function (iterator, test, callback) { var calls = 0; return async.whilst(function() { return ++calls <= 1 || test.apply(this, arguments); }, iterator, callback); }; async.until = function (test, iterator, callback) { return async.whilst(function() { return !test.apply(this, arguments); }, iterator, callback); }; async.doUntil = function (iterator, test, callback) { return async.doWhilst(iterator, function() { return !test.apply(this, arguments); }, callback); }; async.during = function (test, iterator, callback) { callback = callback || noop; var next = _restParam(function(err, args) { if (err) { callback(err); } else { args.push(check); test.apply(this, args); } }); var check = function(err, truth) { if (err) { callback(err); } else if (truth) { iterator(next); } else { callback(null); } }; test(check); }; async.doDuring = function (iterator, test, callback) { var calls = 0; async.during(function(next) { if (calls++ < 1) { next(null, true); } else { test.apply(this, arguments); } }, iterator, callback); }; function _queue(worker, concurrency, payload) { if (concurrency == null) { concurrency = 1; } else if(concurrency === 0) { throw new Error('Concurrency must not be zero'); } function _insert(q, data, pos, callback) { if (callback != null && typeof callback !== "function") { throw new Error("task callback must be a function"); } q.started = true; if (!_isArray(data)) { data = [data]; } if(data.length === 0 && q.idle()) { // call drain immediately if there are no tasks return async.setImmediate(function() { q.drain(); }); } _arrayEach(data, function(task) { var item = { data: task, callback: callback || noop }; if (pos) { q.tasks.unshift(item); } else { q.tasks.push(item); } if (q.tasks.length === q.concurrency) { q.saturated(); } }); async.setImmediate(q.process); } function _next(q, tasks) { return function(){ workers -= 1; var removed = false; var args = arguments; _arrayEach(tasks, function (task) { _arrayEach(workersList, function (worker, index) { if (worker === task && !removed) { workersList.splice(index, 1); removed = true; } }); task.callback.apply(task, args); }); if (q.tasks.length + workers === 0) { q.drain(); } q.process(); }; } var workers = 0; var workersList = []; var q = { tasks: [], concurrency: concurrency, payload: payload, saturated: noop, empty: noop, drain: noop, started: false, paused: false, push: function (data, callback) { _insert(q, data, false, callback); }, kill: function () { q.drain = noop; q.tasks = []; }, unshift: function (data, callback) { _insert(q, data, true, callback); }, process: function () { while(!q.paused && workers < q.concurrency && q.tasks.length){ var tasks = q.payload ? q.tasks.splice(0, q.payload) : q.tasks.splice(0, q.tasks.length); var data = _map(tasks, function (task) { return task.data; }); if (q.tasks.length === 0) { q.empty(); } workers += 1; workersList.push(tasks[0]); var cb = only_once(_next(q, tasks)); worker(data, cb); } }, length: function () { return q.tasks.length; }, running: function () { return workers; }, workersList: function () { return workersList; }, idle: function() { return q.tasks.length + workers === 0; }, pause: function () { q.paused = true; }, resume: function () { if (q.paused === false) { return; } q.paused = false; var resumeCount = Math.min(q.concurrency, q.tasks.length); // Need to call q.process once per concurrent // worker to preserve full concurrency after pause for (var w = 1; w <= resumeCount; w++) { async.setImmediate(q.process); } } }; return q; } async.queue = function (worker, concurrency) { var q = _queue(function (items, cb) { worker(items[0], cb); }, concurrency, 1); return q; }; async.priorityQueue = function (worker, concurrency) { function _compareTasks(a, b){ return a.priority - b.priority; } function _binarySearch(sequence, item, compare) { var beg = -1, end = sequence.length - 1; while (beg < end) { var mid = beg + ((end - beg + 1) >>> 1); if (compare(item, sequence[mid]) >= 0) { beg = mid; } else { end = mid - 1; } } return beg; } function _insert(q, data, priority, callback) { if (callback != null && typeof callback !== "function") { throw new Error("task callback must be a function"); } q.started = true; if (!_isArray(data)) { data = [data]; } if(data.length === 0) { // call drain immediately if there are no tasks return async.setImmediate(function() { q.drain(); }); } _arrayEach(data, function(task) { var item = { data: task, priority: priority, callback: typeof callback === 'function' ? callback : noop }; q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item); if (q.tasks.length === q.concurrency) { q.saturated(); } async.setImmediate(q.process); }); } // Start with a normal queue var q = async.queue(worker, concurrency); // Override push to accept second parameter representing priority q.push = function (data, priority, callback) { _insert(q, data, priority, callback); }; // Remove unshift function delete q.unshift; return q; }; async.cargo = function (worker, payload) { return _queue(worker, 1, payload); }; function _console_fn(name) { return _restParam(function (fn, args) { fn.apply(null, args.concat([_restParam(function (err, args) { if (typeof console === 'object') { if (err) { if (console.error) { console.error(err); } } else if (console[name]) { _arrayEach(args, function (x) { console[name](x); }); } } })])); }); } async.log = _console_fn('log'); async.dir = _console_fn('dir'); /*async.info = _console_fn('info'); async.warn = _console_fn('warn'); async.error = _console_fn('error');*/ async.memoize = function (fn, hasher) { var memo = {}; var queues = {}; var has = Object.prototype.hasOwnProperty; hasher = hasher || identity; var memoized = _restParam(function memoized(args) { var callback = args.pop(); var key = hasher.apply(null, args); if (has.call(memo, key)) { async.setImmediate(function () { callback.apply(null, memo[key]); }); } else if (has.call(queues, key)) { queues[key].push(callback); } else { queues[key] = [callback]; fn.apply(null, args.concat([_restParam(function (args) { memo[key] = args; var q = queues[key]; delete queues[key]; for (var i = 0, l = q.length; i < l; i++) { q[i].apply(null, args); } })])); } }); memoized.memo = memo; memoized.unmemoized = fn; return memoized; }; async.unmemoize = function (fn) { return function () { return (fn.unmemoized || fn).apply(null, arguments); }; }; function _times(mapper) { return function (count, iterator, callback) { mapper(_range(count), iterator, callback); }; } async.times = _times(async.map); async.timesSeries = _times(async.mapSeries); async.timesLimit = function (count, limit, iterator, callback) { return async.mapLimit(_range(count), limit, iterator, callback); }; async.seq = function (/* functions... */) { var fns = arguments; return _restParam(function (args) { var that = this; var callback = args[args.length - 1]; if (typeof callback == 'function') { args.pop(); } else { callback = noop; } async.reduce(fns, args, function (newargs, fn, cb) { fn.apply(that, newargs.concat([_restParam(function (err, nextargs) { cb(err, nextargs); })])); }, function (err, results) { callback.apply(that, [err].concat(results)); }); }); }; async.compose = function (/* functions... */) { return async.seq.apply(null, Array.prototype.reverse.call(arguments)); }; function _applyEach(eachfn) { return _restParam(function(fns, args) { var go = _restParam(function(args) { var that = this; var callback = args.pop(); return eachfn(fns, function (fn, _, cb) { fn.apply(that, args.concat([cb])); }, callback); }); if (args.length) { return go.apply(this, args); } else { return go; } }); } async.applyEach = _applyEach(async.eachOf); async.applyEachSeries = _applyEach(async.eachOfSeries); async.forever = function (fn, callback) { var done = only_once(callback || noop); var task = ensureAsync(fn); function next(err) { if (err) { return done(err); } task(next); } next(); }; function ensureAsync(fn) { return _restParam(function (args) { var callback = args.pop(); args.push(function () { var innerArgs = arguments; if (sync) { async.setImmediate(function () { callback.apply(null, innerArgs); }); } else { callback.apply(null, innerArgs); } }); var sync = true; fn.apply(this, args); sync = false; }); } async.ensureAsync = ensureAsync; async.constant = _restParam(function(values) { var args = [null].concat(values); return function (callback) { return callback.apply(this, args); }; }); async.wrapSync = async.asyncify = function asyncify(func) { return _restParam(function (args) { var callback = args.pop(); var result; try { result = func.apply(this, args); } catch (e) { return callback(e); } // if result is Promise object if (_isObject(result) && typeof result.then === "function") { result.then(function(value) { callback(null, value); })["catch"](function(err) { callback(err.message ? err : new Error(err)); }); } else { callback(null, result); } }); }; // Node.js if (typeof module === 'object' && module.exports) { module.exports = async; } // AMD / RequireJS else if (typeof define === 'function' && define.amd) { define([], function () { return async; }); } // included directly via <script> tag else { root.async = async; } }()); }).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"_process":98}],43:[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":44,"./core":45,"./enc-base64":46,"./evpkdf":48,"./md5":53}],44:[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":45}],45:[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; })); },{}],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; /** * Base64 encoding strategy. */ var Base64 = C_enc.Base64 = { /** * Converts a word array to a Base64 string. * * @param {WordArray} wordArray The word array. * * @return {string} The Base64 string. * * @static * * @example * * var base64String = CryptoJS.enc.Base64.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; var map = this._map; // Clamp excess bits wordArray.clamp(); // Convert var base64Chars = []; for (var i = 0; i < sigBytes; i += 3) { var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff; var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff; var triplet = (byte1 << 16) | (byte2 << 8) | byte3; for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) { base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f)); } } // Add padding var paddingChar = map.charAt(64); if (paddingChar) { while (base64Chars.length % 4) { base64Chars.push(paddingChar); } } return base64Chars.join(''); }, /** * Converts a Base64 string to a word array. * * @param {string} base64Str The Base64 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Base64.parse(base64String); */ parse: function (base64Str) { // Shortcuts var base64StrLength = base64Str.length; var map = this._map; // Ignore padding var paddingChar = map.charAt(64); if (paddingChar) { var paddingIndex = base64Str.indexOf(paddingChar); if (paddingIndex != -1) { base64StrLength = paddingIndex; } } // Convert var words = []; var nBytes = 0; for (var i = 0; i < base64StrLength; i++) { if (i % 4) { var bits1 = map.indexOf(base64Str.charAt(i - 1)) << ((i % 4) * 2); var bits2 = map.indexOf(base64Str.charAt(i)) >>> (6 - (i % 4) * 2); var bitsCombined = bits1 | bits2; words[nBytes >>> 2] |= (bitsCombined) << (24 - (nBytes % 4) * 8); nBytes++; } } return WordArray.create(words, nBytes); }, _map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=' }; }()); return CryptoJS.enc.Base64; })); },{"./core":45}],47:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // 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":45}],48:[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":45,"./hmac":50,"./sha1":69}],49:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (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":44,"./core":45}],50:[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":45}],51:[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":43,"./cipher-core":44,"./core":45,"./enc-base64":46,"./enc-utf16":47,"./evpkdf":48,"./format-hex":49,"./hmac":50,"./lib-typedarrays":52,"./md5":53,"./mode-cfb":54,"./mode-ctr":56,"./mode-ctr-gladman":55,"./mode-ecb":57,"./mode-ofb":58,"./pad-ansix923":59,"./pad-iso10126":60,"./pad-iso97971":61,"./pad-nopadding":62,"./pad-zeropadding":63,"./pbkdf2":64,"./rabbit":66,"./rabbit-legacy":65,"./rc4":67,"./ripemd160":68,"./sha1":69,"./sha224":70,"./sha256":71,"./sha3":72,"./sha384":73,"./sha512":74,"./tripledes":75,"./x64-core":76}],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 () { // 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":45}],53:[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":45}],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) { /** * 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":44,"./core":45}],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) { /** @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":44,"./core":45}],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) { /** * 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":44,"./core":45}],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) { /** * 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":44,"./core":45}],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) { /** * 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":44,"./core":45}],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) { /** * 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":44,"./core":45}],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 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":44,"./core":45}],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) { /** * 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":44,"./core":45}],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) { /** * A noop padding strategy. */ CryptoJS.pad.NoPadding = { pad: function () { }, unpad: function () { } }; return CryptoJS.pad.NoPadding; })); },{"./cipher-core":44,"./core":45}],63:[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":44,"./core":45}],64:[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":45,"./hmac":50,"./sha1":69}],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. * * 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":44,"./core":45,"./enc-base64":46,"./evpkdf":48,"./md5":53}],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; // 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":44,"./core":45,"./enc-base64":46,"./evpkdf":48,"./md5":53}],67:[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":44,"./core":45,"./enc-base64":46,"./evpkdf":48,"./md5":53}],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) { /** @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":45}],69:[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":45}],70:[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":45,"./sha256":71}],71:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (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":45}],72:[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":45,"./x64-core":76}],73:[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":45,"./sha512":74,"./x64-core":76}],74:[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":45,"./x64-core":76}],75:[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":44,"./core":45,"./enc-base64":46,"./evpkdf":48,"./md5":53}],76:[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":45}],77:[function(_dereq_,module,exports){ // Some code originally from async_storage.js in // [Gaia](https://github.com/mozilla-b2g/gaia). (function() { 'use strict'; // Originally found in https://github.com/mozilla-b2g/gaia/blob/e8f624e4cc9ea945727278039b3bc9bcb9f8667a/shared/js/async_storage.js // Promises! var Promise = (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') ? _dereq_('promise') : this.Promise; // Initialize IndexedDB; fall back to vendor-prefixed versions if needed. var indexedDB = indexedDB || this.indexedDB || this.webkitIndexedDB || this.mozIndexedDB || this.OIndexedDB || this.msIndexedDB; // If IndexedDB isn't available, we get outta here! if (!indexedDB) { return; } var DETECT_BLOB_SUPPORT_STORE = 'local-forage-detect-blob-support'; var supportsBlobs; // Abstracts constructing a Blob object, so it also works in older // browsers that don't support the native Blob constructor. (i.e. // old QtWebKit versions, at least). function _createBlob(parts, properties) { parts = parts || []; properties = properties || {}; try { return new Blob(parts, properties); } catch (e) { if (e.name !== 'TypeError') { throw e; } var BlobBuilder = window.BlobBuilder || window.MSBlobBuilder || window.MozBlobBuilder || window.WebKitBlobBuilder; var builder = new BlobBuilder(); for (var i = 0; i < parts.length; i += 1) { builder.append(parts[i]); } return builder.getBlob(properties.type); } } // Transform a binary string to an array buffer, because otherwise // weird stuff happens when you try to work with the binary string directly. // It is known. // From http://stackoverflow.com/questions/14967647/ (continues on next line) // encode-decode-image-with-base64-breaks-image (2013-04-21) function _binStringToArrayBuffer(bin) { var length = bin.length; var buf = new ArrayBuffer(length); var arr = new Uint8Array(buf); for (var i = 0; i < length; i++) { arr[i] = bin.charCodeAt(i); } return buf; } // Fetch a blob using ajax. This reveals bugs in Chrome < 43. // For details on all this junk: // https://github.com/nolanlawson/state-of-binary-data-in-the-browser#readme function _blobAjax(url) { return new Promise(function(resolve, reject) { var xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.withCredentials = true; xhr.responseType = 'arraybuffer'; xhr.onreadystatechange = function() { if (xhr.readyState !== 4) { return; } if (xhr.status === 200) { return resolve({ response: xhr.response, type: xhr.getResponseHeader('Content-Type') }); } reject({status: xhr.status, response: xhr.response}); }; xhr.send(); }); } // // Detect blob support. Chrome didn't support it until version 38. // In version 37 they had a broken version where PNGs (and possibly // other binary types) aren't stored correctly, because when you fetch // them, the content type is always null. // // Furthermore, they have some outstanding bugs where blobs occasionally // are read by FileReader as null, or by ajax as 404s. // // Sadly we use the 404 bug to detect the FileReader bug, so if they // get fixed independently and released in different versions of Chrome, // then the bug could come back. So it's worthwhile to watch these issues: // 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916 // FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836 // function _checkBlobSupportWithoutCaching(idb) { return new Promise(function(resolve, reject) { var blob = _createBlob([''], {type: 'image/png'}); var txn = idb.transaction([DETECT_BLOB_SUPPORT_STORE], 'readwrite'); txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, 'key'); txn.oncomplete = function() { // have to do it in a separate transaction, else the correct // content type is always returned var blobTxn = idb.transaction([DETECT_BLOB_SUPPORT_STORE], 'readwrite'); var getBlobReq = blobTxn.objectStore( DETECT_BLOB_SUPPORT_STORE).get('key'); getBlobReq.onerror = reject; getBlobReq.onsuccess = function(e) { var storedBlob = e.target.result; var url = URL.createObjectURL(storedBlob); _blobAjax(url).then(function(res) { resolve(!!(res && res.type === 'image/png')); }, function() { resolve(false); }).then(function() { URL.revokeObjectURL(url); }); }; }; })['catch'](function() { return false; // error, so assume unsupported }); } function _checkBlobSupport(idb) { if (typeof supportsBlobs === 'boolean') { return Promise.resolve(supportsBlobs); } return _checkBlobSupportWithoutCaching(idb).then(function(value) { supportsBlobs = value; return supportsBlobs; }); } // encode a blob for indexeddb engines that don't support blobs function _encodeBlob(blob) { return new Promise(function(resolve, reject) { var reader = new FileReader(); reader.onerror = reject; reader.onloadend = function(e) { var base64 = btoa(e.target.result || ''); resolve({ __local_forage_encoded_blob: true, data: base64, type: blob.type }); }; reader.readAsBinaryString(blob); }); } // decode an encoded blob function _decodeBlob(encodedBlob) { var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data)); return _createBlob([arrayBuff], { type: encodedBlob.type}); } // is this one of our fancy encoded blobs? function _isEncodedBlob(value) { return value && value.__local_forage_encoded_blob; } // Open the IndexedDB database (automatically creates one if one didn't // previously exist), using any options set in the config. function _initStorage(options) { var self = this; var dbInfo = { db: null }; if (options) { for (var i in options) { dbInfo[i] = options[i]; } } return new Promise(function(resolve, reject) { var openreq = indexedDB.open(dbInfo.name, dbInfo.version); openreq.onerror = function() { reject(openreq.error); }; openreq.onupgradeneeded = function(e) { // First time setup: create an empty object store openreq.result.createObjectStore(dbInfo.storeName); if (e.oldVersion <= 1) { // added when support for blob shims was added openreq.result.createObjectStore(DETECT_BLOB_SUPPORT_STORE); } }; openreq.onsuccess = function() { dbInfo.db = openreq.result; self._dbInfo = dbInfo; resolve(); }; }); } function getItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly') .objectStore(dbInfo.storeName); var req = store.get(key); req.onsuccess = function() { var value = req.result; if (value === undefined) { value = null; } if (_isEncodedBlob(value)) { value = _decodeBlob(value); } resolve(value); }; req.onerror = function() { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } // Iterate over all items stored in database. function iterate(iterator, callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly') .objectStore(dbInfo.storeName); var req = store.openCursor(); var iterationNumber = 1; req.onsuccess = function() { var cursor = req.result; if (cursor) { var value = cursor.value; if (_isEncodedBlob(value)) { value = _decodeBlob(value); } var result = iterator(value, cursor.key, iterationNumber++); if (result !== void(0)) { resolve(result); } else { cursor['continue'](); } } else { resolve(); } }; req.onerror = function() { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function setItem(key, value, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function(resolve, reject) { var dbInfo; self.ready().then(function() { dbInfo = self._dbInfo; return _checkBlobSupport(dbInfo.db); }).then(function(blobSupport) { if (!blobSupport && value instanceof Blob) { return _encodeBlob(value); } return value; }).then(function(value) { var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); var store = transaction.objectStore(dbInfo.storeName); // The reason we don't _save_ null is because IE 10 does // not support saving the `null` type in IndexedDB. How // ironic, given the bug below! // See: https://github.com/mozilla/localForage/issues/161 if (value === null) { value = undefined; } var req = store.put(value, key); transaction.oncomplete = function() { // Cast to undefined so the value passed to // callback/promise is the same as what one would get out // of `getItem()` later. This leads to some weirdness // (setItem('foo', undefined) will return `null`), but // it's not my fault localStorage is our baseline and that // it's weird. if (value === undefined) { value = null; } resolve(value); }; transaction.onabort = transaction.onerror = function() { var err = req.error ? req.error : req.transaction.error; reject(err); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function removeItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); var store = transaction.objectStore(dbInfo.storeName); // We use a Grunt task to make this safe for IE and some // versions of Android (including those used by Cordova). // Normally IE won't like `['delete']()` and will insist on // using `['delete']()`, but we have a build step that // fixes this for us now. var req = store['delete'](key); transaction.oncomplete = function() { resolve(); }; transaction.onerror = function() { reject(req.error); }; // The request will be also be aborted if we've exceeded our storage // space. transaction.onabort = function() { var err = req.error ? req.error : req.transaction.error; reject(err); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function clear(callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); var store = transaction.objectStore(dbInfo.storeName); var req = store.clear(); transaction.oncomplete = function() { resolve(); }; transaction.onabort = transaction.onerror = function() { var err = req.error ? req.error : req.transaction.error; reject(err); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function length(callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly') .objectStore(dbInfo.storeName); var req = store.count(); req.onsuccess = function() { resolve(req.result); }; req.onerror = function() { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function key(n, callback) { var self = this; var promise = new Promise(function(resolve, reject) { if (n < 0) { resolve(null); return; } self.ready().then(function() { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly') .objectStore(dbInfo.storeName); var advanced = false; var req = store.openCursor(); req.onsuccess = function() { var cursor = req.result; if (!cursor) { // this means there weren't enough keys resolve(null); return; } if (n === 0) { // We have the first key, return it if that's what they // wanted. resolve(cursor.key); } else { if (!advanced) { // Otherwise, ask the cursor to skip ahead n // records. advanced = true; cursor.advance(n); } else { // When we get here, we've got the nth key. resolve(cursor.key); } } }; req.onerror = function() { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function keys(callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly') .objectStore(dbInfo.storeName); var req = store.openCursor(); var keys = []; req.onsuccess = function() { var cursor = req.result; if (!cursor) { resolve(keys); return; } keys.push(cursor.key); cursor['continue'](); }; req.onerror = function() { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function executeCallback(promise, callback) { if (callback) { promise.then(function(result) { callback(null, result); }, function(error) { callback(error); }); } } var asyncStorage = { _driver: 'asyncStorage', _initStorage: _initStorage, iterate: iterate, getItem: getItem, setItem: setItem, removeItem: removeItem, clear: clear, length: length, key: key, keys: keys }; if (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') { module.exports = asyncStorage; } else if (typeof define === 'function' && define.amd) { define('asyncStorage', function() { return asyncStorage; }); } else { this.asyncStorage = asyncStorage; } }).call(window); },{"promise":100}],78:[function(_dereq_,module,exports){ // If IndexedDB isn't available, we'll fall back to localStorage. // Note that this will have considerable performance and storage // side-effects (all data will be serialized on save and only data that // can be converted to a string via `JSON.stringify()` will be saved). (function() { 'use strict'; // Promises! var Promise = (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') ? _dereq_('promise') : this.Promise; var globalObject = this; var serializer = null; var localStorage = null; // If the app is running inside a Google Chrome packaged webapp, or some // other context where localStorage isn't available, we don't use // localStorage. This feature detection is preferred over the old // `if (window.chrome && window.chrome.runtime)` code. // See: https://github.com/mozilla/localForage/issues/68 try { // If localStorage isn't available, we get outta here! // This should be inside a try catch if (!this.localStorage || !('setItem' in this.localStorage)) { return; } // Initialize localStorage and create a variable to use throughout // the code. localStorage = this.localStorage; } catch (e) { return; } var ModuleType = { DEFINE: 1, EXPORT: 2, WINDOW: 3 }; // Attaching to window (i.e. no module loader) is the assumed, // simple default. var moduleType = ModuleType.WINDOW; // Find out what kind of module setup we have; if none, we'll just attach // localForage to the main window. if (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') { moduleType = ModuleType.EXPORT; } else if (typeof define === 'function' && define.amd) { moduleType = ModuleType.DEFINE; } // Config the localStorage backend, using options set in the config. function _initStorage(options) { var self = this; var dbInfo = {}; if (options) { for (var i in options) { dbInfo[i] = options[i]; } } dbInfo.keyPrefix = dbInfo.name + '/'; self._dbInfo = dbInfo; var serializerPromise = new Promise(function(resolve/*, reject*/) { // We allow localForage to be declared as a module or as a // library available without AMD/require.js. if (moduleType === ModuleType.DEFINE) { _dereq_(['localforageSerializer'], resolve); } else if (moduleType === ModuleType.EXPORT) { // Making it browserify friendly resolve(_dereq_('./../utils/serializer')); } else { resolve(globalObject.localforageSerializer); } }); return serializerPromise.then(function(lib) { serializer = lib; return Promise.resolve(); }); } // Remove all keys from the datastore, effectively destroying all data in // the app's key/value store! function clear(callback) { var self = this; var promise = self.ready().then(function() { var keyPrefix = self._dbInfo.keyPrefix; for (var i = localStorage.length - 1; i >= 0; i--) { var key = localStorage.key(i); if (key.indexOf(keyPrefix) === 0) { localStorage.removeItem(key); } } }); executeCallback(promise, callback); return promise; } // Retrieve an item from the store. Unlike the original async_storage // library in Gaia, we don't modify return values at all. If a key's value // is `undefined`, we pass that value to the callback function. function getItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = self.ready().then(function() { var dbInfo = self._dbInfo; var result = localStorage.getItem(dbInfo.keyPrefix + key); // If a result was found, parse it from the serialized // string into a JS object. If result isn't truthy, the key // is likely undefined and we'll pass it straight to the // callback. if (result) { result = serializer.deserialize(result); } return result; }); executeCallback(promise, callback); return promise; } // Iterate over all items in the store. function iterate(iterator, callback) { var self = this; var promise = self.ready().then(function() { var keyPrefix = self._dbInfo.keyPrefix; var keyPrefixLength = keyPrefix.length; var length = localStorage.length; // We use a dedicated iterator instead of the `i` variable below // so other keys we fetch in localStorage aren't counted in // the `iterationNumber` argument passed to the `iterate()` // callback. // // See: github.com/mozilla/localForage/pull/435#discussion_r38061530 var iterationNumber = 1; for (var i = 0; i < length; i++) { var key = localStorage.key(i); if (key.indexOf(keyPrefix) !== 0) { continue; } var value = localStorage.getItem(key); // If a result was found, parse it from the serialized // string into a JS object. If result isn't truthy, the // key is likely undefined and we'll pass it straight // to the iterator. if (value) { value = serializer.deserialize(value); } value = iterator(value, key.substring(keyPrefixLength), iterationNumber++); if (value !== void(0)) { return value; } } }); executeCallback(promise, callback); return promise; } // Same as localStorage's key() method, except takes a callback. function key(n, callback) { var self = this; var promise = self.ready().then(function() { var dbInfo = self._dbInfo; var result; try { result = localStorage.key(n); } catch (error) { result = null; } // Remove the prefix from the key, if a key is found. if (result) { result = result.substring(dbInfo.keyPrefix.length); } return result; }); executeCallback(promise, callback); return promise; } function keys(callback) { var self = this; var promise = self.ready().then(function() { var dbInfo = self._dbInfo; var length = localStorage.length; var keys = []; for (var i = 0; i < length; i++) { if (localStorage.key(i).indexOf(dbInfo.keyPrefix) === 0) { keys.push(localStorage.key(i).substring(dbInfo.keyPrefix.length)); } } return keys; }); executeCallback(promise, callback); return promise; } // Supply the number of keys in the datastore to the callback function. function length(callback) { var self = this; var promise = self.keys().then(function(keys) { return keys.length; }); executeCallback(promise, callback); return promise; } // Remove an item from the store, nice and simple. function removeItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = self.ready().then(function() { var dbInfo = self._dbInfo; localStorage.removeItem(dbInfo.keyPrefix + key); }); executeCallback(promise, callback); return promise; } // Set a key's value and run an optional callback once the value is set. // Unlike Gaia's implementation, the callback function is passed the value, // in case you want to operate on that value only after you're sure it // saved, or something like that. function setItem(key, value, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = self.ready().then(function() { // Convert undefined values to null. // https://github.com/mozilla/localForage/pull/42 if (value === undefined) { value = null; } // Save the original value to pass to the callback. var originalValue = value; return new Promise(function(resolve, reject) { serializer.serialize(value, function(value, error) { if (error) { reject(error); } else { try { var dbInfo = self._dbInfo; localStorage.setItem(dbInfo.keyPrefix + key, value); resolve(originalValue); } catch (e) { // localStorage capacity exceeded. // TODO: Make this a specific error/event. if (e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') { reject(e); } reject(e); } } }); }); }); executeCallback(promise, callback); return promise; } function executeCallback(promise, callback) { if (callback) { promise.then(function(result) { callback(null, result); }, function(error) { callback(error); }); } } var localStorageWrapper = { _driver: 'localStorageWrapper', _initStorage: _initStorage, // Default API, from Gaia/localStorage. iterate: iterate, getItem: getItem, setItem: setItem, removeItem: removeItem, clear: clear, length: length, key: key, keys: keys }; if (moduleType === ModuleType.EXPORT) { module.exports = localStorageWrapper; } else if (moduleType === ModuleType.DEFINE) { define('localStorageWrapper', function() { return localStorageWrapper; }); } else { this.localStorageWrapper = localStorageWrapper; } }).call(window); },{"./../utils/serializer":81,"promise":100}],79:[function(_dereq_,module,exports){ /* * Includes code from: * * base64-arraybuffer * https://github.com/niklasvh/base64-arraybuffer * * Copyright (c) 2012 Niklas von Hertzen * Licensed under the MIT license. */ (function() { 'use strict'; // Promises! var Promise = (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') ? _dereq_('promise') : this.Promise; var globalObject = this; var serializer = null; var openDatabase = this.openDatabase; // If WebSQL methods aren't available, we can stop now. if (!openDatabase) { return; } var ModuleType = { DEFINE: 1, EXPORT: 2, WINDOW: 3 }; // Attaching to window (i.e. no module loader) is the assumed, // simple default. var moduleType = ModuleType.WINDOW; // Find out what kind of module setup we have; if none, we'll just attach // localForage to the main window. if (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') { moduleType = ModuleType.EXPORT; } else if (typeof define === 'function' && define.amd) { moduleType = ModuleType.DEFINE; } // Open the WebSQL database (automatically creates one if one didn't // previously exist), using any options set in the config. function _initStorage(options) { var self = this; var dbInfo = { db: null }; if (options) { for (var i in options) { dbInfo[i] = typeof(options[i]) !== 'string' ? options[i].toString() : options[i]; } } var serializerPromise = new Promise(function(resolve/*, reject*/) { // We allow localForage to be declared as a module or as a // library available without AMD/require.js. if (moduleType === ModuleType.DEFINE) { _dereq_(['localforageSerializer'], resolve); } else if (moduleType === ModuleType.EXPORT) { // Making it browserify friendly resolve(_dereq_('./../utils/serializer')); } else { resolve(globalObject.localforageSerializer); } }); var dbInfoPromise = new Promise(function(resolve, reject) { // Open the database; the openDatabase API will automatically // create it for us if it doesn't exist. try { dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size); } catch (e) { return self.setDriver(self.LOCALSTORAGE).then(function() { return self._initStorage(options); }).then(resolve)['catch'](reject); } // Create our key/value table if it doesn't exist. dbInfo.db.transaction(function(t) { t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName + ' (id INTEGER PRIMARY KEY, key unique, value)', [], function() { self._dbInfo = dbInfo; resolve(); }, function(t, error) { reject(error); }); }); }); return serializerPromise.then(function(lib) { serializer = lib; return dbInfoPromise; }); } function getItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; dbInfo.db.transaction(function(t) { t.executeSql('SELECT * FROM ' + dbInfo.storeName + ' WHERE key = ? LIMIT 1', [key], function(t, results) { var result = results.rows.length ? results.rows.item(0).value : null; // Check to see if this is serialized content we need to // unpack. if (result) { result = serializer.deserialize(result); } resolve(result); }, function(t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function iterate(iterator, callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; dbInfo.db.transaction(function(t) { t.executeSql('SELECT * FROM ' + dbInfo.storeName, [], function(t, results) { var rows = results.rows; var length = rows.length; for (var i = 0; i < length; i++) { var item = rows.item(i); var result = item.value; // Check to see if this is serialized content // we need to unpack. if (result) { result = serializer.deserialize(result); } result = iterator(result, item.key, i + 1); // void(0) prevents problems with redefinition // of `undefined`. if (result !== void(0)) { resolve(result); return; } } resolve(); }, function(t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function setItem(key, value, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function(resolve, reject) { self.ready().then(function() { // The localStorage API doesn't return undefined values in an // "expected" way, so undefined is always cast to null in all // drivers. See: https://github.com/mozilla/localForage/pull/42 if (value === undefined) { value = null; } // Save the original value to pass to the callback. var originalValue = value; serializer.serialize(value, function(value, error) { if (error) { reject(error); } else { var dbInfo = self._dbInfo; dbInfo.db.transaction(function(t) { t.executeSql('INSERT OR REPLACE INTO ' + dbInfo.storeName + ' (key, value) VALUES (?, ?)', [key, value], function() { resolve(originalValue); }, function(t, error) { reject(error); }); }, function(sqlError) { // The transaction failed; check // to see if it's a quota error. if (sqlError.code === sqlError.QUOTA_ERR) { // We reject the callback outright for now, but // it's worth trying to re-run the transaction. // Even if the user accepts the prompt to use // more storage on Safari, this error will // be called. // // TODO: Try to re-run the transaction. reject(sqlError); } }); } }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function removeItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; dbInfo.db.transaction(function(t) { t.executeSql('DELETE FROM ' + dbInfo.storeName + ' WHERE key = ?', [key], function() { resolve(); }, function(t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } // Deletes every item in the table. // TODO: Find out if this resets the AUTO_INCREMENT number. function clear(callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; dbInfo.db.transaction(function(t) { t.executeSql('DELETE FROM ' + dbInfo.storeName, [], function() { resolve(); }, function(t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } // Does a simple `COUNT(key)` to get the number of items stored in // localForage. function length(callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; dbInfo.db.transaction(function(t) { // Ahhh, SQL makes this one soooooo easy. t.executeSql('SELECT COUNT(key) as c FROM ' + dbInfo.storeName, [], function(t, results) { var result = results.rows.item(0).c; resolve(result); }, function(t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } // Return the key located at key index X; essentially gets the key from a // `WHERE id = ?`. This is the most efficient way I can think to implement // this rarely-used (in my experience) part of the API, but it can seem // inconsistent, because we do `INSERT OR REPLACE INTO` on `setItem()`, so // the ID of each key will change every time it's updated. Perhaps a stored // procedure for the `setItem()` SQL would solve this problem? // TODO: Don't change ID on `setItem()`. function key(n, callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; dbInfo.db.transaction(function(t) { t.executeSql('SELECT key FROM ' + dbInfo.storeName + ' WHERE id = ? LIMIT 1', [n + 1], function(t, results) { var result = results.rows.length ? results.rows.item(0).key : null; resolve(result); }, function(t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function keys(callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; dbInfo.db.transaction(function(t) { t.executeSql('SELECT key FROM ' + dbInfo.storeName, [], function(t, results) { var keys = []; for (var i = 0; i < results.rows.length; i++) { keys.push(results.rows.item(i).key); } resolve(keys); }, function(t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function executeCallback(promise, callback) { if (callback) { promise.then(function(result) { callback(null, result); }, function(error) { callback(error); }); } } var webSQLStorage = { _driver: 'webSQLStorage', _initStorage: _initStorage, iterate: iterate, getItem: getItem, setItem: setItem, removeItem: removeItem, clear: clear, length: length, key: key, keys: keys }; if (moduleType === ModuleType.DEFINE) { define('webSQLStorage', function() { return webSQLStorage; }); } else if (moduleType === ModuleType.EXPORT) { module.exports = webSQLStorage; } else { this.webSQLStorage = webSQLStorage; } }).call(window); },{"./../utils/serializer":81,"promise":100}],80:[function(_dereq_,module,exports){ (function() { 'use strict'; // Promises! var Promise = (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') ? _dereq_('promise') : this.Promise; // Custom drivers are stored here when `defineDriver()` is called. // They are shared across all instances of localForage. var CustomDrivers = {}; var DriverType = { INDEXEDDB: 'asyncStorage', LOCALSTORAGE: 'localStorageWrapper', WEBSQL: 'webSQLStorage' }; var DefaultDriverOrder = [ DriverType.INDEXEDDB, DriverType.WEBSQL, DriverType.LOCALSTORAGE ]; var LibraryMethods = [ 'clear', 'getItem', 'iterate', 'key', 'keys', 'length', 'removeItem', 'setItem' ]; var ModuleType = { DEFINE: 1, EXPORT: 2, WINDOW: 3 }; var DefaultConfig = { description: '', driver: DefaultDriverOrder.slice(), name: 'localforage', // Default DB size is _JUST UNDER_ 5MB, as it's the highest size // we can use without a prompt. size: 4980736, storeName: 'keyvaluepairs', version: 1.0 }; // Attaching to window (i.e. no module loader) is the assumed, // simple default. var moduleType = ModuleType.WINDOW; // Find out what kind of module setup we have; if none, we'll just attach // localForage to the main window. if (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') { moduleType = ModuleType.EXPORT; } else if (typeof define === 'function' && define.amd) { moduleType = ModuleType.DEFINE; } // Check to see if IndexedDB is available and if it is the latest // implementation; it's our preferred backend library. We use "_spec_test" // as the name of the database because it's not the one we'll operate on, // but it's useful to make sure its using the right spec. // See: https://github.com/mozilla/localForage/issues/128 var driverSupport = (function(self) { // Initialize IndexedDB; fall back to vendor-prefixed versions // if needed. var indexedDB = indexedDB || self.indexedDB || self.webkitIndexedDB || self.mozIndexedDB || self.OIndexedDB || self.msIndexedDB; var result = {}; result[DriverType.WEBSQL] = !!self.openDatabase; result[DriverType.INDEXEDDB] = !!(function() { // We mimic PouchDB here; just UA test for Safari (which, as of // iOS 8/Yosemite, doesn't properly support IndexedDB). // IndexedDB support is broken and different from Blink's. // This is faster than the test case (and it's sync), so we just // do this. *SIGH* // http://bl.ocks.org/nolanlawson/raw/c83e9039edf2278047e9/ // // We test for openDatabase because IE Mobile identifies itself // as Safari. Oh the lulz... if (typeof self.openDatabase !== 'undefined' && self.navigator && self.navigator.userAgent && /Safari/.test(self.navigator.userAgent) && !/Chrome/.test(self.navigator.userAgent)) { return false; } try { return indexedDB && typeof indexedDB.open === 'function' && // Some Samsung/HTC Android 4.0-4.3 devices // have older IndexedDB specs; if this isn't available // their IndexedDB is too old for us to use. // (Replaces the onupgradeneeded test.) typeof self.IDBKeyRange !== 'undefined'; } catch (e) { return false; } })(); result[DriverType.LOCALSTORAGE] = !!(function() { try { return (self.localStorage && ('setItem' in self.localStorage) && (self.localStorage.setItem)); } catch (e) { return false; } })(); return result; })(this); var isArray = Array.isArray || function(arg) { return Object.prototype.toString.call(arg) === '[object Array]'; }; function callWhenReady(localForageInstance, libraryMethod) { localForageInstance[libraryMethod] = function() { var _args = arguments; return localForageInstance.ready().then(function() { return localForageInstance[libraryMethod].apply(localForageInstance, _args); }); }; } function extend() { for (var i = 1; i < arguments.length; i++) { var arg = arguments[i]; if (arg) { for (var key in arg) { if (arg.hasOwnProperty(key)) { if (isArray(arg[key])) { arguments[0][key] = arg[key].slice(); } else { arguments[0][key] = arg[key]; } } } } } return arguments[0]; } function isLibraryDriver(driverName) { for (var driver in DriverType) { if (DriverType.hasOwnProperty(driver) && DriverType[driver] === driverName) { return true; } } return false; } var globalObject = this; function LocalForage(options) { this._config = extend({}, DefaultConfig, options); this._driverSet = null; this._ready = false; this._dbInfo = null; // Add a stub for each driver API method that delays the call to the // corresponding driver method until localForage is ready. These stubs // will be replaced by the driver methods as soon as the driver is // loaded, so there is no performance impact. for (var i = 0; i < LibraryMethods.length; i++) { callWhenReady(this, LibraryMethods[i]); } this.setDriver(this._config.driver); } LocalForage.prototype.INDEXEDDB = DriverType.INDEXEDDB; LocalForage.prototype.LOCALSTORAGE = DriverType.LOCALSTORAGE; LocalForage.prototype.WEBSQL = DriverType.WEBSQL; // Set any config values for localForage; can be called anytime before // the first API call (e.g. `getItem`, `setItem`). // We loop through options so we don't overwrite existing config // values. LocalForage.prototype.config = function(options) { // If the options argument is an object, we use it to set values. // Otherwise, we return either a specified config value or all // config values. if (typeof(options) === 'object') { // If localforage is ready and fully initialized, we can't set // any new configuration values. Instead, we return an error. if (this._ready) { return new Error("Can't call config() after localforage " + 'has been used.'); } for (var i in options) { if (i === 'storeName') { options[i] = options[i].replace(/\W/g, '_'); } this._config[i] = options[i]; } // after all config options are set and // the driver option is used, try setting it if ('driver' in options && options.driver) { this.setDriver(this._config.driver); } return true; } else if (typeof(options) === 'string') { return this._config[options]; } else { return this._config; } }; // Used to define a custom driver, shared across all instances of // localForage. LocalForage.prototype.defineDriver = function(driverObject, callback, errorCallback) { var defineDriver = new Promise(function(resolve, reject) { try { var driverName = driverObject._driver; var complianceError = new Error( 'Custom driver not compliant; see ' + 'https://mozilla.github.io/localForage/#definedriver' ); var namingError = new Error( 'Custom driver name already in use: ' + driverObject._driver ); // A driver name should be defined and not overlap with the // library-defined, default drivers. if (!driverObject._driver) { reject(complianceError); return; } if (isLibraryDriver(driverObject._driver)) { reject(namingError); return; } var customDriverMethods = LibraryMethods.concat('_initStorage'); for (var i = 0; i < customDriverMethods.length; i++) { var customDriverMethod = customDriverMethods[i]; if (!customDriverMethod || !driverObject[customDriverMethod] || typeof driverObject[customDriverMethod] !== 'function') { reject(complianceError); return; } } var supportPromise = Promise.resolve(true); if ('_support' in driverObject) { if (driverObject._support && typeof driverObject._support === 'function') { supportPromise = driverObject._support(); } else { supportPromise = Promise.resolve(!!driverObject._support); } } supportPromise.then(function(supportResult) { driverSupport[driverName] = supportResult; CustomDrivers[driverName] = driverObject; resolve(); }, reject); } catch (e) { reject(e); } }); defineDriver.then(callback, errorCallback); return defineDriver; }; LocalForage.prototype.driver = function() { return this._driver || null; }; LocalForage.prototype.ready = function(callback) { var self = this; var ready = new Promise(function(resolve, reject) { self._driverSet.then(function() { if (self._ready === null) { self._ready = self._initStorage(self._config); } self._ready.then(resolve, reject); })['catch'](reject); }); ready.then(callback, callback); return ready; }; LocalForage.prototype.setDriver = function(drivers, callback, errorCallback) { var self = this; if (typeof drivers === 'string') { drivers = [drivers]; } this._driverSet = new Promise(function(resolve, reject) { var driverName = self._getFirstSupportedDriver(drivers); var error = new Error('No available storage method found.'); if (!driverName) { self._driverSet = Promise.reject(error); reject(error); return; } self._dbInfo = null; self._ready = null; if (isLibraryDriver(driverName)) { var driverPromise = new Promise(function(resolve/*, reject*/) { // We allow localForage to be declared as a module or as a // library available without AMD/require.js. if (moduleType === ModuleType.DEFINE) { _dereq_([driverName], resolve); } else if (moduleType === ModuleType.EXPORT) { // Making it browserify friendly switch (driverName) { case self.INDEXEDDB: resolve(_dereq_('./drivers/indexeddb')); break; case self.LOCALSTORAGE: resolve(_dereq_('./drivers/localstorage')); break; case self.WEBSQL: resolve(_dereq_('./drivers/websql')); break; } } else { resolve(globalObject[driverName]); } }); driverPromise.then(function(driver) { self._extend(driver); resolve(); }); } else if (CustomDrivers[driverName]) { self._extend(CustomDrivers[driverName]); resolve(); } else { self._driverSet = Promise.reject(error); reject(error); } }); function setDriverToConfig() { self._config.driver = self.driver(); } this._driverSet.then(setDriverToConfig, setDriverToConfig); this._driverSet.then(callback, errorCallback); return this._driverSet; }; LocalForage.prototype.supports = function(driverName) { return !!driverSupport[driverName]; }; LocalForage.prototype._extend = function(libraryMethodsAndProperties) { extend(this, libraryMethodsAndProperties); }; // Used to determine which driver we should use as the backend for this // instance of localForage. LocalForage.prototype._getFirstSupportedDriver = function(drivers) { if (drivers && isArray(drivers)) { for (var i = 0; i < drivers.length; i++) { var driver = drivers[i]; if (this.supports(driver)) { return driver; } } } return null; }; LocalForage.prototype.createInstance = function(options) { return new LocalForage(options); }; // The actual localForage object that we expose as a module or via a // global. It's extended by pulling in one of our other libraries. var localForage = new LocalForage(); // We allow localForage to be declared as a module or as a library // available without AMD/require.js. if (moduleType === ModuleType.DEFINE) { define('localforage', function() { return localForage; }); } else if (moduleType === ModuleType.EXPORT) { module.exports = localForage; } else { this.localforage = localForage; } }).call(window); },{"./drivers/indexeddb":77,"./drivers/localstorage":78,"./drivers/websql":79,"promise":100}],81:[function(_dereq_,module,exports){ (function() { 'use strict'; // Sadly, the best way to save binary data in WebSQL/localStorage is serializing // it to Base64, so this is how we store it to prevent very strange errors with less // verbose ways of binary <-> string data storage. var BASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; var BLOB_TYPE_PREFIX = '~~local_forage_type~'; var BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/; var SERIALIZED_MARKER = '__lfsc__:'; var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length; // OMG the serializations! var TYPE_ARRAYBUFFER = 'arbf'; var TYPE_BLOB = 'blob'; var TYPE_INT8ARRAY = 'si08'; var TYPE_UINT8ARRAY = 'ui08'; var TYPE_UINT8CLAMPEDARRAY = 'uic8'; var TYPE_INT16ARRAY = 'si16'; var TYPE_INT32ARRAY = 'si32'; var TYPE_UINT16ARRAY = 'ur16'; var TYPE_UINT32ARRAY = 'ui32'; var TYPE_FLOAT32ARRAY = 'fl32'; var TYPE_FLOAT64ARRAY = 'fl64'; var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + TYPE_ARRAYBUFFER.length; // Get out of our habit of using `window` inline, at least. var globalObject = this; // Abstracts constructing a Blob object, so it also works in older // browsers that don't support the native Blob constructor. (i.e. // old QtWebKit versions, at least). function _createBlob(parts, properties) { parts = parts || []; properties = properties || {}; try { return new Blob(parts, properties); } catch (err) { if (err.name !== 'TypeError') { throw err; } var BlobBuilder = globalObject.BlobBuilder || globalObject.MSBlobBuilder || globalObject.MozBlobBuilder || globalObject.WebKitBlobBuilder; var builder = new BlobBuilder(); for (var i = 0; i < parts.length; i += 1) { builder.append(parts[i]); } return builder.getBlob(properties.type); } } // Serialize a value, afterwards executing a callback (which usually // instructs the `setItem()` callback/promise to be executed). This is how // we store binary data with localStorage. function serialize(value, callback) { var valueString = ''; if (value) { valueString = value.toString(); } // Cannot use `value instanceof ArrayBuffer` or such here, as these // checks fail when running the tests using casper.js... // // TODO: See why those tests fail and use a better solution. if (value && (value.toString() === '[object ArrayBuffer]' || value.buffer && value.buffer.toString() === '[object ArrayBuffer]')) { // Convert binary arrays to a string and prefix the string with // a special marker. var buffer; var marker = SERIALIZED_MARKER; if (value instanceof ArrayBuffer) { buffer = value; marker += TYPE_ARRAYBUFFER; } else { buffer = value.buffer; if (valueString === '[object Int8Array]') { marker += TYPE_INT8ARRAY; } else if (valueString === '[object Uint8Array]') { marker += TYPE_UINT8ARRAY; } else if (valueString === '[object Uint8ClampedArray]') { marker += TYPE_UINT8CLAMPEDARRAY; } else if (valueString === '[object Int16Array]') { marker += TYPE_INT16ARRAY; } else if (valueString === '[object Uint16Array]') { marker += TYPE_UINT16ARRAY; } else if (valueString === '[object Int32Array]') { marker += TYPE_INT32ARRAY; } else if (valueString === '[object Uint32Array]') { marker += TYPE_UINT32ARRAY; } else if (valueString === '[object Float32Array]') { marker += TYPE_FLOAT32ARRAY; } else if (valueString === '[object Float64Array]') { marker += TYPE_FLOAT64ARRAY; } else { callback(new Error('Failed to get type for BinaryArray')); } } callback(marker + bufferToString(buffer)); } else if (valueString === '[object Blob]') { // Conver the blob to a binaryArray and then to a string. var fileReader = new FileReader(); fileReader.onload = function() { // Backwards-compatible prefix for the blob type. var str = BLOB_TYPE_PREFIX + value.type + '~' + bufferToString(this.result); callback(SERIALIZED_MARKER + TYPE_BLOB + str); }; fileReader.readAsArrayBuffer(value); } else { try { callback(JSON.stringify(value)); } catch (e) { console.error("Couldn't convert value into a JSON string: ", value); callback(null, e); } } } // Deserialize data we've inserted into a value column/field. We place // special markers into our strings to mark them as encoded; this isn't // as nice as a meta field, but it's the only sane thing we can do whilst // keeping localStorage support intact. // // Oftentimes this will just deserialize JSON content, but if we have a // special marker (SERIALIZED_MARKER, defined above), we will extract // some kind of arraybuffer/binary data/typed array out of the string. function deserialize(value) { // If we haven't marked this string as being specially serialized (i.e. // something other than serialized JSON), we can just return it and be // done with it. if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) { return JSON.parse(value); } // The following code deals with deserializing some kind of Blob or // TypedArray. First we separate out the type of data we're dealing // with from the data itself. var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH); var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH); var blobType; // Backwards-compatible blob type serialization strategy. // DBs created with older versions of localForage will simply not have the blob type. if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) { var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX); blobType = matcher[1]; serializedString = serializedString.substring(matcher[0].length); } var buffer = stringToBuffer(serializedString); // Return the right type based on the code/type set during // serialization. switch (type) { case TYPE_ARRAYBUFFER: return buffer; case TYPE_BLOB: return _createBlob([buffer], {type: blobType}); case TYPE_INT8ARRAY: return new Int8Array(buffer); case TYPE_UINT8ARRAY: return new Uint8Array(buffer); case TYPE_UINT8CLAMPEDARRAY: return new Uint8ClampedArray(buffer); case TYPE_INT16ARRAY: return new Int16Array(buffer); case TYPE_UINT16ARRAY: return new Uint16Array(buffer); case TYPE_INT32ARRAY: return new Int32Array(buffer); case TYPE_UINT32ARRAY: return new Uint32Array(buffer); case TYPE_FLOAT32ARRAY: return new Float32Array(buffer); case TYPE_FLOAT64ARRAY: return new Float64Array(buffer); default: throw new Error('Unkown type: ' + type); } } function stringToBuffer(serializedString) { // Fill the string into a ArrayBuffer. var bufferLength = serializedString.length * 0.75; var len = serializedString.length; var i; var p = 0; var encoded1, encoded2, encoded3, encoded4; if (serializedString[serializedString.length - 1] === '=') { bufferLength--; if (serializedString[serializedString.length - 2] === '=') { bufferLength--; } } var buffer = new ArrayBuffer(bufferLength); var bytes = new Uint8Array(buffer); for (i = 0; i < len; i+=4) { encoded1 = BASE_CHARS.indexOf(serializedString[i]); encoded2 = BASE_CHARS.indexOf(serializedString[i+1]); encoded3 = BASE_CHARS.indexOf(serializedString[i+2]); encoded4 = BASE_CHARS.indexOf(serializedString[i+3]); /*jslint bitwise: true */ bytes[p++] = (encoded1 << 2) | (encoded2 >> 4); bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2); bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63); } return buffer; } // Converts a buffer to a string to store, serialized, in the backend // storage library. function bufferToString(buffer) { // base64-arraybuffer var bytes = new Uint8Array(buffer); var base64String = ''; var i; for (i = 0; i < bytes.length; i += 3) { /*jslint bitwise: true */ base64String += BASE_CHARS[bytes[i] >> 2]; base64String += BASE_CHARS[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)]; base64String += BASE_CHARS[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)]; base64String += BASE_CHARS[bytes[i + 2] & 63]; } if ((bytes.length % 3) === 2) { base64String = base64String.substring(0, base64String.length - 1) + '='; } else if (bytes.length % 3 === 1) { base64String = base64String.substring(0, base64String.length - 2) + '=='; } return base64String; } var localforageSerializer = { serialize: serialize, deserialize: deserialize, stringToBuffer: stringToBuffer, bufferToString: bufferToString }; if (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') { module.exports = localforageSerializer; } else if (typeof define === 'function' && define.amd) { define('localforageSerializer', function() { return localforageSerializer; }); } else { this.localforageSerializer = localforageSerializer; } }).call(window); },{}],82:[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":83,"./lib/inflate":84,"./lib/utils/common":85,"./lib/zlib/constants":88}],83:[function(_dereq_,module,exports){ 'use strict'; var zlib_deflate = _dereq_('./zlib/deflate'); var utils = _dereq_('./utils/common'); var strings = _dereq_('./utils/strings'); var msg = _dereq_('./zlib/messages'); var ZStream = _dereq_('./zlib/zstream'); var toString = Object.prototype.toString; /* Public constants ==========================================================*/ /* ===========================================================================*/ var Z_NO_FLUSH = 0; var Z_FINISH = 4; var Z_OK = 0; var Z_STREAM_END = 1; var Z_SYNC_FLUSH = 2; var Z_DEFAULT_COMPRESSION = -1; var Z_DEFAULT_STRATEGY = 0; var Z_DEFLATED = 8; /* ===========================================================================*/ /** * class Deflate * * Generic JS-style wrapper for zlib calls. If you don't need * streaming behaviour - use more simple functions: [[deflate]], * [[deflateRaw]] and [[gzip]]. **/ /* internal * Deflate.chunks -> Array * * Chunks of output data, if [[Deflate#onData]] not overriden. **/ /** * Deflate.result -> Uint8Array|Array * * Compressed result, generated by default [[Deflate#onData]] * and [[Deflate#onEnd]] handlers. Filled after you push last chunk * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you * push a chunk with explicit flush (call [[Deflate#push]] with * `Z_SYNC_FLUSH` param). **/ /** * Deflate.err -> Number * * Error code after deflate finished. 0 (Z_OK) on success. * You will not need it in real life, because deflate errors * are possible only on wrong options or bad `onData` / `onEnd` * custom handlers. **/ /** * Deflate.msg -> String * * Error message, if [[Deflate.err]] != 0 **/ /** * new Deflate(options) * - options (Object): zlib deflate options. * * Creates new deflator instance with specified params. Throws exception * on bad params. Supported options: * * - `level` * - `windowBits` * - `memLevel` * - `strategy` * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) * for more information on these. * * Additional options, for internal needs: * * - `chunkSize` - size of generated data chunks (16K by default) * - `raw` (Boolean) - do raw deflate * - `gzip` (Boolean) - create gzip wrapper * - `to` (String) - if equal to 'string', then result will be "binary string" * (each char code [0..255]) * - `header` (Object) - custom header for gzip * - `text` (Boolean) - true if compressed data believed to be text * - `time` (Number) - modification time, unix timestamp * - `os` (Number) - operation system code * - `extra` (Array) - array of bytes with extra data (max 65536) * - `name` (String) - file name (binary string) * - `comment` (String) - comment (binary string) * - `hcrc` (Boolean) - true if header crc should be added * * ##### Example: * * ```javascript * var pako = require('pako') * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); * * var deflate = new pako.Deflate({ level: 3}); * * deflate.push(chunk1, false); * deflate.push(chunk2, true); // true -> last chunk * * if (deflate.err) { throw new Error(deflate.err); } * * console.log(deflate.result); * ``` **/ function Deflate(options) { if (!(this instanceof Deflate)) return new Deflate(options); this.options = utils.assign({ level: Z_DEFAULT_COMPRESSION, method: Z_DEFLATED, chunkSize: 16384, windowBits: 15, memLevel: 8, strategy: Z_DEFAULT_STRATEGY, to: '' }, options || {}); var opt = this.options; if (opt.raw && (opt.windowBits > 0)) { opt.windowBits = -opt.windowBits; } else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) { opt.windowBits += 16; } this.err = 0; // error code, if happens (0 = Z_OK) this.msg = ''; // error message this.ended = false; // used to avoid multiple onEnd() calls this.chunks = []; // chunks of compressed data this.strm = new ZStream(); this.strm.avail_out = 0; var status = zlib_deflate.deflateInit2( this.strm, opt.level, opt.method, opt.windowBits, opt.memLevel, opt.strategy ); if (status !== Z_OK) { throw new Error(msg[status]); } if (opt.header) { zlib_deflate.deflateSetHeader(this.strm, opt.header); } } /** * Deflate#push(data[, mode]) -> Boolean * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be * converted to utf8 byte sequence. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH. * * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with * new compressed chunks. Returns `true` on success. The last data block must have * mode Z_FINISH (or `true`). That will flush internal pending buffers and call * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you * can use mode Z_SYNC_FLUSH, keeping the compression context. * * On fail call [[Deflate#onEnd]] with error code and return false. * * We strongly recommend to use `Uint8Array` on input for best speed (output * array format is detected automatically). Also, don't skip last param and always * use the same type in your code (boolean or number). That will improve JS speed. * * For regular `Array`-s make sure all elements are [0..255]. * * ##### Example * * ```javascript * push(chunk, false); // push one of data chunks * ... * push(chunk, true); // push last chunk * ``` **/ Deflate.prototype.push = function (data, mode) { var strm = this.strm; var chunkSize = this.options.chunkSize; var status, _mode; if (this.ended) { return false; } _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH); // Convert data if needed if (typeof data === 'string') { // If we need to compress text, change encoding to utf8. strm.input = strings.string2buf(data); } else if (toString.call(data) === '[object ArrayBuffer]') { strm.input = new Uint8Array(data); } else { strm.input = data; } strm.next_in = 0; strm.avail_in = strm.input.length; do { if (strm.avail_out === 0) { strm.output = new utils.Buf8(chunkSize); strm.next_out = 0; strm.avail_out = chunkSize; } status = zlib_deflate.deflate(strm, _mode); /* no bad return value */ if (status !== Z_STREAM_END && status !== Z_OK) { this.onEnd(status); this.ended = true; return false; } if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) { if (this.options.to === 'string') { this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out))); } else { this.onData(utils.shrinkBuf(strm.output, strm.next_out)); } } } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END); // Finalize on the last chunk. if (_mode === Z_FINISH) { status = zlib_deflate.deflateEnd(this.strm); this.onEnd(status); this.ended = true; return status === Z_OK; } // callback interim results if Z_SYNC_FLUSH. if (_mode === Z_SYNC_FLUSH) { this.onEnd(Z_OK); strm.avail_out = 0; return true; } return true; }; /** * Deflate#onData(chunk) -> Void * - chunk (Uint8Array|Array|String): ouput data. Type of array depends * on js engine support. When string output requested, each chunk * will be string. * * By default, stores data blocks in `chunks[]` property and glue * those in `onEnd`. Override this handler, if you need another behaviour. **/ Deflate.prototype.onData = function (chunk) { this.chunks.push(chunk); }; /** * Deflate#onEnd(status) -> Void * - status (Number): deflate status. 0 (Z_OK) on success, * other if not. * * Called once after you tell deflate that the input stream is * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) * or if an error happened. By default - join collected chunks, * free memory and fill `results` / `err` properties. **/ Deflate.prototype.onEnd = function (status) { // On success - join if (status === Z_OK) { if (this.options.to === 'string') { this.result = this.chunks.join(''); } else { this.result = utils.flattenChunks(this.chunks); } } this.chunks = []; this.err = status; this.msg = this.strm.msg; }; /** * deflate(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to compress. * - options (Object): zlib deflate options. * * Compress `data` with deflate algorithm and `options`. * * Supported options are: * * - level * - windowBits * - memLevel * - strategy * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) * for more information on these. * * Sugar (options): * * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify * negative windowBits implicitly. * - `to` (String) - if equal to 'string', then result will be "binary string" * (each char code [0..255]) * * ##### Example: * * ```javascript * var pako = require('pako') * , data = Uint8Array([1,2,3,4,5,6,7,8,9]); * * console.log(pako.deflate(data)); * ``` **/ function deflate(input, options) { var deflator = new Deflate(options); deflator.push(input, true); // That will never happens, if you don't cheat with options :) if (deflator.err) { throw deflator.msg; } return deflator.result; } /** * deflateRaw(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to compress. * - options (Object): zlib deflate options. * * The same as [[deflate]], but creates raw data, without wrapper * (header and adler32 crc). **/ function deflateRaw(input, options) { options = options || {}; options.raw = true; return deflate(input, options); } /** * gzip(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to compress. * - options (Object): zlib deflate options. * * The same as [[deflate]], but create gzip wrapper instead of * deflate one. **/ function gzip(input, options) { options = options || {}; options.gzip = true; return deflate(input, options); } exports.Deflate = Deflate; exports.deflate = deflate; exports.deflateRaw = deflateRaw; exports.gzip = gzip; },{"./utils/common":85,"./utils/strings":86,"./zlib/deflate":90,"./zlib/messages":95,"./zlib/zstream":97}],84:[function(_dereq_,module,exports){ 'use strict'; var zlib_inflate = _dereq_('./zlib/inflate'); var utils = _dereq_('./utils/common'); var strings = _dereq_('./utils/strings'); var c = _dereq_('./zlib/constants'); var msg = _dereq_('./zlib/messages'); var ZStream = _dereq_('./zlib/zstream'); var GZheader = _dereq_('./zlib/gzheader'); var toString = Object.prototype.toString; /** * class Inflate * * Generic JS-style wrapper for zlib calls. If you don't need * streaming behaviour - use more simple functions: [[inflate]] * and [[inflateRaw]]. **/ /* internal * inflate.chunks -> Array * * Chunks of output data, if [[Inflate#onData]] not overriden. **/ /** * Inflate.result -> Uint8Array|Array|String * * Uncompressed result, generated by default [[Inflate#onData]] * and [[Inflate#onEnd]] handlers. Filled after you push last chunk * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you * push a chunk with explicit flush (call [[Inflate#push]] with * `Z_SYNC_FLUSH` param). **/ /** * Inflate.err -> Number * * Error code after inflate finished. 0 (Z_OK) on success. * Should be checked if broken data possible. **/ /** * Inflate.msg -> String * * Error message, if [[Inflate.err]] != 0 **/ /** * new Inflate(options) * - options (Object): zlib inflate options. * * Creates new inflator instance with specified params. Throws exception * on bad params. Supported options: * * - `windowBits` * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) * for more information on these. * * Additional options, for internal needs: * * - `chunkSize` - size of generated data chunks (16K by default) * - `raw` (Boolean) - do raw inflate * - `to` (String) - if equal to 'string', then result will be converted * from utf8 to utf16 (javascript) string. When string output requested, * chunk length can differ from `chunkSize`, depending on content. * * By default, when no options set, autodetect deflate/gzip data format via * wrapper header. * * ##### Example: * * ```javascript * var pako = require('pako') * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); * * var inflate = new pako.Inflate({ level: 3}); * * inflate.push(chunk1, false); * inflate.push(chunk2, true); // true -> last chunk * * if (inflate.err) { throw new Error(inflate.err); } * * console.log(inflate.result); * ``` **/ function Inflate(options) { if (!(this instanceof Inflate)) return new Inflate(options); this.options = utils.assign({ chunkSize: 16384, windowBits: 0, to: '' }, options || {}); var opt = this.options; // Force window size for `raw` data, if not set directly, // because we have no header for autodetect. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) { opt.windowBits = -opt.windowBits; if (opt.windowBits === 0) { opt.windowBits = -15; } } // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate if ((opt.windowBits >= 0) && (opt.windowBits < 16) && !(options && options.windowBits)) { opt.windowBits += 32; } // Gzip header has no info about windows size, we can do autodetect only // for deflate. So, if window size not set, force it to max when gzip possible if ((opt.windowBits > 15) && (opt.windowBits < 48)) { // bit 3 (16) -> gzipped data // bit 4 (32) -> autodetect gzip/deflate if ((opt.windowBits & 15) === 0) { opt.windowBits |= 15; } } this.err = 0; // error code, if happens (0 = Z_OK) this.msg = ''; // error message this.ended = false; // used to avoid multiple onEnd() calls this.chunks = []; // chunks of compressed data this.strm = new ZStream(); this.strm.avail_out = 0; var status = zlib_inflate.inflateInit2( this.strm, opt.windowBits ); if (status !== c.Z_OK) { throw new Error(msg[status]); } this.header = new GZheader(); zlib_inflate.inflateGetHeader(this.strm, this.header); } /** * Inflate#push(data[, mode]) -> Boolean * - data (Uint8Array|Array|ArrayBuffer|String): input data * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH. * * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with * new output chunks. Returns `true` on success. The last data block must have * mode Z_FINISH (or `true`). That will flush internal pending buffers and call * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you * can use mode Z_SYNC_FLUSH, keeping the decompression context. * * On fail call [[Inflate#onEnd]] with error code and return false. * * We strongly recommend to use `Uint8Array` on input for best speed (output * format is detected automatically). Also, don't skip last param and always * use the same type in your code (boolean or number). That will improve JS speed. * * For regular `Array`-s make sure all elements are [0..255]. * * ##### Example * * ```javascript * push(chunk, false); // push one of data chunks * ... * push(chunk, true); // push last chunk * ``` **/ Inflate.prototype.push = function (data, mode) { var strm = this.strm; var chunkSize = this.options.chunkSize; var status, _mode; var next_out_utf8, tail, utf8str; // Flag to properly process Z_BUF_ERROR on testing inflate call // when we check that all output data was flushed. var allowBufError = false; if (this.ended) { return false; } _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH); // Convert data if needed if (typeof data === 'string') { // Only binary strings can be decompressed on practice strm.input = strings.binstring2buf(data); } else if (toString.call(data) === '[object ArrayBuffer]') { strm.input = new Uint8Array(data); } else { strm.input = data; } strm.next_in = 0; strm.avail_in = strm.input.length; do { if (strm.avail_out === 0) { strm.output = new utils.Buf8(chunkSize); strm.next_out = 0; strm.avail_out = chunkSize; } status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */ if (status === c.Z_BUF_ERROR && allowBufError === true) { status = c.Z_OK; allowBufError = false; } if (status !== c.Z_STREAM_END && status !== c.Z_OK) { this.onEnd(status); this.ended = true; return false; } if (strm.next_out) { if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) { if (this.options.to === 'string') { next_out_utf8 = strings.utf8border(strm.output, strm.next_out); tail = strm.next_out - next_out_utf8; utf8str = strings.buf2string(strm.output, next_out_utf8); // move tail strm.next_out = tail; strm.avail_out = chunkSize - tail; if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); } this.onData(utf8str); } else { this.onData(utils.shrinkBuf(strm.output, strm.next_out)); } } } // When no more input data, we should check that internal inflate buffers // are flushed. The only way to do it when avail_out = 0 - run one more // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR. // Here we set flag to process this error properly. // // NOTE. Deflate does not return error in this case and does not needs such // logic. if (strm.avail_in === 0 && strm.avail_out === 0) { allowBufError = true; } } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END); if (status === c.Z_STREAM_END) { _mode = c.Z_FINISH; } // Finalize on the last chunk. if (_mode === c.Z_FINISH) { status = zlib_inflate.inflateEnd(this.strm); this.onEnd(status); this.ended = true; return status === c.Z_OK; } // callback interim results if Z_SYNC_FLUSH. if (_mode === c.Z_SYNC_FLUSH) { this.onEnd(c.Z_OK); strm.avail_out = 0; return true; } return true; }; /** * Inflate#onData(chunk) -> Void * - chunk (Uint8Array|Array|String): ouput data. Type of array depends * on js engine support. When string output requested, each chunk * will be string. * * By default, stores data blocks in `chunks[]` property and glue * those in `onEnd`. Override this handler, if you need another behaviour. **/ Inflate.prototype.onData = function (chunk) { this.chunks.push(chunk); }; /** * Inflate#onEnd(status) -> Void * - status (Number): inflate status. 0 (Z_OK) on success, * other if not. * * Called either after you tell inflate that the input stream is * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) * or if an error happened. By default - join collected chunks, * free memory and fill `results` / `err` properties. **/ Inflate.prototype.onEnd = function (status) { // On success - join if (status === c.Z_OK) { if (this.options.to === 'string') { // Glue & convert here, until we teach pako to send // utf8 alligned strings to onData this.result = this.chunks.join(''); } else { this.result = utils.flattenChunks(this.chunks); } } this.chunks = []; this.err = status; this.msg = this.strm.msg; }; /** * inflate(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to decompress. * - options (Object): zlib inflate options. * * Decompress `data` with inflate/ungzip and `options`. Autodetect * format via wrapper header by default. That's why we don't provide * separate `ungzip` method. * * Supported options are: * * - windowBits * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) * for more information. * * Sugar (options): * * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify * negative windowBits implicitly. * - `to` (String) - if equal to 'string', then result will be converted * from utf8 to utf16 (javascript) string. When string output requested, * chunk length can differ from `chunkSize`, depending on content. * * * ##### Example: * * ```javascript * var pako = require('pako') * , input = pako.deflate([1,2,3,4,5,6,7,8,9]) * , output; * * try { * output = pako.inflate(input); * } catch (err) * console.log(err); * } * ``` **/ function inflate(input, options) { var inflator = new Inflate(options); inflator.push(input, true); // That will never happens, if you don't cheat with options :) if (inflator.err) { throw inflator.msg; } return inflator.result; } /** * inflateRaw(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to decompress. * - options (Object): zlib inflate options. * * The same as [[inflate]], but creates raw data, without wrapper * (header and adler32 crc). **/ function inflateRaw(input, options) { options = options || {}; options.raw = true; return inflate(input, options); } /** * ungzip(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to decompress. * - options (Object): zlib inflate options. * * Just shortcut to [[inflate]], because it autodetects format * by header.content. Done for convenience. **/ exports.Inflate = Inflate; exports.inflate = inflate; exports.inflateRaw = inflateRaw; exports.ungzip = inflate; },{"./utils/common":85,"./utils/strings":86,"./zlib/constants":88,"./zlib/gzheader":91,"./zlib/inflate":93,"./zlib/messages":95,"./zlib/zstream":97}],85:[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); },{}],86:[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":85}],87:[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; },{}],88:[function(_dereq_,module,exports){ 'use strict'; module.exports = { /* Allowed flush values; see deflate() and inflate() below for details */ Z_NO_FLUSH: 0, Z_PARTIAL_FLUSH: 1, Z_SYNC_FLUSH: 2, Z_FULL_FLUSH: 3, Z_FINISH: 4, Z_BLOCK: 5, Z_TREES: 6, /* Return codes for the compression/decompression functions. Negative values * are errors, positive values are used for special but normal events. */ Z_OK: 0, Z_STREAM_END: 1, Z_NEED_DICT: 2, Z_ERRNO: -1, Z_STREAM_ERROR: -2, Z_DATA_ERROR: -3, //Z_MEM_ERROR: -4, Z_BUF_ERROR: -5, //Z_VERSION_ERROR: -6, /* compression levels */ Z_NO_COMPRESSION: 0, Z_BEST_SPEED: 1, Z_BEST_COMPRESSION: 9, Z_DEFAULT_COMPRESSION: -1, Z_FILTERED: 1, Z_HUFFMAN_ONLY: 2, Z_RLE: 3, Z_FIXED: 4, Z_DEFAULT_STRATEGY: 0, /* Possible values of the data_type field (though see inflate()) */ Z_BINARY: 0, Z_TEXT: 1, //Z_ASCII: 1, // = Z_TEXT (deprecated) Z_UNKNOWN: 2, /* The deflate compression method */ Z_DEFLATED: 8 //Z_NULL: null // Use -1 or null inline, depending on var type }; },{}],89:[function(_dereq_,module,exports){ 'use strict'; // Note: we can't get significant speed boost here. // So write code to minimize size - no pregenerated tables // and array tools dependencies. // Use ordinary array, since untyped makes no boost here function makeTable() { var c, table = []; for (var n = 0; n < 256; n++) { c = n; for (var k = 0; k < 8; k++) { c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); } table[n] = c; } return table; } // Create table on load. Just 255 signed longs. Not a problem. var crcTable = makeTable(); function crc32(crc, buf, len, pos) { var t = crcTable, end = pos + len; crc ^= -1; for (var i = pos; i < end; i++) { crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF]; } return (crc ^ (-1)); // >>> 0; } module.exports = crc32; },{}],90:[function(_dereq_,module,exports){ 'use strict'; var utils = _dereq_('../utils/common'); var trees = _dereq_('./trees'); var adler32 = _dereq_('./adler32'); var crc32 = _dereq_('./crc32'); var msg = _dereq_('./messages'); /* Public constants ==========================================================*/ /* ===========================================================================*/ /* Allowed flush values; see deflate() and inflate() below for details */ var Z_NO_FLUSH = 0; var Z_PARTIAL_FLUSH = 1; //var Z_SYNC_FLUSH = 2; var Z_FULL_FLUSH = 3; var Z_FINISH = 4; var Z_BLOCK = 5; //var Z_TREES = 6; /* Return codes for the compression/decompression functions. Negative values * are errors, positive values are used for special but normal events. */ var Z_OK = 0; var Z_STREAM_END = 1; //var Z_NEED_DICT = 2; //var Z_ERRNO = -1; var Z_STREAM_ERROR = -2; var Z_DATA_ERROR = -3; //var Z_MEM_ERROR = -4; var Z_BUF_ERROR = -5; //var Z_VERSION_ERROR = -6; /* compression levels */ //var Z_NO_COMPRESSION = 0; //var Z_BEST_SPEED = 1; //var Z_BEST_COMPRESSION = 9; var Z_DEFAULT_COMPRESSION = -1; var Z_FILTERED = 1; var Z_HUFFMAN_ONLY = 2; var Z_RLE = 3; var Z_FIXED = 4; var Z_DEFAULT_STRATEGY = 0; /* Possible values of the data_type field (though see inflate()) */ //var Z_BINARY = 0; //var Z_TEXT = 1; //var Z_ASCII = 1; // = Z_TEXT var Z_UNKNOWN = 2; /* The deflate compression method */ var Z_DEFLATED = 8; /*============================================================================*/ var MAX_MEM_LEVEL = 9; /* Maximum value for memLevel in deflateInit2 */ var MAX_WBITS = 15; /* 32K LZ77 window */ var DEF_MEM_LEVEL = 8; var LENGTH_CODES = 29; /* number of length codes, not counting the special END_BLOCK code */ var LITERALS = 256; /* number of literal bytes 0..255 */ var L_CODES = LITERALS + 1 + LENGTH_CODES; /* number of Literal or Length codes, including the END_BLOCK code */ var D_CODES = 30; /* number of distance codes */ var BL_CODES = 19; /* number of codes used to transfer the bit lengths */ var HEAP_SIZE = 2 * L_CODES + 1; /* maximum heap size */ var MAX_BITS = 15; /* All codes must not exceed MAX_BITS bits */ var MIN_MATCH = 3; var MAX_MATCH = 258; var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1); var PRESET_DICT = 0x20; var INIT_STATE = 42; var EXTRA_STATE = 69; var NAME_STATE = 73; var COMMENT_STATE = 91; var HCRC_STATE = 103; var BUSY_STATE = 113; var FINISH_STATE = 666; var BS_NEED_MORE = 1; /* block not completed, need more input or more output */ var BS_BLOCK_DONE = 2; /* block flush performed */ var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */ var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */ var OS_CODE = 0x03; // Unix :) . Don't detect, use this default. function err(strm, errorCode) { strm.msg = msg[errorCode]; return errorCode; } function rank(f) { return ((f) << 1) - ((f) > 4 ? 9 : 0); } function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } /* ========================================================================= * Flush as much pending output as possible. All deflate() output goes * through this function so some applications may wish to modify it * to avoid allocating a large strm->output buffer and copying into it. * (See also read_buf()). */ function flush_pending(strm) { var s = strm.state; //_tr_flush_bits(s); var len = s.pending; if (len > strm.avail_out) { len = strm.avail_out; } if (len === 0) { return; } utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out); strm.next_out += len; s.pending_out += len; strm.total_out += len; strm.avail_out -= len; s.pending -= len; if (s.pending === 0) { s.pending_out = 0; } } function flush_block_only(s, last) { trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last); s.block_start = s.strstart; flush_pending(s.strm); } function put_byte(s, b) { s.pending_buf[s.pending++] = b; } /* ========================================================================= * Put a short in the pending buffer. The 16-bit value is put in MSB order. * IN assertion: the stream state is correct and there is enough room in * pending_buf. */ function putShortMSB(s, b) { // put_byte(s, (Byte)(b >> 8)); // put_byte(s, (Byte)(b & 0xff)); s.pending_buf[s.pending++] = (b >>> 8) & 0xff; s.pending_buf[s.pending++] = b & 0xff; } /* =========================================================================== * Read a new buffer from the current input stream, update the adler32 * and total number of bytes read. All deflate() input goes through * this function so some applications may wish to modify it to avoid * allocating a large strm->input buffer and copying from it. * (See also flush_pending()). */ function read_buf(strm, buf, start, size) { var len = strm.avail_in; if (len > size) { len = size; } if (len === 0) { return 0; } strm.avail_in -= len; utils.arraySet(buf, strm.input, strm.next_in, len, start); if (strm.state.wrap === 1) { strm.adler = adler32(strm.adler, buf, len, start); } else if (strm.state.wrap === 2) { strm.adler = crc32(strm.adler, buf, len, start); } strm.next_in += len; strm.total_in += len; return len; } /* =========================================================================== * Set match_start to the longest match starting at the given string and * return its length. Matches shorter or equal to prev_length are discarded, * in which case the result is equal to prev_length and match_start is * garbage. * IN assertions: cur_match is the head of the hash chain for the current * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 * OUT assertion: the match length is not greater than s->lookahead. */ function longest_match(s, cur_match) { var chain_length = s.max_chain_length; /* max hash chain length */ var scan = s.strstart; /* current string */ var match; /* matched string */ var len; /* length of current match */ var best_len = s.prev_length; /* best match length so far */ var nice_match = s.nice_match; /* stop if match long enough */ var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ? s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/; var _win = s.window; // shortcut var wmask = s.w_mask; var prev = s.prev; /* Stop when cur_match becomes <= limit. To simplify the code, * we prevent matches with the string of window index 0. */ var strend = s.strstart + MAX_MATCH; var scan_end1 = _win[scan + best_len - 1]; var scan_end = _win[scan + best_len]; /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. * It is easy to get rid of this optimization if necessary. */ // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); /* Do not waste too much time if we already have a good match: */ if (s.prev_length >= s.good_match) { chain_length >>= 2; } /* Do not look for matches beyond the end of the input. This is necessary * to make deflate deterministic. */ if (nice_match > s.lookahead) { nice_match = s.lookahead; } // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); do { // Assert(cur_match < s->strstart, "no future"); match = cur_match; /* Skip to next match if the match length cannot increase * or if the match length is less than 2. Note that the checks below * for insufficient lookahead only occur occasionally for performance * reasons. Therefore uninitialized memory will be accessed, and * conditional jumps will be made that depend on those values. * However the length of the match is limited to the lookahead, so * the output of deflate is not affected by the uninitialized values. */ if (_win[match + best_len] !== scan_end || _win[match + best_len - 1] !== scan_end1 || _win[match] !== _win[scan] || _win[++match] !== _win[scan + 1]) { continue; } /* The check at best_len-1 can be removed because it will be made * again later. (This heuristic is not always a win.) * It is not necessary to compare scan[2] and match[2] since they * are always equal when the other bytes match, given that * the hash keys are equal and that HASH_BITS >= 8. */ scan += 2; match++; // Assert(*scan == *match, "match[2]?"); /* We check for insufficient lookahead only every 8th comparison; * the 256th check will be made at strstart+258. */ do { /*jshint noempty:false*/ } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && scan < strend); // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); len = MAX_MATCH - (strend - scan); scan = strend - MAX_MATCH; if (len > best_len) { s.match_start = cur_match; best_len = len; if (len >= nice_match) { break; } scan_end1 = _win[scan + best_len - 1]; scan_end = _win[scan + best_len]; } } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0); if (best_len <= s.lookahead) { return best_len; } return s.lookahead; } /* =========================================================================== * Fill the window when the lookahead becomes insufficient. * Updates strstart and lookahead. * * IN assertion: lookahead < MIN_LOOKAHEAD * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD * At least one byte has been read, or avail_in == 0; reads are * performed for at least two bytes (required for the zip translate_eol * option -- not supported here). */ function fill_window(s) { var _w_size = s.w_size; var p, n, m, more, str; //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); do { more = s.window_size - s.lookahead - s.strstart; // JS ints have 32 bit, block below not needed /* Deal with !@#$% 64K limit: */ //if (sizeof(int) <= 2) { // if (more == 0 && s->strstart == 0 && s->lookahead == 0) { // more = wsize; // // } else if (more == (unsigned)(-1)) { // /* Very unlikely, but possible on 16 bit machine if // * strstart == 0 && lookahead == 1 (input done a byte at time) // */ // more--; // } //} /* If the window is almost full and there is insufficient lookahead, * move the upper half to the lower one to make room in the upper half. */ if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) { utils.arraySet(s.window, s.window, _w_size, _w_size, 0); s.match_start -= _w_size; s.strstart -= _w_size; /* we now have strstart >= MAX_DIST */ s.block_start -= _w_size; /* Slide the hash table (could be avoided with 32 bit values at the expense of memory usage). We slide even when level == 0 to keep the hash table consistent if we switch back to level > 0 later. (Using level 0 permanently is not an optimal usage of zlib, so we don't care about this pathological case.) */ n = s.hash_size; p = n; do { m = s.head[--p]; s.head[p] = (m >= _w_size ? m - _w_size : 0); } while (--n); n = _w_size; p = n; do { m = s.prev[--p]; s.prev[p] = (m >= _w_size ? m - _w_size : 0); /* If n is not on any hash chain, prev[n] is garbage but * its value will never be used. */ } while (--n); more += _w_size; } if (s.strm.avail_in === 0) { break; } /* If there was no sliding: * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && * more == window_size - lookahead - strstart * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) * => more >= window_size - 2*WSIZE + 2 * In the BIG_MEM or MMAP case (not yet supported), * window_size == input_size + MIN_LOOKAHEAD && * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. * Otherwise, window_size == 2*WSIZE so more >= 2. * If there was sliding, more >= WSIZE. So in all cases, more >= 2. */ //Assert(more >= 2, "more < 2"); n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more); s.lookahead += n; /* Initialize the hash value now that we have some input: */ if (s.lookahead + s.insert >= MIN_MATCH) { str = s.strstart - s.insert; s.ins_h = s.window[str]; /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask; //#if MIN_MATCH != 3 // Call update_hash() MIN_MATCH-3 more times //#endif while (s.insert) { /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; s.prev[str & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = str; str++; s.insert--; if (s.lookahead + s.insert < MIN_MATCH) { break; } } } /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, * but this is not important since only literal bytes will be emitted. */ } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0); /* If the WIN_INIT bytes after the end of the current data have never been * written, then zero those bytes in order to avoid memory check reports of * the use of uninitialized (or uninitialised as Julian writes) bytes by * the longest match routines. Update the high water mark for the next * time through here. WIN_INIT is set to MAX_MATCH since the longest match * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. */ // if (s.high_water < s.window_size) { // var curr = s.strstart + s.lookahead; // var init = 0; // // if (s.high_water < curr) { // /* Previous high water mark below current data -- zero WIN_INIT // * bytes or up to end of window, whichever is less. // */ // init = s.window_size - curr; // if (init > WIN_INIT) // init = WIN_INIT; // zmemzero(s->window + curr, (unsigned)init); // s->high_water = curr + init; // } // else if (s->high_water < (ulg)curr + WIN_INIT) { // /* High water mark at or above current data, but below current data // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up // * to end of window, whichever is less. // */ // init = (ulg)curr + WIN_INIT - s->high_water; // if (init > s->window_size - s->high_water) // init = s->window_size - s->high_water; // zmemzero(s->window + s->high_water, (unsigned)init); // s->high_water += init; // } // } // // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, // "not enough room for search"); } /* =========================================================================== * Copy without compression as much as possible from the input stream, return * the current block state. * This function does not insert new strings in the dictionary since * uncompressible data is probably not useful. This function is used * only for the level=0 compression option. * NOTE: this function should be optimized to avoid extra copying from * window to pending_buf. */ function deflate_stored(s, flush) { /* Stored blocks are limited to 0xffff bytes, pending_buf is limited * to pending_buf_size, and each stored block has a 5 byte header: */ var max_block_size = 0xffff; if (max_block_size > s.pending_buf_size - 5) { max_block_size = s.pending_buf_size - 5; } /* Copy as much as possible from input to output: */ for (;;) { /* Fill the window as much as possible: */ if (s.lookahead <= 1) { //Assert(s->strstart < s->w_size+MAX_DIST(s) || // s->block_start >= (long)s->w_size, "slide too late"); // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) || // s.block_start >= s.w_size)) { // throw new Error("slide too late"); // } fill_window(s); if (s.lookahead === 0 && flush === Z_NO_FLUSH) { return BS_NEED_MORE; } if (s.lookahead === 0) { break; } /* flush the current block */ } //Assert(s->block_start >= 0L, "block gone"); // if (s.block_start < 0) throw new Error("block gone"); s.strstart += s.lookahead; s.lookahead = 0; /* Emit a stored block if pending_buf will be full: */ var max_start = s.block_start + max_block_size; if (s.strstart === 0 || s.strstart >= max_start) { /* strstart == 0 is possible when wraparound on 16-bit machine */ s.lookahead = s.strstart - max_start; s.strstart = max_start; /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } /* Flush if we may have to slide, otherwise block_start may become * negative and the data will be gone: */ if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } s.insert = 0; if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.strstart > s.block_start) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_NEED_MORE; } /* =========================================================================== * Compress as much as possible from the input stream, return the current * block state. * This function does not perform lazy evaluation of matches and inserts * new strings in the dictionary only for unmatched strings or for short * matches. It is used only for the fast compression options. */ function deflate_fast(s, flush) { var hash_head; /* head of the hash chain */ var bflush; /* set if current block must be flushed */ for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the next match, plus MIN_MATCH bytes to insert the * string following the next match. */ if (s.lookahead < MIN_LOOKAHEAD) { fill_window(s); if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { return BS_NEED_MORE; } if (s.lookahead === 0) { break; /* flush the current block */ } } /* Insert the string window[strstart .. strstart+2] in the * dictionary, and set hash_head to the head of the hash chain: */ hash_head = 0/*NIL*/; if (s.lookahead >= MIN_MATCH) { /*** INSERT_STRING(s, s.strstart, hash_head); ***/ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = s.strstart; /***/ } /* Find the longest match, discarding those <= prev_length. * At this point we have always match_length < MIN_MATCH */ if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) { /* To simplify the code, we prevent matches with the string * of window index 0 (in particular we have to avoid a match * of the string with itself at the start of the input file). */ s.match_length = longest_match(s, hash_head); /* longest_match() sets match_start */ } if (s.match_length >= MIN_MATCH) { // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only /*** _tr_tally_dist(s, s.strstart - s.match_start, s.match_length - MIN_MATCH, bflush); ***/ bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH); s.lookahead -= s.match_length; /* Insert new strings in the hash table only if the match length * is not too large. This saves time but degrades compression. */ if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) { s.match_length--; /* string at strstart already in table */ do { s.strstart++; /*** INSERT_STRING(s, s.strstart, hash_head); ***/ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = s.strstart; /***/ /* strstart never exceeds WSIZE-MAX_MATCH, so there are * always MIN_MATCH bytes ahead. */ } while (--s.match_length !== 0); s.strstart++; } else { s.strstart += s.match_length; s.match_length = 0; s.ins_h = s.window[s.strstart]; /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask; //#if MIN_MATCH != 3 // Call UPDATE_HASH() MIN_MATCH-3 more times //#endif /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not * matter since it will be recomputed at next deflate call. */ } } else { /* No match, output a literal byte */ //Tracevv((stderr,"%c", s.window[s.strstart])); /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart]); s.lookahead--; s.strstart++; } if (bflush) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1); if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.last_lit) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_BLOCK_DONE; } /* =========================================================================== * Same as above, but achieves better compression. We use a lazy * evaluation for matches: a match is finally adopted only if there is * no better match at the next window position. */ function deflate_slow(s, flush) { var hash_head; /* head of hash chain */ var bflush; /* set if current block must be flushed */ var max_insert; /* Process the input block. */ for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the next match, plus MIN_MATCH bytes to insert the * string following the next match. */ if (s.lookahead < MIN_LOOKAHEAD) { fill_window(s); if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { return BS_NEED_MORE; } if (s.lookahead === 0) { break; } /* flush the current block */ } /* Insert the string window[strstart .. strstart+2] in the * dictionary, and set hash_head to the head of the hash chain: */ hash_head = 0/*NIL*/; if (s.lookahead >= MIN_MATCH) { /*** INSERT_STRING(s, s.strstart, hash_head); ***/ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = s.strstart; /***/ } /* Find the longest match, discarding those <= prev_length. */ s.prev_length = s.match_length; s.prev_match = s.match_start; s.match_length = MIN_MATCH - 1; if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match && s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) { /* To simplify the code, we prevent matches with the string * of window index 0 (in particular we have to avoid a match * of the string with itself at the start of the input file). */ s.match_length = longest_match(s, hash_head); /* longest_match() sets match_start */ if (s.match_length <= 5 && (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) { /* If prev_match is also MIN_MATCH, match_start is garbage * but we will ignore the current match anyway. */ s.match_length = MIN_MATCH - 1; } } /* If there was a match at the previous step and the current * match is not better, output the previous match: */ if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) { max_insert = s.strstart + s.lookahead - MIN_MATCH; /* Do not insert strings in hash table beyond this. */ //check_match(s, s.strstart-1, s.prev_match, s.prev_length); /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH, bflush);***/ bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH); /* Insert in hash table all strings up to the end of the match. * strstart-1 and strstart are already inserted. If there is not * enough lookahead, the last two strings are not inserted in * the hash table. */ s.lookahead -= s.prev_length - 1; s.prev_length -= 2; do { if (++s.strstart <= max_insert) { /*** INSERT_STRING(s, s.strstart, hash_head); ***/ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = s.strstart; /***/ } } while (--s.prev_length !== 0); s.match_available = 0; s.match_length = MIN_MATCH - 1; s.strstart++; if (bflush) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } else if (s.match_available) { /* If there was no match at the previous position, output a * single literal. If there was a match but the current match * is longer, truncate the previous match to a single literal. */ //Tracevv((stderr,"%c", s->window[s->strstart-1])); /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); if (bflush) { /*** FLUSH_BLOCK_ONLY(s, 0) ***/ flush_block_only(s, false); /***/ } s.strstart++; s.lookahead--; if (s.strm.avail_out === 0) { return BS_NEED_MORE; } } else { /* There is no previous match to compare with, wait for * the next step to decide. */ s.match_available = 1; s.strstart++; s.lookahead--; } } //Assert (flush != Z_NO_FLUSH, "no flush?"); if (s.match_available) { //Tracevv((stderr,"%c", s->window[s->strstart-1])); /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); s.match_available = 0; } s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1; if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.last_lit) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_BLOCK_DONE; } /* =========================================================================== * For Z_RLE, simply look for runs of bytes, generate matches only of distance * one. Do not maintain a hash table. (It will be regenerated if this run of * deflate switches away from Z_RLE.) */ function deflate_rle(s, flush) { var bflush; /* set if current block must be flushed */ var prev; /* byte at distance one to match */ var scan, strend; /* scan goes up to strend for length of run */ var _win = s.window; for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the longest run, plus one for the unrolled loop. */ if (s.lookahead <= MAX_MATCH) { fill_window(s); if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) { return BS_NEED_MORE; } if (s.lookahead === 0) { break; } /* flush the current block */ } /* See how many times the previous byte repeats */ s.match_length = 0; if (s.lookahead >= MIN_MATCH && s.strstart > 0) { scan = s.strstart - 1; prev = _win[scan]; if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) { strend = s.strstart + MAX_MATCH; do { /*jshint noempty:false*/ } while (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && scan < strend); s.match_length = MAX_MATCH - (strend - scan); if (s.match_length > s.lookahead) { s.match_length = s.lookahead; } } //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); } /* Emit match if have run of MIN_MATCH or longer, else emit literal */ if (s.match_length >= MIN_MATCH) { //check_match(s, s.strstart, s.strstart - 1, s.match_length); /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/ bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH); s.lookahead -= s.match_length; s.strstart += s.match_length; s.match_length = 0; } else { /* No match, output a literal byte */ //Tracevv((stderr,"%c", s->window[s->strstart])); /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart]); s.lookahead--; s.strstart++; } if (bflush) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } s.insert = 0; if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.last_lit) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_BLOCK_DONE; } /* =========================================================================== * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. * (It will be regenerated if this run of deflate switches away from Huffman.) */ function deflate_huff(s, flush) { var bflush; /* set if current block must be flushed */ for (;;) { /* Make sure that we have a literal to write. */ if (s.lookahead === 0) { fill_window(s); if (s.lookahead === 0) { if (flush === Z_NO_FLUSH) { return BS_NEED_MORE; } break; /* flush the current block */ } } /* Output a literal byte */ s.match_length = 0; //Tracevv((stderr,"%c", s->window[s->strstart])); /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart]); s.lookahead--; s.strstart++; if (bflush) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } s.insert = 0; if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.last_lit) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_BLOCK_DONE; } /* Values for max_lazy_match, good_match and max_chain_length, depending on * the desired pack level (0..9). The values given below have been tuned to * exclude worst case performance for pathological files. Better values may be * found for specific files. */ function Config(good_length, max_lazy, nice_length, max_chain, func) { this.good_length = good_length; this.max_lazy = max_lazy; this.nice_length = nice_length; this.max_chain = max_chain; this.func = func; } var configuration_table; configuration_table = [ /* good lazy nice chain */ new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */ new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */ new Config(4, 5, 16, 8, deflate_fast), /* 2 */ new Config(4, 6, 32, 32, deflate_fast), /* 3 */ new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */ new Config(8, 16, 32, 32, deflate_slow), /* 5 */ new Config(8, 16, 128, 128, deflate_slow), /* 6 */ new Config(8, 32, 128, 256, deflate_slow), /* 7 */ new Config(32, 128, 258, 1024, deflate_slow), /* 8 */ new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */ ]; /* =========================================================================== * Initialize the "longest match" routines for a new zlib stream */ function lm_init(s) { s.window_size = 2 * s.w_size; /*** CLEAR_HASH(s); ***/ zero(s.head); // Fill with NIL (= 0); /* Set the default configuration parameters: */ s.max_lazy_match = configuration_table[s.level].max_lazy; s.good_match = configuration_table[s.level].good_length; s.nice_match = configuration_table[s.level].nice_length; s.max_chain_length = configuration_table[s.level].max_chain; s.strstart = 0; s.block_start = 0; s.lookahead = 0; s.insert = 0; s.match_length = s.prev_length = MIN_MATCH - 1; s.match_available = 0; s.ins_h = 0; } function DeflateState() { this.strm = null; /* pointer back to this zlib stream */ this.status = 0; /* as the name implies */ this.pending_buf = null; /* output still pending */ this.pending_buf_size = 0; /* size of pending_buf */ this.pending_out = 0; /* next pending byte to output to the stream */ this.pending = 0; /* nb of bytes in the pending buffer */ this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ this.gzhead = null; /* gzip header information to write */ this.gzindex = 0; /* where in extra, name, or comment */ this.method = Z_DEFLATED; /* can only be DEFLATED */ this.last_flush = -1; /* value of flush param for previous deflate call */ this.w_size = 0; /* LZ77 window size (32K by default) */ this.w_bits = 0; /* log2(w_size) (8..16) */ this.w_mask = 0; /* w_size - 1 */ this.window = null; /* Sliding window. Input bytes are read into the second half of the window, * and move to the first half later to keep a dictionary of at least wSize * bytes. With this organization, matches are limited to a distance of * wSize-MAX_MATCH bytes, but this ensures that IO is always * performed with a length multiple of the block size. */ this.window_size = 0; /* Actual size of window: 2*wSize, except when the user input buffer * is directly used as sliding window. */ this.prev = null; /* Link to older string with same hash index. To limit the size of this * array to 64K, this link is maintained only for the last 32K strings. * An index in this array is thus a window index modulo 32K. */ this.head = null; /* Heads of the hash chains or NIL. */ this.ins_h = 0; /* hash index of string to be inserted */ this.hash_size = 0; /* number of elements in hash table */ this.hash_bits = 0; /* log2(hash_size) */ this.hash_mask = 0; /* hash_size-1 */ this.hash_shift = 0; /* Number of bits by which ins_h must be shifted at each input * step. It must be such that after MIN_MATCH steps, the oldest * byte no longer takes part in the hash key, that is: * hash_shift * MIN_MATCH >= hash_bits */ this.block_start = 0; /* Window position at the beginning of the current output block. Gets * negative when the window is moved backwards. */ this.match_length = 0; /* length of best match */ this.prev_match = 0; /* previous match */ this.match_available = 0; /* set if previous match exists */ this.strstart = 0; /* start of string to insert */ this.match_start = 0; /* start of matching string */ this.lookahead = 0; /* number of valid bytes ahead in window */ this.prev_length = 0; /* Length of the best match at previous step. Matches not greater than this * are discarded. This is used in the lazy match evaluation. */ this.max_chain_length = 0; /* To speed up deflation, hash chains are never searched beyond this * length. A higher limit improves compression ratio but degrades the * speed. */ this.max_lazy_match = 0; /* Attempt to find a better match only when the current match is strictly * smaller than this value. This mechanism is used only for compression * levels >= 4. */ // That's alias to max_lazy_match, don't use directly //this.max_insert_length = 0; /* Insert new strings in the hash table only if the match length is not * greater than this length. This saves time but degrades compression. * max_insert_length is used only for compression levels <= 3. */ this.level = 0; /* compression level (1..9) */ this.strategy = 0; /* favor or force Huffman coding*/ this.good_match = 0; /* Use a faster search when the previous match is longer than this */ this.nice_match = 0; /* Stop searching when current match exceeds this */ /* used by trees.c: */ /* Didn't use ct_data typedef below to suppress compiler warning */ // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ // Use flat array of DOUBLE size, with interleaved fata, // because JS does not support effective this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2); this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2); this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2); zero(this.dyn_ltree); zero(this.dyn_dtree); zero(this.bl_tree); this.l_desc = null; /* desc. for literal tree */ this.d_desc = null; /* desc. for distance tree */ this.bl_desc = null; /* desc. for bit length tree */ //ush bl_count[MAX_BITS+1]; this.bl_count = new utils.Buf16(MAX_BITS + 1); /* number of codes at each bit length for an optimal tree */ //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */ zero(this.heap); this.heap_len = 0; /* number of elements in the heap */ this.heap_max = 0; /* element of largest frequency */ /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. * The same heap array is used to build all trees. */ this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1]; zero(this.depth); /* Depth of each subtree used as tie breaker for trees of equal frequency */ this.l_buf = 0; /* buffer index for literals or lengths */ this.lit_bufsize = 0; /* Size of match buffer for literals/lengths. There are 4 reasons for * limiting lit_bufsize to 64K: * - frequencies can be kept in 16 bit counters * - if compression is not successful for the first block, all input * data is still in the window so we can still emit a stored block even * when input comes from standard input. (This can also be done for * all blocks if lit_bufsize is not greater than 32K.) * - if compression is not successful for a file smaller than 64K, we can * even emit a stored file instead of a stored block (saving 5 bytes). * This is applicable only for zip (not gzip or zlib). * - creating new Huffman trees less frequently may not provide fast * adaptation to changes in the input data statistics. (Take for * example a binary file with poorly compressible code followed by * a highly compressible string table.) Smaller buffer sizes give * fast adaptation but have of course the overhead of transmitting * trees more frequently. * - I can't count above 4 */ this.last_lit = 0; /* running index in l_buf */ this.d_buf = 0; /* Buffer index for distances. To simplify the code, d_buf and l_buf have * the same number of elements. To use different lengths, an extra flag * array would be necessary. */ this.opt_len = 0; /* bit length of current block with optimal trees */ this.static_len = 0; /* bit length of current block with static trees */ this.matches = 0; /* number of string matches in current block */ this.insert = 0; /* bytes at end of window left to insert */ this.bi_buf = 0; /* Output buffer. bits are inserted starting at the bottom (least * significant bits). */ this.bi_valid = 0; /* Number of valid bits in bi_buf. All bits above the last valid bit * are always zero. */ // Used for window memory init. We safely ignore it for JS. That makes // sense only for pointers and memory check tools. //this.high_water = 0; /* High water mark offset in window for initialized bytes -- bytes above * this are set to zero in order to avoid memory check warnings when * longest match routines access bytes past the input. This is then * updated to the new high water mark. */ } function deflateResetKeep(strm) { var s; if (!strm || !strm.state) { return err(strm, Z_STREAM_ERROR); } strm.total_in = strm.total_out = 0; strm.data_type = Z_UNKNOWN; s = strm.state; s.pending = 0; s.pending_out = 0; if (s.wrap < 0) { s.wrap = -s.wrap; /* was made negative by deflate(..., Z_FINISH); */ } s.status = (s.wrap ? INIT_STATE : BUSY_STATE); strm.adler = (s.wrap === 2) ? 0 // crc32(0, Z_NULL, 0) : 1; // adler32(0, Z_NULL, 0) s.last_flush = Z_NO_FLUSH; trees._tr_init(s); return Z_OK; } function deflateReset(strm) { var ret = deflateResetKeep(strm); if (ret === Z_OK) { lm_init(strm.state); } return ret; } function deflateSetHeader(strm, head) { if (!strm || !strm.state) { return Z_STREAM_ERROR; } if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; } strm.state.gzhead = head; return Z_OK; } function deflateInit2(strm, level, method, windowBits, memLevel, strategy) { if (!strm) { // === Z_NULL return Z_STREAM_ERROR; } var wrap = 1; if (level === Z_DEFAULT_COMPRESSION) { level = 6; } if (windowBits < 0) { /* suppress zlib wrapper */ wrap = 0; windowBits = -windowBits; } else if (windowBits > 15) { wrap = 2; /* write gzip wrapper instead */ windowBits -= 16; } if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED || windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) { return err(strm, Z_STREAM_ERROR); } if (windowBits === 8) { windowBits = 9; } /* until 256-byte window bug fixed */ var s = new DeflateState(); strm.state = s; s.strm = strm; s.wrap = wrap; s.gzhead = null; s.w_bits = windowBits; s.w_size = 1 << s.w_bits; s.w_mask = s.w_size - 1; s.hash_bits = memLevel + 7; s.hash_size = 1 << s.hash_bits; s.hash_mask = s.hash_size - 1; s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH); s.window = new utils.Buf8(s.w_size * 2); s.head = new utils.Buf16(s.hash_size); s.prev = new utils.Buf16(s.w_size); // Don't need mem init magic for JS. //s.high_water = 0; /* nothing written to s->window yet */ s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ s.pending_buf_size = s.lit_bufsize * 4; s.pending_buf = new utils.Buf8(s.pending_buf_size); s.d_buf = s.lit_bufsize >> 1; s.l_buf = (1 + 2) * s.lit_bufsize; s.level = level; s.strategy = strategy; s.method = method; return deflateReset(strm); } function deflateInit(strm, level) { return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY); } function deflate(strm, flush) { var old_flush, s; var beg, val; // for gzip header write only if (!strm || !strm.state || flush > Z_BLOCK || flush < 0) { return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR; } s = strm.state; if (!strm.output || (!strm.input && strm.avail_in !== 0) || (s.status === FINISH_STATE && flush !== Z_FINISH)) { return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR); } s.strm = strm; /* just in case */ old_flush = s.last_flush; s.last_flush = flush; /* Write the header */ if (s.status === INIT_STATE) { if (s.wrap === 2) { // GZIP header strm.adler = 0; //crc32(0L, Z_NULL, 0); put_byte(s, 31); put_byte(s, 139); put_byte(s, 8); if (!s.gzhead) { // s->gzhead == Z_NULL put_byte(s, 0); put_byte(s, 0); put_byte(s, 0); put_byte(s, 0); put_byte(s, 0); put_byte(s, s.level === 9 ? 2 : (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? 4 : 0)); put_byte(s, OS_CODE); s.status = BUSY_STATE; } else { put_byte(s, (s.gzhead.text ? 1 : 0) + (s.gzhead.hcrc ? 2 : 0) + (!s.gzhead.extra ? 0 : 4) + (!s.gzhead.name ? 0 : 8) + (!s.gzhead.comment ? 0 : 16) ); put_byte(s, s.gzhead.time & 0xff); put_byte(s, (s.gzhead.time >> 8) & 0xff); put_byte(s, (s.gzhead.time >> 16) & 0xff); put_byte(s, (s.gzhead.time >> 24) & 0xff); put_byte(s, s.level === 9 ? 2 : (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? 4 : 0)); put_byte(s, s.gzhead.os & 0xff); if (s.gzhead.extra && s.gzhead.extra.length) { put_byte(s, s.gzhead.extra.length & 0xff); put_byte(s, (s.gzhead.extra.length >> 8) & 0xff); } if (s.gzhead.hcrc) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0); } s.gzindex = 0; s.status = EXTRA_STATE; } } else // DEFLATE header { var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8; var level_flags = -1; if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) { level_flags = 0; } else if (s.level < 6) { level_flags = 1; } else if (s.level === 6) { level_flags = 2; } else { level_flags = 3; } header |= (level_flags << 6); if (s.strstart !== 0) { header |= PRESET_DICT; } header += 31 - (header % 31); s.status = BUSY_STATE; putShortMSB(s, header); /* Save the adler32 of the preset dictionary: */ if (s.strstart !== 0) { putShortMSB(s, strm.adler >>> 16); putShortMSB(s, strm.adler & 0xffff); } strm.adler = 1; // adler32(0L, Z_NULL, 0); } } //#ifdef GZIP if (s.status === EXTRA_STATE) { if (s.gzhead.extra/* != Z_NULL*/) { beg = s.pending; /* start of bytes to update crc */ while (s.gzindex < (s.gzhead.extra.length & 0xffff)) { if (s.pending === s.pending_buf_size) { if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } flush_pending(strm); beg = s.pending; if (s.pending === s.pending_buf_size) { break; } } put_byte(s, s.gzhead.extra[s.gzindex] & 0xff); s.gzindex++; } if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } if (s.gzindex === s.gzhead.extra.length) { s.gzindex = 0; s.status = NAME_STATE; } } else { s.status = NAME_STATE; } } if (s.status === NAME_STATE) { if (s.gzhead.name/* != Z_NULL*/) { beg = s.pending; /* start of bytes to update crc */ //int val; do { if (s.pending === s.pending_buf_size) { if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } flush_pending(strm); beg = s.pending; if (s.pending === s.pending_buf_size) { val = 1; break; } } // JS specific: little magic to add zero terminator to end of string if (s.gzindex < s.gzhead.name.length) { val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff; } else { val = 0; } put_byte(s, val); } while (val !== 0); if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } if (val === 0) { s.gzindex = 0; s.status = COMMENT_STATE; } } else { s.status = COMMENT_STATE; } } if (s.status === COMMENT_STATE) { if (s.gzhead.comment/* != Z_NULL*/) { beg = s.pending; /* start of bytes to update crc */ //int val; do { if (s.pending === s.pending_buf_size) { if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } flush_pending(strm); beg = s.pending; if (s.pending === s.pending_buf_size) { val = 1; break; } } // JS specific: little magic to add zero terminator to end of string if (s.gzindex < s.gzhead.comment.length) { val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff; } else { val = 0; } put_byte(s, val); } while (val !== 0); if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } if (val === 0) { s.status = HCRC_STATE; } } else { s.status = HCRC_STATE; } } if (s.status === HCRC_STATE) { if (s.gzhead.hcrc) { if (s.pending + 2 > s.pending_buf_size) { flush_pending(strm); } if (s.pending + 2 <= s.pending_buf_size) { put_byte(s, strm.adler & 0xff); put_byte(s, (strm.adler >> 8) & 0xff); strm.adler = 0; //crc32(0L, Z_NULL, 0); s.status = BUSY_STATE; } } else { s.status = BUSY_STATE; } } //#endif /* Flush as much pending output as possible */ if (s.pending !== 0) { flush_pending(strm); if (strm.avail_out === 0) { /* Since avail_out is 0, deflate will be called again with * more output space, but possibly with both pending and * avail_in equal to zero. There won't be anything to do, * but this is not an error situation so make sure we * return OK instead of BUF_ERROR at next call of deflate: */ s.last_flush = -1; return Z_OK; } /* Make sure there is something to do and avoid duplicate consecutive * flushes. For repeated and useless calls with Z_FINISH, we keep * returning Z_STREAM_END instead of Z_BUF_ERROR. */ } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) && flush !== Z_FINISH) { return err(strm, Z_BUF_ERROR); } /* User must not provide more input after the first FINISH: */ if (s.status === FINISH_STATE && strm.avail_in !== 0) { return err(strm, Z_BUF_ERROR); } /* Start a new block or continue the current one. */ if (strm.avail_in !== 0 || s.lookahead !== 0 || (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) { var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) : (s.strategy === Z_RLE ? deflate_rle(s, flush) : configuration_table[s.level].func(s, flush)); if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) { s.status = FINISH_STATE; } if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) { if (strm.avail_out === 0) { s.last_flush = -1; /* avoid BUF_ERROR next call, see above */ } return Z_OK; /* If flush != Z_NO_FLUSH && avail_out == 0, the next call * of deflate should use the same flush parameter to make sure * that the flush is complete. So we don't have to output an * empty block here, this will be done at next call. This also * ensures that for a very small output buffer, we emit at most * one empty block. */ } if (bstate === BS_BLOCK_DONE) { if (flush === Z_PARTIAL_FLUSH) { trees._tr_align(s); } else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */ trees._tr_stored_block(s, 0, 0, false); /* For a full flush, this empty block will be recognized * as a special marker by inflate_sync(). */ if (flush === Z_FULL_FLUSH) { /*** CLEAR_HASH(s); ***/ /* forget history */ zero(s.head); // Fill with NIL (= 0); if (s.lookahead === 0) { s.strstart = 0; s.block_start = 0; s.insert = 0; } } } flush_pending(strm); if (strm.avail_out === 0) { s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */ return Z_OK; } } } //Assert(strm->avail_out > 0, "bug2"); //if (strm.avail_out <= 0) { throw new Error("bug2");} if (flush !== Z_FINISH) { return Z_OK; } if (s.wrap <= 0) { return Z_STREAM_END; } /* Write the trailer */ if (s.wrap === 2) { put_byte(s, strm.adler & 0xff); put_byte(s, (strm.adler >> 8) & 0xff); put_byte(s, (strm.adler >> 16) & 0xff); put_byte(s, (strm.adler >> 24) & 0xff); put_byte(s, strm.total_in & 0xff); put_byte(s, (strm.total_in >> 8) & 0xff); put_byte(s, (strm.total_in >> 16) & 0xff); put_byte(s, (strm.total_in >> 24) & 0xff); } else { putShortMSB(s, strm.adler >>> 16); putShortMSB(s, strm.adler & 0xffff); } flush_pending(strm); /* If avail_out is zero, the application will call deflate again * to flush the rest. */ if (s.wrap > 0) { s.wrap = -s.wrap; } /* write the trailer only once! */ return s.pending !== 0 ? Z_OK : Z_STREAM_END; } function deflateEnd(strm) { var status; if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { return Z_STREAM_ERROR; } status = strm.state.status; if (status !== INIT_STATE && status !== EXTRA_STATE && status !== NAME_STATE && status !== COMMENT_STATE && status !== HCRC_STATE && status !== BUSY_STATE && status !== FINISH_STATE ) { return err(strm, Z_STREAM_ERROR); } strm.state = null; return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK; } /* ========================================================================= * Copy the source state to the destination state */ //function deflateCopy(dest, source) { // //} exports.deflateInit = deflateInit; exports.deflateInit2 = deflateInit2; exports.deflateReset = deflateReset; exports.deflateResetKeep = deflateResetKeep; exports.deflateSetHeader = deflateSetHeader; exports.deflate = deflate; exports.deflateEnd = deflateEnd; exports.deflateInfo = 'pako deflate (from Nodeca project)'; /* Not implemented exports.deflateBound = deflateBound; exports.deflateCopy = deflateCopy; exports.deflateSetDictionary = deflateSetDictionary; exports.deflateParams = deflateParams; exports.deflatePending = deflatePending; exports.deflatePrime = deflatePrime; exports.deflateTune = deflateTune; */ },{"../utils/common":85,"./adler32":87,"./crc32":89,"./messages":95,"./trees":96}],91:[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; },{}],92:[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; }; },{}],93:[function(_dereq_,module,exports){ 'use strict'; var utils = _dereq_('../utils/common'); var adler32 = _dereq_('./adler32'); var crc32 = _dereq_('./crc32'); var inflate_fast = _dereq_('./inffast'); var inflate_table = _dereq_('./inftrees'); var CODES = 0; var LENS = 1; var DISTS = 2; /* Public constants ==========================================================*/ /* ===========================================================================*/ /* Allowed flush values; see deflate() and inflate() below for details */ //var Z_NO_FLUSH = 0; //var Z_PARTIAL_FLUSH = 1; //var Z_SYNC_FLUSH = 2; //var Z_FULL_FLUSH = 3; var Z_FINISH = 4; var Z_BLOCK = 5; var Z_TREES = 6; /* Return codes for the compression/decompression functions. Negative values * are errors, positive values are used for special but normal events. */ var Z_OK = 0; var Z_STREAM_END = 1; var Z_NEED_DICT = 2; //var Z_ERRNO = -1; var Z_STREAM_ERROR = -2; var Z_DATA_ERROR = -3; var Z_MEM_ERROR = -4; var Z_BUF_ERROR = -5; //var Z_VERSION_ERROR = -6; /* The deflate compression method */ var Z_DEFLATED = 8; /* STATES ====================================================================*/ /* ===========================================================================*/ var HEAD = 1; /* i: waiting for magic header */ var FLAGS = 2; /* i: waiting for method and flags (gzip) */ var TIME = 3; /* i: waiting for modification time (gzip) */ var OS = 4; /* i: waiting for extra flags and operating system (gzip) */ var EXLEN = 5; /* i: waiting for extra length (gzip) */ var EXTRA = 6; /* i: waiting for extra bytes (gzip) */ var NAME = 7; /* i: waiting for end of file name (gzip) */ var COMMENT = 8; /* i: waiting for end of comment (gzip) */ var HCRC = 9; /* i: waiting for header crc (gzip) */ var DICTID = 10; /* i: waiting for dictionary check value */ var DICT = 11; /* waiting for inflateSetDictionary() call */ var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */ var STORED = 14; /* i: waiting for stored size (length and complement) */ var COPY_ = 15; /* i/o: same as COPY below, but only first time in */ var COPY = 16; /* i/o: waiting for input or output to copy stored block */ var TABLE = 17; /* i: waiting for dynamic block table lengths */ var LENLENS = 18; /* i: waiting for code length code lengths */ var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */ var LEN_ = 20; /* i: same as LEN below, but only first time in */ var LEN = 21; /* i: waiting for length/lit/eob code */ var LENEXT = 22; /* i: waiting for length extra bits */ var DIST = 23; /* i: waiting for distance code */ var DISTEXT = 24; /* i: waiting for distance extra bits */ var MATCH = 25; /* o: waiting for output space to copy string */ var LIT = 26; /* o: waiting for output space to write literal */ var CHECK = 27; /* i: waiting for 32-bit check value */ var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */ var DONE = 29; /* finished check, done -- remain here until reset */ var BAD = 30; /* got a data error -- remain here until reset */ var MEM = 31; /* got an inflate() memory error -- remain here until reset */ var SYNC = 32; /* looking for synchronization bytes to restart inflate() */ /* ===========================================================================*/ var ENOUGH_LENS = 852; var ENOUGH_DISTS = 592; //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); var MAX_WBITS = 15; /* 32K LZ77 window */ var DEF_WBITS = MAX_WBITS; function zswap32(q) { return (((q >>> 24) & 0xff) + ((q >>> 8) & 0xff00) + ((q & 0xff00) << 8) + ((q & 0xff) << 24)); } function InflateState() { this.mode = 0; /* current inflate mode */ this.last = false; /* true if processing last block */ this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ this.havedict = false; /* true if dictionary provided */ this.flags = 0; /* gzip header method and flags (0 if zlib) */ this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */ this.check = 0; /* protected copy of check value */ this.total = 0; /* protected copy of output count */ // TODO: may be {} this.head = null; /* where to save gzip header information */ /* sliding window */ this.wbits = 0; /* log base 2 of requested window size */ this.wsize = 0; /* window size or zero if not using window */ this.whave = 0; /* valid bytes in the window */ this.wnext = 0; /* window write index */ this.window = null; /* allocated sliding window, if needed */ /* bit accumulator */ this.hold = 0; /* input bit accumulator */ this.bits = 0; /* number of bits in "in" */ /* for string and stored block copying */ this.length = 0; /* literal or length of data to copy */ this.offset = 0; /* distance back to copy string from */ /* for table and code decoding */ this.extra = 0; /* extra bits needed */ /* fixed and dynamic code tables */ this.lencode = null; /* starting table for length/literal codes */ this.distcode = null; /* starting table for distance codes */ this.lenbits = 0; /* index bits for lencode */ this.distbits = 0; /* index bits for distcode */ /* dynamic table building */ this.ncode = 0; /* number of code length code lengths */ this.nlen = 0; /* number of length code lengths */ this.ndist = 0; /* number of distance code lengths */ this.have = 0; /* number of code lengths in lens[] */ this.next = null; /* next available space in codes[] */ this.lens = new utils.Buf16(320); /* temporary storage for code lengths */ this.work = new utils.Buf16(288); /* work area for code table building */ /* because we don't have pointers in js, we use lencode and distcode directly as buffers so we don't need codes */ //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */ this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */ this.distdyn = null; /* dynamic table for distance codes (JS specific) */ this.sane = 0; /* if false, allow invalid distance too far */ this.back = 0; /* bits back of last unprocessed length/lit */ this.was = 0; /* initial length of match */ } function inflateResetKeep(strm) { var state; if (!strm || !strm.state) { return Z_STREAM_ERROR; } state = strm.state; strm.total_in = strm.total_out = state.total = 0; strm.msg = ''; /*Z_NULL*/ if (state.wrap) { /* to support ill-conceived Java test suite */ strm.adler = state.wrap & 1; } state.mode = HEAD; state.last = 0; state.havedict = 0; state.dmax = 32768; state.head = null/*Z_NULL*/; state.hold = 0; state.bits = 0; //state.lencode = state.distcode = state.next = state.codes; state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS); state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS); state.sane = 1; state.back = -1; //Tracev((stderr, "inflate: reset\n")); return Z_OK; } function inflateReset(strm) { var state; if (!strm || !strm.state) { return Z_STREAM_ERROR; } state = strm.state; state.wsize = 0; state.whave = 0; state.wnext = 0; return inflateResetKeep(strm); } function inflateReset2(strm, windowBits) { var wrap; var state; /* get the state */ if (!strm || !strm.state) { return Z_STREAM_ERROR; } state = strm.state; /* extract wrap request from windowBits parameter */ if (windowBits < 0) { wrap = 0; windowBits = -windowBits; } else { wrap = (windowBits >> 4) + 1; if (windowBits < 48) { windowBits &= 15; } } /* set number of window bits, free window if different */ if (windowBits && (windowBits < 8 || windowBits > 15)) { return Z_STREAM_ERROR; } if (state.window !== null && state.wbits !== windowBits) { state.window = null; } /* update state and reset the rest of it */ state.wrap = wrap; state.wbits = windowBits; return inflateReset(strm); } function inflateInit2(strm, windowBits) { var ret; var state; if (!strm) { return Z_STREAM_ERROR; } //strm.msg = Z_NULL; /* in case we return an error */ state = new InflateState(); //if (state === Z_NULL) return Z_MEM_ERROR; //Tracev((stderr, "inflate: allocated\n")); strm.state = state; state.window = null/*Z_NULL*/; ret = inflateReset2(strm, windowBits); if (ret !== Z_OK) { strm.state = null/*Z_NULL*/; } return ret; } function inflateInit(strm) { return inflateInit2(strm, DEF_WBITS); } /* Return state with length and distance decoding tables and index sizes set to fixed code decoding. Normally this returns fixed tables from inffixed.h. If BUILDFIXED is defined, then instead this routine builds the tables the first time it's called, and returns those tables the first time and thereafter. This reduces the size of the code by about 2K bytes, in exchange for a little execution time. However, BUILDFIXED should not be used for threaded applications, since the rewriting of the tables and virgin may not be thread-safe. */ var virgin = true; var lenfix, distfix; // We have no pointers in JS, so keep tables separate function fixedtables(state) { /* build fixed huffman tables if first call (may not be thread safe) */ if (virgin) { var sym; lenfix = new utils.Buf32(512); distfix = new utils.Buf32(32); /* literal/length table */ sym = 0; while (sym < 144) { state.lens[sym++] = 8; } while (sym < 256) { state.lens[sym++] = 9; } while (sym < 280) { state.lens[sym++] = 7; } while (sym < 288) { state.lens[sym++] = 8; } inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 }); /* distance table */ sym = 0; while (sym < 32) { state.lens[sym++] = 5; } inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 }); /* do this just once */ virgin = false; } state.lencode = lenfix; state.lenbits = 9; state.distcode = distfix; state.distbits = 5; } /* Update the window with the last wsize (normally 32K) bytes written before returning. If window does not exist yet, create it. This is only called when a window is already in use, or when output has been written during this inflate call, but the end of the deflate stream has not been reached yet. It is also called to create a window for dictionary data when a dictionary is loaded. Providing output buffers larger than 32K to inflate() should provide a speed advantage, since only the last 32K of output is copied to the sliding window upon return from inflate(), and since all distances after the first 32K of output will fall in the output data, making match copies simpler and faster. The advantage may be dependent on the size of the processor's data caches. */ function updatewindow(strm, src, end, copy) { var dist; var state = strm.state; /* if it hasn't been done already, allocate space for the window */ if (state.window === null) { state.wsize = 1 << state.wbits; state.wnext = 0; state.whave = 0; state.window = new utils.Buf8(state.wsize); } /* copy state->wsize or less output bytes into the circular window */ if (copy >= state.wsize) { utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0); state.wnext = 0; state.whave = state.wsize; } else { dist = state.wsize - state.wnext; if (dist > copy) { dist = copy; } //zmemcpy(state->window + state->wnext, end - copy, dist); utils.arraySet(state.window, src, end - copy, dist, state.wnext); copy -= dist; if (copy) { //zmemcpy(state->window, end - copy, copy); utils.arraySet(state.window, src, end - copy, copy, 0); state.wnext = copy; state.whave = state.wsize; } else { state.wnext += dist; if (state.wnext === state.wsize) { state.wnext = 0; } if (state.whave < state.wsize) { state.whave += dist; } } } return 0; } function inflate(strm, flush) { var state; var input, output; // input/output buffers var next; /* next input INDEX */ var put; /* next output INDEX */ var have, left; /* available input and output */ var hold; /* bit buffer */ var bits; /* bits in bit buffer */ var _in, _out; /* save starting available input and output */ var copy; /* number of stored or match bytes to copy */ var from; /* where to copy match bytes from */ var from_source; var here = 0; /* current decoding table entry */ var here_bits, here_op, here_val; // paked "here" denormalized (JS specific) //var last; /* parent table entry */ var last_bits, last_op, last_val; // paked "last" denormalized (JS specific) var len; /* length to copy for repeats, bits to drop */ var ret; /* return code */ var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */ var opts; var n; // temporary var for NEED_BITS var order = /* permutation of code lengths */ [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]; if (!strm || !strm.state || !strm.output || (!strm.input && strm.avail_in !== 0)) { return Z_STREAM_ERROR; } state = strm.state; if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */ //--- LOAD() --- put = strm.next_out; output = strm.output; left = strm.avail_out; next = strm.next_in; input = strm.input; have = strm.avail_in; hold = state.hold; bits = state.bits; //--- _in = have; _out = left; ret = Z_OK; inf_leave: // goto emulation for (;;) { switch (state.mode) { case HEAD: if (state.wrap === 0) { state.mode = TYPEDO; break; } //=== NEEDBITS(16); while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */ state.check = 0/*crc32(0L, Z_NULL, 0)*/; //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; state.check = crc32(state.check, hbuf, 2, 0); //===// //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = FLAGS; break; } state.flags = 0; /* expect zlib header */ if (state.head) { state.head.done = false; } if (!(state.wrap & 1) || /* check if zlib header allowed */ (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) { strm.msg = 'incorrect header check'; state.mode = BAD; break; } if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) { strm.msg = 'unknown compression method'; state.mode = BAD; break; } //--- DROPBITS(4) ---// hold >>>= 4; bits -= 4; //---// len = (hold & 0x0f)/*BITS(4)*/ + 8; if (state.wbits === 0) { state.wbits = len; } else if (len > state.wbits) { strm.msg = 'invalid window size'; state.mode = BAD; break; } state.dmax = 1 << len; //Tracev((stderr, "inflate: zlib header ok\n")); strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; state.mode = hold & 0x200 ? DICTID : TYPE; //=== INITBITS(); hold = 0; bits = 0; //===// break; case FLAGS: //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.flags = hold; if ((state.flags & 0xff) !== Z_DEFLATED) { strm.msg = 'unknown compression method'; state.mode = BAD; break; } if (state.flags & 0xe000) { strm.msg = 'unknown header flags set'; state.mode = BAD; break; } if (state.head) { state.head.text = ((hold >> 8) & 1); } if (state.flags & 0x0200) { //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; state.check = crc32(state.check, hbuf, 2, 0); //===// } //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = TIME; /* falls through */ case TIME: //=== NEEDBITS(32); */ while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (state.head) { state.head.time = hold; } if (state.flags & 0x0200) { //=== CRC4(state.check, hold) hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; hbuf[2] = (hold >>> 16) & 0xff; hbuf[3] = (hold >>> 24) & 0xff; state.check = crc32(state.check, hbuf, 4, 0); //=== } //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = OS; /* falls through */ case OS: //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (state.head) { state.head.xflags = (hold & 0xff); state.head.os = (hold >> 8); } if (state.flags & 0x0200) { //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; state.check = crc32(state.check, hbuf, 2, 0); //===// } //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = EXLEN; /* falls through */ case EXLEN: if (state.flags & 0x0400) { //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.length = hold; if (state.head) { state.head.extra_len = hold; } if (state.flags & 0x0200) { //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; state.check = crc32(state.check, hbuf, 2, 0); //===// } //=== INITBITS(); hold = 0; bits = 0; //===// } else if (state.head) { state.head.extra = null/*Z_NULL*/; } state.mode = EXTRA; /* falls through */ case EXTRA: if (state.flags & 0x0400) { copy = state.length; if (copy > have) { copy = have; } if (copy) { if (state.head) { len = state.head.extra_len - state.length; if (!state.head.extra) { // Use untyped array for more conveniend processing later state.head.extra = new Array(state.head.extra_len); } utils.arraySet( state.head.extra, input, next, // extra field is limited to 65536 bytes // - no need for additional size check copy, /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/ len ); //zmemcpy(state.head.extra + len, next, // len + copy > state.head.extra_max ? // state.head.extra_max - len : copy); } if (state.flags & 0x0200) { state.check = crc32(state.check, input, copy, next); } have -= copy; next += copy; state.length -= copy; } if (state.length) { break inf_leave; } } state.length = 0; state.mode = NAME; /* falls through */ case NAME: if (state.flags & 0x0800) { if (have === 0) { break inf_leave; } copy = 0; do { // TODO: 2 or 1 bytes? len = input[next + copy++]; /* use constant limit because in js we should not preallocate memory */ if (state.head && len && (state.length < 65536 /*state.head.name_max*/)) { state.head.name += String.fromCharCode(len); } } while (len && copy < have); if (state.flags & 0x0200) { state.check = crc32(state.check, input, copy, next); } have -= copy; next += copy; if (len) { break inf_leave; } } else if (state.head) { state.head.name = null; } state.length = 0; state.mode = COMMENT; /* falls through */ case COMMENT: if (state.flags & 0x1000) { if (have === 0) { break inf_leave; } copy = 0; do { len = input[next + copy++]; /* use constant limit because in js we should not preallocate memory */ if (state.head && len && (state.length < 65536 /*state.head.comm_max*/)) { state.head.comment += String.fromCharCode(len); } } while (len && copy < have); if (state.flags & 0x0200) { state.check = crc32(state.check, input, copy, next); } have -= copy; next += copy; if (len) { break inf_leave; } } else if (state.head) { state.head.comment = null; } state.mode = HCRC; /* falls through */ case HCRC: if (state.flags & 0x0200) { //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (hold !== (state.check & 0xffff)) { strm.msg = 'header crc mismatch'; state.mode = BAD; break; } //=== INITBITS(); hold = 0; bits = 0; //===// } if (state.head) { state.head.hcrc = ((state.flags >> 9) & 1); state.head.done = true; } strm.adler = state.check = 0; state.mode = TYPE; break; case DICTID: //=== NEEDBITS(32); */ while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// strm.adler = state.check = zswap32(hold); //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = DICT; /* falls through */ case DICT: if (state.havedict === 0) { //--- RESTORE() --- strm.next_out = put; strm.avail_out = left; strm.next_in = next; strm.avail_in = have; state.hold = hold; state.bits = bits; //--- return Z_NEED_DICT; } strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; state.mode = TYPE; /* falls through */ case TYPE: if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; } /* falls through */ case TYPEDO: if (state.last) { //--- BYTEBITS() ---// hold >>>= bits & 7; bits -= bits & 7; //---// state.mode = CHECK; break; } //=== NEEDBITS(3); */ while (bits < 3) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.last = (hold & 0x01)/*BITS(1)*/; //--- DROPBITS(1) ---// hold >>>= 1; bits -= 1; //---// switch ((hold & 0x03)/*BITS(2)*/) { case 0: /* stored block */ //Tracev((stderr, "inflate: stored block%s\n", // state.last ? " (last)" : "")); state.mode = STORED; break; case 1: /* fixed block */ fixedtables(state); //Tracev((stderr, "inflate: fixed codes block%s\n", // state.last ? " (last)" : "")); state.mode = LEN_; /* decode codes */ if (flush === Z_TREES) { //--- DROPBITS(2) ---// hold >>>= 2; bits -= 2; //---// break inf_leave; } break; case 2: /* dynamic block */ //Tracev((stderr, "inflate: dynamic codes block%s\n", // state.last ? " (last)" : "")); state.mode = TABLE; break; case 3: strm.msg = 'invalid block type'; state.mode = BAD; } //--- DROPBITS(2) ---// hold >>>= 2; bits -= 2; //---// break; case STORED: //--- BYTEBITS() ---// /* go to byte boundary */ hold >>>= bits & 7; bits -= bits & 7; //---// //=== NEEDBITS(32); */ while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) { strm.msg = 'invalid stored block lengths'; state.mode = BAD; break; } state.length = hold & 0xffff; //Tracev((stderr, "inflate: stored length %u\n", // state.length)); //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = COPY_; if (flush === Z_TREES) { break inf_leave; } /* falls through */ case COPY_: state.mode = COPY; /* falls through */ case COPY: copy = state.length; if (copy) { if (copy > have) { copy = have; } if (copy > left) { copy = left; } if (copy === 0) { break inf_leave; } //--- zmemcpy(put, next, copy); --- utils.arraySet(output, input, next, copy, put); //---// have -= copy; next += copy; left -= copy; put += copy; state.length -= copy; break; } //Tracev((stderr, "inflate: stored end\n")); state.mode = TYPE; break; case TABLE: //=== NEEDBITS(14); */ while (bits < 14) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257; //--- DROPBITS(5) ---// hold >>>= 5; bits -= 5; //---// state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1; //--- DROPBITS(5) ---// hold >>>= 5; bits -= 5; //---// state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4; //--- DROPBITS(4) ---// hold >>>= 4; bits -= 4; //---// //#ifndef PKZIP_BUG_WORKAROUND if (state.nlen > 286 || state.ndist > 30) { strm.msg = 'too many length or distance symbols'; state.mode = BAD; break; } //#endif //Tracev((stderr, "inflate: table sizes ok\n")); state.have = 0; state.mode = LENLENS; /* falls through */ case LENLENS: while (state.have < state.ncode) { //=== NEEDBITS(3); while (bits < 3) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.lens[order[state.have++]] = (hold & 0x07);//BITS(3); //--- DROPBITS(3) ---// hold >>>= 3; bits -= 3; //---// } while (state.have < 19) { state.lens[order[state.have++]] = 0; } // We have separate tables & no pointers. 2 commented lines below not needed. //state.next = state.codes; //state.lencode = state.next; // Switch to use dynamic table state.lencode = state.lendyn; state.lenbits = 7; opts = { bits: state.lenbits }; ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts); state.lenbits = opts.bits; if (ret) { strm.msg = 'invalid code lengths set'; state.mode = BAD; break; } //Tracev((stderr, "inflate: code lengths ok\n")); state.have = 0; state.mode = CODELENS; /* falls through */ case CODELENS: while (state.have < state.nlen + state.ndist) { for (;;) { here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/ here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if ((here_bits) <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } if (here_val < 16) { //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// state.lens[state.have++] = here_val; } else { if (here_val === 16) { //=== NEEDBITS(here.bits + 2); n = here_bits + 2; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// if (state.have === 0) { strm.msg = 'invalid bit length repeat'; state.mode = BAD; break; } len = state.lens[state.have - 1]; copy = 3 + (hold & 0x03);//BITS(2); //--- DROPBITS(2) ---// hold >>>= 2; bits -= 2; //---// } else if (here_val === 17) { //=== NEEDBITS(here.bits + 3); n = here_bits + 3; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// len = 0; copy = 3 + (hold & 0x07);//BITS(3); //--- DROPBITS(3) ---// hold >>>= 3; bits -= 3; //---// } else { //=== NEEDBITS(here.bits + 7); n = here_bits + 7; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// len = 0; copy = 11 + (hold & 0x7f);//BITS(7); //--- DROPBITS(7) ---// hold >>>= 7; bits -= 7; //---// } if (state.have + copy > state.nlen + state.ndist) { strm.msg = 'invalid bit length repeat'; state.mode = BAD; break; } while (copy--) { state.lens[state.have++] = len; } } } /* handle error breaks in while */ if (state.mode === BAD) { break; } /* check for end-of-block code (better have one) */ if (state.lens[256] === 0) { strm.msg = 'invalid code -- missing end-of-block'; state.mode = BAD; break; } /* build code tables -- note: do not change the lenbits or distbits values here (9 and 6) without reading the comments in inftrees.h concerning the ENOUGH constants, which depend on those values */ state.lenbits = 9; opts = { bits: state.lenbits }; ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts); // We have separate tables & no pointers. 2 commented lines below not needed. // state.next_index = opts.table_index; state.lenbits = opts.bits; // state.lencode = state.next; if (ret) { strm.msg = 'invalid literal/lengths set'; state.mode = BAD; break; } state.distbits = 6; //state.distcode.copy(state.codes); // Switch to use dynamic table state.distcode = state.distdyn; opts = { bits: state.distbits }; ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts); // We have separate tables & no pointers. 2 commented lines below not needed. // state.next_index = opts.table_index; state.distbits = opts.bits; // state.distcode = state.next; if (ret) { strm.msg = 'invalid distances set'; state.mode = BAD; break; } //Tracev((stderr, 'inflate: codes ok\n')); state.mode = LEN_; if (flush === Z_TREES) { break inf_leave; } /* falls through */ case LEN_: state.mode = LEN; /* falls through */ case LEN: if (have >= 6 && left >= 258) { //--- RESTORE() --- strm.next_out = put; strm.avail_out = left; strm.next_in = next; strm.avail_in = have; state.hold = hold; state.bits = bits; //--- inflate_fast(strm, _out); //--- LOAD() --- put = strm.next_out; output = strm.output; left = strm.avail_out; next = strm.next_in; input = strm.input; have = strm.avail_in; hold = state.hold; bits = state.bits; //--- if (state.mode === TYPE) { state.back = -1; } break; } state.back = 0; for (;;) { here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/ here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if (here_bits <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } if (here_op && (here_op & 0xf0) === 0) { last_bits = here_bits; last_op = here_op; last_val = here_val; for (;;) { here = state.lencode[last_val + ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if ((last_bits + here_bits) <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } //--- DROPBITS(last.bits) ---// hold >>>= last_bits; bits -= last_bits; //---// state.back += last_bits; } //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// state.back += here_bits; state.length = here_val; if (here_op === 0) { //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? // "inflate: literal '%c'\n" : // "inflate: literal 0x%02x\n", here.val)); state.mode = LIT; break; } if (here_op & 32) { //Tracevv((stderr, "inflate: end of block\n")); state.back = -1; state.mode = TYPE; break; } if (here_op & 64) { strm.msg = 'invalid literal/length code'; state.mode = BAD; break; } state.extra = here_op & 15; state.mode = LENEXT; /* falls through */ case LENEXT: if (state.extra) { //=== NEEDBITS(state.extra); n = state.extra; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; //--- DROPBITS(state.extra) ---// hold >>>= state.extra; bits -= state.extra; //---// state.back += state.extra; } //Tracevv((stderr, "inflate: length %u\n", state.length)); state.was = state.length; state.mode = DIST; /* falls through */ case DIST: for (;;) { here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/ here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if ((here_bits) <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } if ((here_op & 0xf0) === 0) { last_bits = here_bits; last_op = here_op; last_val = here_val; for (;;) { here = state.distcode[last_val + ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if ((last_bits + here_bits) <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } //--- DROPBITS(last.bits) ---// hold >>>= last_bits; bits -= last_bits; //---// state.back += last_bits; } //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// state.back += here_bits; if (here_op & 64) { strm.msg = 'invalid distance code'; state.mode = BAD; break; } state.offset = here_val; state.extra = (here_op) & 15; state.mode = DISTEXT; /* falls through */ case DISTEXT: if (state.extra) { //=== NEEDBITS(state.extra); n = state.extra; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; //--- DROPBITS(state.extra) ---// hold >>>= state.extra; bits -= state.extra; //---// state.back += state.extra; } //#ifdef INFLATE_STRICT if (state.offset > state.dmax) { strm.msg = 'invalid distance too far back'; state.mode = BAD; break; } //#endif //Tracevv((stderr, "inflate: distance %u\n", state.offset)); state.mode = MATCH; /* falls through */ case MATCH: if (left === 0) { break inf_leave; } copy = _out - left; if (state.offset > copy) { /* copy from window */ copy = state.offset - copy; if (copy > state.whave) { if (state.sane) { strm.msg = 'invalid distance too far back'; state.mode = BAD; break; } // (!) This block is disabled in zlib defailts, // don't enable it for binary compatibility //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR // Trace((stderr, "inflate.c too far\n")); // copy -= state.whave; // if (copy > state.length) { copy = state.length; } // if (copy > left) { copy = left; } // left -= copy; // state.length -= copy; // do { // output[put++] = 0; // } while (--copy); // if (state.length === 0) { state.mode = LEN; } // break; //#endif } if (copy > state.wnext) { copy -= state.wnext; from = state.wsize - copy; } else { from = state.wnext - copy; } if (copy > state.length) { copy = state.length; } from_source = state.window; } else { /* copy from output */ from_source = output; from = put - state.offset; copy = state.length; } if (copy > left) { copy = left; } left -= copy; state.length -= copy; do { output[put++] = from_source[from++]; } while (--copy); if (state.length === 0) { state.mode = LEN; } break; case LIT: if (left === 0) { break inf_leave; } output[put++] = state.length; left--; state.mode = LEN; break; case CHECK: if (state.wrap) { //=== NEEDBITS(32); while (bits < 32) { if (have === 0) { break inf_leave; } have--; // Use '|' insdead of '+' to make sure that result is signed hold |= input[next++] << bits; bits += 8; } //===// _out -= left; strm.total_out += _out; state.total += _out; if (_out) { strm.adler = state.check = /*UPDATE(state.check, put - _out, _out);*/ (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out)); } _out = left; // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too if ((state.flags ? hold : zswap32(hold)) !== state.check) { strm.msg = 'incorrect data check'; state.mode = BAD; break; } //=== INITBITS(); hold = 0; bits = 0; //===// //Tracev((stderr, "inflate: check matches trailer\n")); } state.mode = LENGTH; /* falls through */ case LENGTH: if (state.wrap && state.flags) { //=== NEEDBITS(32); while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (hold !== (state.total & 0xffffffff)) { strm.msg = 'incorrect length check'; state.mode = BAD; break; } //=== INITBITS(); hold = 0; bits = 0; //===// //Tracev((stderr, "inflate: length matches trailer\n")); } state.mode = DONE; /* falls through */ case DONE: ret = Z_STREAM_END; break inf_leave; case BAD: ret = Z_DATA_ERROR; break inf_leave; case MEM: return Z_MEM_ERROR; case SYNC: /* falls through */ default: return Z_STREAM_ERROR; } } // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave" /* Return from inflate(), updating the total counts and the check value. If there was no progress during the inflate() call, return a buffer error. Call updatewindow() to create and/or update the window state. Note: a memory error from inflate() is non-recoverable. */ //--- RESTORE() --- strm.next_out = put; strm.avail_out = left; strm.next_in = next; strm.avail_in = have; state.hold = hold; state.bits = bits; //--- if (state.wsize || (_out !== strm.avail_out && state.mode < BAD && (state.mode < CHECK || flush !== Z_FINISH))) { if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) { state.mode = MEM; return Z_MEM_ERROR; } } _in -= strm.avail_in; _out -= strm.avail_out; strm.total_in += _in; strm.total_out += _out; state.total += _out; if (state.wrap && _out) { strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/ (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out)); } strm.data_type = state.bits + (state.last ? 64 : 0) + (state.mode === TYPE ? 128 : 0) + (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0); if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) { ret = Z_BUF_ERROR; } return ret; } function inflateEnd(strm) { if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) { return Z_STREAM_ERROR; } var state = strm.state; if (state.window) { state.window = null; } strm.state = null; return Z_OK; } function inflateGetHeader(strm, head) { var state; /* check state */ if (!strm || !strm.state) { return Z_STREAM_ERROR; } state = strm.state; if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; } /* save header structure */ state.head = head; head.done = false; return Z_OK; } exports.inflateReset = inflateReset; exports.inflateReset2 = inflateReset2; exports.inflateResetKeep = inflateResetKeep; exports.inflateInit = inflateInit; exports.inflateInit2 = inflateInit2; exports.inflate = inflate; exports.inflateEnd = inflateEnd; exports.inflateGetHeader = inflateGetHeader; exports.inflateInfo = 'pako inflate (from Nodeca project)'; /* Not implemented exports.inflateCopy = inflateCopy; exports.inflateGetDictionary = inflateGetDictionary; exports.inflateMark = inflateMark; exports.inflatePrime = inflatePrime; exports.inflateSetDictionary = inflateSetDictionary; exports.inflateSync = inflateSync; exports.inflateSyncPoint = inflateSyncPoint; exports.inflateUndermine = inflateUndermine; */ },{"../utils/common":85,"./adler32":87,"./crc32":89,"./inffast":92,"./inftrees":94}],94:[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":85}],95:[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) */ }; },{}],96:[function(_dereq_,module,exports){ 'use strict'; var utils = _dereq_('../utils/common'); /* Public constants ==========================================================*/ /* ===========================================================================*/ //var Z_FILTERED = 1; //var Z_HUFFMAN_ONLY = 2; //var Z_RLE = 3; var Z_FIXED = 4; //var Z_DEFAULT_STRATEGY = 0; /* Possible values of the data_type field (though see inflate()) */ var Z_BINARY = 0; var Z_TEXT = 1; //var Z_ASCII = 1; // = Z_TEXT var Z_UNKNOWN = 2; /*============================================================================*/ function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } // From zutil.h var STORED_BLOCK = 0; var STATIC_TREES = 1; var DYN_TREES = 2; /* The three kinds of block type */ var MIN_MATCH = 3; var MAX_MATCH = 258; /* The minimum and maximum match lengths */ // From deflate.h /* =========================================================================== * Internal compression state. */ var LENGTH_CODES = 29; /* number of length codes, not counting the special END_BLOCK code */ var LITERALS = 256; /* number of literal bytes 0..255 */ var L_CODES = LITERALS + 1 + LENGTH_CODES; /* number of Literal or Length codes, including the END_BLOCK code */ var D_CODES = 30; /* number of distance codes */ var BL_CODES = 19; /* number of codes used to transfer the bit lengths */ var HEAP_SIZE = 2 * L_CODES + 1; /* maximum heap size */ var MAX_BITS = 15; /* All codes must not exceed MAX_BITS bits */ var Buf_size = 16; /* size of bit buffer in bi_buf */ /* =========================================================================== * Constants */ var MAX_BL_BITS = 7; /* Bit length codes must not exceed MAX_BL_BITS bits */ var END_BLOCK = 256; /* end of block literal code */ var REP_3_6 = 16; /* repeat previous bit length 3-6 times (2 bits of repeat count) */ var REPZ_3_10 = 17; /* repeat a zero length 3-10 times (3 bits of repeat count) */ var REPZ_11_138 = 18; /* repeat a zero length 11-138 times (7 bits of repeat count) */ /* eslint-disable comma-spacing,array-bracket-spacing */ var extra_lbits = /* extra bits for each length code */ [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]; var extra_dbits = /* extra bits for each distance code */ [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]; var extra_blbits = /* extra bits for each bit length code */ [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]; var bl_order = [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]; /* eslint-enable comma-spacing,array-bracket-spacing */ /* The lengths of the bit length codes are sent in order of decreasing * probability, to avoid transmitting the lengths for unused bit length codes. */ /* =========================================================================== * Local data. These are initialized only once. */ // We pre-fill arrays with 0 to avoid uninitialized gaps var DIST_CODE_LEN = 512; /* see definition of array dist_code below */ // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1 var static_ltree = new Array((L_CODES + 2) * 2); zero(static_ltree); /* The static literal tree. Since the bit lengths are imposed, there is no * need for the L_CODES extra codes used during heap construction. However * The codes 286 and 287 are needed to build a canonical tree (see _tr_init * below). */ var static_dtree = new Array(D_CODES * 2); zero(static_dtree); /* The static distance tree. (Actually a trivial tree since all codes use * 5 bits.) */ var _dist_code = new Array(DIST_CODE_LEN); zero(_dist_code); /* Distance codes. The first 256 values correspond to the distances * 3 .. 258, the last 256 values correspond to the top 8 bits of * the 15 bit distances. */ var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1); zero(_length_code); /* length code for each normalized match length (0 == MIN_MATCH) */ var base_length = new Array(LENGTH_CODES); zero(base_length); /* First normalized length for each code (0 = MIN_MATCH) */ var base_dist = new Array(D_CODES); zero(base_dist); /* First normalized distance for each code (0 = distance of 1) */ function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) { this.static_tree = static_tree; /* static tree or NULL */ this.extra_bits = extra_bits; /* extra bits for each code or NULL */ this.extra_base = extra_base; /* base index for extra_bits */ this.elems = elems; /* max number of elements in the tree */ this.max_length = max_length; /* max bit length for the codes */ // show if `static_tree` has data or dummy - needed for monomorphic objects this.has_stree = static_tree && static_tree.length; } var static_l_desc; var static_d_desc; var static_bl_desc; function TreeDesc(dyn_tree, stat_desc) { this.dyn_tree = dyn_tree; /* the dynamic tree */ this.max_code = 0; /* largest code with non zero frequency */ this.stat_desc = stat_desc; /* the corresponding static tree */ } function d_code(dist) { return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)]; } /* =========================================================================== * Output a short LSB first on the stream. * IN assertion: there is enough room in pendingBuf. */ function put_short(s, w) { // put_byte(s, (uch)((w) & 0xff)); // put_byte(s, (uch)((ush)(w) >> 8)); s.pending_buf[s.pending++] = (w) & 0xff; s.pending_buf[s.pending++] = (w >>> 8) & 0xff; } /* =========================================================================== * Send a value on a given number of bits. * IN assertion: length <= 16 and value fits in length bits. */ function send_bits(s, value, length) { if (s.bi_valid > (Buf_size - length)) { s.bi_buf |= (value << s.bi_valid) & 0xffff; put_short(s, s.bi_buf); s.bi_buf = value >> (Buf_size - s.bi_valid); s.bi_valid += length - Buf_size; } else { s.bi_buf |= (value << s.bi_valid) & 0xffff; s.bi_valid += length; } } function send_code(s, c, tree) { send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/); } /* =========================================================================== * Reverse the first len bits of a code, using straightforward code (a faster * method would use a table) * IN assertion: 1 <= len <= 15 */ function bi_reverse(code, len) { var res = 0; do { res |= code & 1; code >>>= 1; res <<= 1; } while (--len > 0); return res >>> 1; } /* =========================================================================== * Flush the bit buffer, keeping at most 7 bits in it. */ function bi_flush(s) { if (s.bi_valid === 16) { put_short(s, s.bi_buf); s.bi_buf = 0; s.bi_valid = 0; } else if (s.bi_valid >= 8) { s.pending_buf[s.pending++] = s.bi_buf & 0xff; s.bi_buf >>= 8; s.bi_valid -= 8; } } /* =========================================================================== * Compute the optimal bit lengths for a tree and update the total bit length * for the current block. * IN assertion: the fields freq and dad are set, heap[heap_max] and * above are the tree nodes sorted by increasing frequency. * OUT assertions: the field len is set to the optimal bit length, the * array bl_count contains the frequencies for each bit length. * The length opt_len is updated; static_len is also updated if stree is * not null. */ function gen_bitlen(s, desc) // deflate_state *s; // tree_desc *desc; /* the tree descriptor */ { var tree = desc.dyn_tree; var max_code = desc.max_code; var stree = desc.stat_desc.static_tree; var has_stree = desc.stat_desc.has_stree; var extra = desc.stat_desc.extra_bits; var base = desc.stat_desc.extra_base; var max_length = desc.stat_desc.max_length; var h; /* heap index */ var n, m; /* iterate over the tree elements */ var bits; /* bit length */ var xbits; /* extra bits */ var f; /* frequency */ var overflow = 0; /* number of elements with bit length too large */ for (bits = 0; bits <= MAX_BITS; bits++) { s.bl_count[bits] = 0; } /* In a first pass, compute the optimal bit lengths (which may * overflow in the case of the bit length tree). */ tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */ for (h = s.heap_max + 1; h < HEAP_SIZE; h++) { n = s.heap[h]; bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1; if (bits > max_length) { bits = max_length; overflow++; } tree[n * 2 + 1]/*.Len*/ = bits; /* We overwrite tree[n].Dad which is no longer needed */ if (n > max_code) { continue; } /* not a leaf node */ s.bl_count[bits]++; xbits = 0; if (n >= base) { xbits = extra[n - base]; } f = tree[n * 2]/*.Freq*/; s.opt_len += f * (bits + xbits); if (has_stree) { s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits); } } if (overflow === 0) { return; } // Trace((stderr,"\nbit length overflow\n")); /* This happens for example on obj2 and pic of the Calgary corpus */ /* Find the first bit length which could increase: */ do { bits = max_length - 1; while (s.bl_count[bits] === 0) { bits--; } s.bl_count[bits]--; /* move one leaf down the tree */ s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */ s.bl_count[max_length]--; /* The brother of the overflow item also moves one step up, * but this does not affect bl_count[max_length] */ overflow -= 2; } while (overflow > 0); /* Now recompute all bit lengths, scanning in increasing frequency. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all * lengths instead of fixing only the wrong ones. This idea is taken * from 'ar' written by Haruhiko Okumura.) */ for (bits = max_length; bits !== 0; bits--) { n = s.bl_count[bits]; while (n !== 0) { m = s.heap[--h]; if (m > max_code) { continue; } if (tree[m * 2 + 1]/*.Len*/ !== bits) { // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/; tree[m * 2 + 1]/*.Len*/ = bits; } n--; } } } /* =========================================================================== * Generate the codes for a given tree and bit counts (which need not be * optimal). * IN assertion: the array bl_count contains the bit length statistics for * the given tree and the field len is set for all tree elements. * OUT assertion: the field code is set for all tree elements of non * zero code length. */ function gen_codes(tree, max_code, bl_count) // ct_data *tree; /* the tree to decorate */ // int max_code; /* largest code with non zero frequency */ // ushf *bl_count; /* number of codes at each bit length */ { var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */ var code = 0; /* running code value */ var bits; /* bit index */ var n; /* code index */ /* The distribution counts are first used to generate the code values * without bit reversal. */ for (bits = 1; bits <= MAX_BITS; bits++) { next_code[bits] = code = (code + bl_count[bits - 1]) << 1; } /* Check that the bit counts in bl_count are consistent. The last code * must be all ones. */ //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1, // "inconsistent bit counts"); //Tracev((stderr,"\ngen_codes: max_code %d ", max_code)); for (n = 0; n <= max_code; n++) { var len = tree[n * 2 + 1]/*.Len*/; if (len === 0) { continue; } /* Now reverse the bits */ tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len); //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ", // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1)); } } /* =========================================================================== * Initialize the various 'constant' tables. */ function tr_static_init() { var n; /* iterates over tree elements */ var bits; /* bit counter */ var length; /* length value */ var code; /* code value */ var dist; /* distance index */ var bl_count = new Array(MAX_BITS + 1); /* number of codes at each bit length for an optimal tree */ // do check in _tr_init() //if (static_init_done) return; /* For some embedded targets, global variables are not initialized: */ /*#ifdef NO_INIT_GLOBAL_POINTERS static_l_desc.static_tree = static_ltree; static_l_desc.extra_bits = extra_lbits; static_d_desc.static_tree = static_dtree; static_d_desc.extra_bits = extra_dbits; static_bl_desc.extra_bits = extra_blbits; #endif*/ /* Initialize the mapping length (0..255) -> length code (0..28) */ length = 0; for (code = 0; code < LENGTH_CODES - 1; code++) { base_length[code] = length; for (n = 0; n < (1 << extra_lbits[code]); n++) { _length_code[length++] = code; } } //Assert (length == 256, "tr_static_init: length != 256"); /* Note that the length 255 (match length 258) can be represented * in two different ways: code 284 + 5 bits or code 285, so we * overwrite length_code[255] to use the best encoding: */ _length_code[length - 1] = code; /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ dist = 0; for (code = 0; code < 16; code++) { base_dist[code] = dist; for (n = 0; n < (1 << extra_dbits[code]); n++) { _dist_code[dist++] = code; } } //Assert (dist == 256, "tr_static_init: dist != 256"); dist >>= 7; /* from now on, all distances are divided by 128 */ for (; code < D_CODES; code++) { base_dist[code] = dist << 7; for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) { _dist_code[256 + dist++] = code; } } //Assert (dist == 256, "tr_static_init: 256+dist != 512"); /* Construct the codes of the static literal tree */ for (bits = 0; bits <= MAX_BITS; bits++) { bl_count[bits] = 0; } n = 0; while (n <= 143) { static_ltree[n * 2 + 1]/*.Len*/ = 8; n++; bl_count[8]++; } while (n <= 255) { static_ltree[n * 2 + 1]/*.Len*/ = 9; n++; bl_count[9]++; } while (n <= 279) { static_ltree[n * 2 + 1]/*.Len*/ = 7; n++; bl_count[7]++; } while (n <= 287) { static_ltree[n * 2 + 1]/*.Len*/ = 8; n++; bl_count[8]++; } /* Codes 286 and 287 do not exist, but we must include them in the * tree construction to get a canonical Huffman tree (longest code * all ones) */ gen_codes(static_ltree, L_CODES + 1, bl_count); /* The static distance tree is trivial: */ for (n = 0; n < D_CODES; n++) { static_dtree[n * 2 + 1]/*.Len*/ = 5; static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5); } // Now data ready and we can init static trees static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS); static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS); static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS); //static_init_done = true; } /* =========================================================================== * Initialize a new block. */ function init_block(s) { var n; /* iterates over tree elements */ /* Initialize the trees. */ for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; } for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; } for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; } s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1; s.opt_len = s.static_len = 0; s.last_lit = s.matches = 0; } /* =========================================================================== * Flush the bit buffer and align the output on a byte boundary */ function bi_windup(s) { if (s.bi_valid > 8) { put_short(s, s.bi_buf); } else if (s.bi_valid > 0) { //put_byte(s, (Byte)s->bi_buf); s.pending_buf[s.pending++] = s.bi_buf; } s.bi_buf = 0; s.bi_valid = 0; } /* =========================================================================== * Copy a stored block, storing first the length and its * one's complement if requested. */ function copy_block(s, buf, len, header) //DeflateState *s; //charf *buf; /* the input data */ //unsigned len; /* its length */ //int header; /* true if block header must be written */ { bi_windup(s); /* align on byte boundary */ if (header) { put_short(s, len); put_short(s, ~len); } // while (len--) { // put_byte(s, *buf++); // } utils.arraySet(s.pending_buf, s.window, buf, len, s.pending); s.pending += len; } /* =========================================================================== * Compares to subtrees, using the tree depth as tie breaker when * the subtrees have equal frequency. This minimizes the worst case length. */ function smaller(tree, n, m, depth) { var _n2 = n * 2; var _m2 = m * 2; return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ || (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m])); } /* =========================================================================== * Restore the heap property by moving down the tree starting at node k, * exchanging a node with the smallest of its two sons if necessary, stopping * when the heap property is re-established (each father smaller than its * two sons). */ function pqdownheap(s, tree, k) // deflate_state *s; // ct_data *tree; /* the tree to restore */ // int k; /* node to move down */ { var v = s.heap[k]; var j = k << 1; /* left son of k */ while (j <= s.heap_len) { /* Set j to the smallest of the two sons: */ if (j < s.heap_len && smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) { j++; } /* Exit if v is smaller than both sons */ if (smaller(tree, v, s.heap[j], s.depth)) { break; } /* Exchange v with the smallest son */ s.heap[k] = s.heap[j]; k = j; /* And continue down the tree, setting j to the left son of k */ j <<= 1; } s.heap[k] = v; } // inlined manually // var SMALLEST = 1; /* =========================================================================== * Send the block data compressed using the given Huffman trees */ function compress_block(s, ltree, dtree) // deflate_state *s; // const ct_data *ltree; /* literal tree */ // const ct_data *dtree; /* distance tree */ { var dist; /* distance of matched string */ var lc; /* match length or unmatched char (if dist == 0) */ var lx = 0; /* running index in l_buf */ var code; /* the code to send */ var extra; /* number of extra bits to send */ if (s.last_lit !== 0) { do { dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]); lc = s.pending_buf[s.l_buf + lx]; lx++; if (dist === 0) { send_code(s, lc, ltree); /* send a literal byte */ //Tracecv(isgraph(lc), (stderr," '%c' ", lc)); } else { /* Here, lc is the match length - MIN_MATCH */ code = _length_code[lc]; send_code(s, code + LITERALS + 1, ltree); /* send the length code */ extra = extra_lbits[code]; if (extra !== 0) { lc -= base_length[code]; send_bits(s, lc, extra); /* send the extra length bits */ } dist--; /* dist is now the match distance - 1 */ code = d_code(dist); //Assert (code < D_CODES, "bad d_code"); send_code(s, code, dtree); /* send the distance code */ extra = extra_dbits[code]; if (extra !== 0) { dist -= base_dist[code]; send_bits(s, dist, extra); /* send the extra distance bits */ } } /* literal or match pair ? */ /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, // "pendingBuf overflow"); } while (lx < s.last_lit); } send_code(s, END_BLOCK, ltree); } /* =========================================================================== * Construct one Huffman tree and assigns the code bit strings and lengths. * Update the total bit length for the current block. * IN assertion: the field freq is set for all tree elements. * OUT assertions: the fields len and code are set to the optimal bit length * and corresponding code. The length opt_len is updated; static_len is * also updated if stree is not null. The field max_code is set. */ function build_tree(s, desc) // deflate_state *s; // tree_desc *desc; /* the tree descriptor */ { var tree = desc.dyn_tree; var stree = desc.stat_desc.static_tree; var has_stree = desc.stat_desc.has_stree; var elems = desc.stat_desc.elems; var n, m; /* iterate over heap elements */ var max_code = -1; /* largest code with non zero frequency */ var node; /* new node being created */ /* Construct the initial heap, with least frequent element in * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. * heap[0] is not used. */ s.heap_len = 0; s.heap_max = HEAP_SIZE; for (n = 0; n < elems; n++) { if (tree[n * 2]/*.Freq*/ !== 0) { s.heap[++s.heap_len] = max_code = n; s.depth[n] = 0; } else { tree[n * 2 + 1]/*.Len*/ = 0; } } /* The pkzip format requires that at least one distance code exists, * and that at least one bit should be sent even if there is only one * possible code. So to avoid special checks later on we force at least * two codes of non zero frequency. */ while (s.heap_len < 2) { node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0); tree[node * 2]/*.Freq*/ = 1; s.depth[node] = 0; s.opt_len--; if (has_stree) { s.static_len -= stree[node * 2 + 1]/*.Len*/; } /* node is 0 or 1 so it does not have extra bits */ } desc.max_code = max_code; /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, * establish sub-heaps of increasing lengths: */ for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); } /* Construct the Huffman tree by repeatedly combining the least two * frequent nodes. */ node = elems; /* next internal node of the tree */ do { //pqremove(s, tree, n); /* n = node of least frequency */ /*** pqremove ***/ n = s.heap[1/*SMALLEST*/]; s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--]; pqdownheap(s, tree, 1/*SMALLEST*/); /***/ m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */ s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */ s.heap[--s.heap_max] = m; /* Create a new node father of n and m */ tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/; s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node; /* and insert the new node in the heap */ s.heap[1/*SMALLEST*/] = node++; pqdownheap(s, tree, 1/*SMALLEST*/); } while (s.heap_len >= 2); s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/]; /* At this point, the fields freq and dad are set. We can now * generate the bit lengths. */ gen_bitlen(s, desc); /* The field len is now set, we can generate the bit codes */ gen_codes(tree, max_code, s.bl_count); } /* =========================================================================== * Scan a literal or distance tree to determine the frequencies of the codes * in the bit length tree. */ function scan_tree(s, tree, max_code) // deflate_state *s; // ct_data *tree; /* the tree to be scanned */ // int max_code; /* and its largest code of non zero frequency */ { var n; /* iterates over all tree elements */ var prevlen = -1; /* last emitted length */ var curlen; /* length of current code */ var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ var count = 0; /* repeat count of the current code */ var max_count = 7; /* max repeat count */ var min_count = 4; /* min repeat count */ if (nextlen === 0) { max_count = 138; min_count = 3; } tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */ for (n = 0; n <= max_code; n++) { curlen = nextlen; nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; if (++count < max_count && curlen === nextlen) { continue; } else if (count < min_count) { s.bl_tree[curlen * 2]/*.Freq*/ += count; } else if (curlen !== 0) { if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; } s.bl_tree[REP_3_6 * 2]/*.Freq*/++; } else if (count <= 10) { s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++; } else { s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++; } count = 0; prevlen = curlen; if (nextlen === 0) { max_count = 138; min_count = 3; } else if (curlen === nextlen) { max_count = 6; min_count = 3; } else { max_count = 7; min_count = 4; } } } /* =========================================================================== * Send a literal or distance tree in compressed form, using the codes in * bl_tree. */ function send_tree(s, tree, max_code) // deflate_state *s; // ct_data *tree; /* the tree to be scanned */ // int max_code; /* and its largest code of non zero frequency */ { var n; /* iterates over all tree elements */ var prevlen = -1; /* last emitted length */ var curlen; /* length of current code */ var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ var count = 0; /* repeat count of the current code */ var max_count = 7; /* max repeat count */ var min_count = 4; /* min repeat count */ /* tree[max_code+1].Len = -1; */ /* guard already set */ if (nextlen === 0) { max_count = 138; min_count = 3; } for (n = 0; n <= max_code; n++) { curlen = nextlen; nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; if (++count < max_count && curlen === nextlen) { continue; } else if (count < min_count) { do { send_code(s, curlen, s.bl_tree); } while (--count !== 0); } else if (curlen !== 0) { if (curlen !== prevlen) { send_code(s, curlen, s.bl_tree); count--; } //Assert(count >= 3 && count <= 6, " 3_6?"); send_code(s, REP_3_6, s.bl_tree); send_bits(s, count - 3, 2); } else if (count <= 10) { send_code(s, REPZ_3_10, s.bl_tree); send_bits(s, count - 3, 3); } else { send_code(s, REPZ_11_138, s.bl_tree); send_bits(s, count - 11, 7); } count = 0; prevlen = curlen; if (nextlen === 0) { max_count = 138; min_count = 3; } else if (curlen === nextlen) { max_count = 6; min_count = 3; } else { max_count = 7; min_count = 4; } } } /* =========================================================================== * Construct the Huffman tree for the bit lengths and return the index in * bl_order of the last bit length code to send. */ function build_bl_tree(s) { var max_blindex; /* index of last bit length code of non zero freq */ /* Determine the bit length frequencies for literal and distance trees */ scan_tree(s, s.dyn_ltree, s.l_desc.max_code); scan_tree(s, s.dyn_dtree, s.d_desc.max_code); /* Build the bit length tree: */ build_tree(s, s.bl_desc); /* opt_len now includes the length of the tree representations, except * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. */ /* Determine the number of bit length codes to send. The pkzip format * requires that at least 4 bit length codes be sent. (appnote.txt says * 3 but the actual value used is 4.) */ for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) { if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) { break; } } /* Update opt_len to include the bit length tree and counts */ s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4; //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", // s->opt_len, s->static_len)); return max_blindex; } /* =========================================================================== * Send the header for a block using dynamic Huffman trees: the counts, the * lengths of the bit length codes, the literal tree and the distance tree. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. */ function send_all_trees(s, lcodes, dcodes, blcodes) // deflate_state *s; // int lcodes, dcodes, blcodes; /* number of codes for each tree */ { var rank; /* index in bl_order */ //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, // "too many codes"); //Tracev((stderr, "\nbl counts: ")); send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */ send_bits(s, dcodes - 1, 5); send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */ for (rank = 0; rank < blcodes; rank++) { //Tracev((stderr, "\nbl code %2d ", bl_order[rank])); send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3); } //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */ //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */ //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); } /* =========================================================================== * Check if the data type is TEXT or BINARY, using the following algorithm: * - TEXT if the two conditions below are satisfied: * a) There are no non-portable control characters belonging to the * "black list" (0..6, 14..25, 28..31). * b) There is at least one printable character belonging to the * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). * - BINARY otherwise. * - The following partially-portable control characters form a * "gray list" that is ignored in this detection algorithm: * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). * IN assertion: the fields Freq of dyn_ltree are set. */ function detect_data_type(s) { /* black_mask is the bit mask of black-listed bytes * set bits 0..6, 14..25, and 28..31 * 0xf3ffc07f = binary 11110011111111111100000001111111 */ var black_mask = 0xf3ffc07f; var n; /* Check for non-textual ("black-listed") bytes. */ for (n = 0; n <= 31; n++, black_mask >>>= 1) { if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) { return Z_BINARY; } } /* Check for textual ("white-listed") bytes. */ if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) { return Z_TEXT; } for (n = 32; n < LITERALS; n++) { if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) { return Z_TEXT; } } /* There are no "black-listed" or "white-listed" bytes: * this stream either is empty or has tolerated ("gray-listed") bytes only. */ return Z_BINARY; } var static_init_done = false; /* =========================================================================== * Initialize the tree data structures for a new zlib stream. */ function _tr_init(s) { if (!static_init_done) { tr_static_init(); static_init_done = true; } s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc); s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc); s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc); s.bi_buf = 0; s.bi_valid = 0; /* Initialize the first block of the first file: */ init_block(s); } /* =========================================================================== * Send a stored block */ function _tr_stored_block(s, buf, stored_len, last) //DeflateState *s; //charf *buf; /* input block */ //ulg stored_len; /* length of input block */ //int last; /* one if this is the last block for a file */ { send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */ copy_block(s, buf, stored_len, true); /* with header */ } /* =========================================================================== * Send one empty static block to give enough lookahead for inflate. * This takes 10 bits, of which 7 may remain in the bit buffer. */ function _tr_align(s) { send_bits(s, STATIC_TREES << 1, 3); send_code(s, END_BLOCK, static_ltree); bi_flush(s); } /* =========================================================================== * Determine the best encoding for the current block: dynamic trees, static * trees or store, and output the encoded block to the zip file. */ function _tr_flush_block(s, buf, stored_len, last) //DeflateState *s; //charf *buf; /* input block, or NULL if too old */ //ulg stored_len; /* length of input block */ //int last; /* one if this is the last block for a file */ { var opt_lenb, static_lenb; /* opt_len and static_len in bytes */ var max_blindex = 0; /* index of last bit length code of non zero freq */ /* Build the Huffman trees unless a stored block is forced */ if (s.level > 0) { /* Check if the file is binary or text */ if (s.strm.data_type === Z_UNKNOWN) { s.strm.data_type = detect_data_type(s); } /* Construct the literal and distance trees */ build_tree(s, s.l_desc); // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, // s->static_len)); build_tree(s, s.d_desc); // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, // s->static_len)); /* At this point, opt_len and static_len are the total bit lengths of * the compressed block data, excluding the tree representations. */ /* Build the bit length tree for the above two trees, and get the index * in bl_order of the last bit length code to send. */ max_blindex = build_bl_tree(s); /* Determine the best encoding. Compute the block lengths in bytes. */ opt_lenb = (s.opt_len + 3 + 7) >>> 3; static_lenb = (s.static_len + 3 + 7) >>> 3; // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, // s->last_lit)); if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; } } else { // Assert(buf != (char*)0, "lost buf"); opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ } if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) { /* 4: two words for the lengths */ /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. * Otherwise we can't have processed more than WSIZE input bytes since * the last block flush, because compression would have been * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to * transform a block into a stored block. */ _tr_stored_block(s, buf, stored_len, last); } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) { send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3); compress_block(s, static_ltree, static_dtree); } else { send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3); send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1); compress_block(s, s.dyn_ltree, s.dyn_dtree); } // Assert (s->compressed_len == s->bits_sent, "bad compressed size"); /* The above check is made mod 2^32, for files larger than 512 MB * and uLong implemented on 32 bits. */ init_block(s); if (last) { bi_windup(s); } // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, // s->compressed_len-7*last)); } /* =========================================================================== * Save the match info and tally the frequency counts. Return true if * the current block must be flushed. */ function _tr_tally(s, dist, lc) // deflate_state *s; // unsigned dist; /* distance of matched string */ // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ { //var out_length, in_length, dcode; s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff; s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff; s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff; s.last_lit++; if (dist === 0) { /* lc is the unmatched char */ s.dyn_ltree[lc * 2]/*.Freq*/++; } else { s.matches++; /* Here, lc is the match length - MIN_MATCH */ dist--; /* dist = match distance - 1 */ //Assert((ush)dist < (ush)MAX_DIST(s) && // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++; s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++; } // (!) This block is disabled in zlib defailts, // don't enable it for binary compatibility //#ifdef TRUNCATE_BLOCK // /* Try to guess if it is profitable to stop the current block here */ // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) { // /* Compute an upper bound for the compressed length */ // out_length = s.last_lit*8; // in_length = s.strstart - s.block_start; // // for (dcode = 0; dcode < D_CODES; dcode++) { // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]); // } // out_length >>>= 3; // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", // // s->last_lit, in_length, out_length, // // 100L - out_length*100L/in_length)); // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) { // return true; // } // } //#endif return (s.last_lit === s.lit_bufsize - 1); /* We avoid equality with lit_bufsize because of wraparound at 64K * on 16 bit machines and because stored blocks are restricted to * 64K-1 bytes. */ } exports._tr_init = _tr_init; exports._tr_stored_block = _tr_stored_block; exports._tr_flush_block = _tr_flush_block; exports._tr_tally = _tr_tally; exports._tr_align = _tr_align; },{"../utils/common":85}],97:[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; },{}],98:[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; }; },{}],99:[function(_dereq_,module,exports){ 'use strict'; var asap = _dereq_('asap') module.exports = Promise function Promise(fn) { if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new') if (typeof fn !== 'function') throw new TypeError('not a function') var state = null var value = null var deferreds = [] var self = this this.then = function(onFulfilled, onRejected) { return new Promise(function(resolve, reject) { handle(new Handler(onFulfilled, onRejected, resolve, reject)) }) } function handle(deferred) { if (state === null) { deferreds.push(deferred) return } asap(function() { var cb = state ? deferred.onFulfilled : deferred.onRejected if (cb === null) { (state ? deferred.resolve : deferred.reject)(value) return } var ret try { ret = cb(value) } catch (e) { deferred.reject(e) return } deferred.resolve(ret) }) } function resolve(newValue) { try { //Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure if (newValue === self) throw new TypeError('A promise cannot be resolved with itself.') if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) { var then = newValue.then if (typeof then === 'function') { doResolve(then.bind(newValue), resolve, reject) return } } state = true value = newValue finale() } catch (e) { reject(e) } } function reject(newValue) { state = false value = newValue finale() } function finale() { for (var i = 0, len = deferreds.length; i < len; i++) handle(deferreds[i]) deferreds = null } doResolve(fn, resolve, reject) } function Handler(onFulfilled, onRejected, resolve, reject){ this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null this.onRejected = typeof onRejected === 'function' ? onRejected : null this.resolve = resolve this.reject = reject } /** * Take a potentially misbehaving resolver function and make sure * onFulfilled and onRejected are only called once. * * Makes no guarantees about asynchrony. */ function doResolve(fn, onFulfilled, onRejected) { var done = false; try { fn(function (value) { if (done) return done = true onFulfilled(value) }, function (reason) { if (done) return done = true onRejected(reason) }) } catch (ex) { if (done) return done = true onRejected(ex) } } },{"asap":41}],100:[function(_dereq_,module,exports){ 'use strict'; //This file contains then/promise specific extensions to the core promise API var Promise = _dereq_('./core.js') var asap = _dereq_('asap') module.exports = Promise /* Static Functions */ function ValuePromise(value) { this.then = function (onFulfilled) { if (typeof onFulfilled !== 'function') return this return new Promise(function (resolve, reject) { asap(function () { try { resolve(onFulfilled(value)) } catch (ex) { reject(ex); } }) }) } } ValuePromise.prototype = Object.create(Promise.prototype) var TRUE = new ValuePromise(true) var FALSE = new ValuePromise(false) var NULL = new ValuePromise(null) var UNDEFINED = new ValuePromise(undefined) var ZERO = new ValuePromise(0) var EMPTYSTRING = new ValuePromise('') Promise.resolve = function (value) { if (value instanceof Promise) return value if (value === null) return NULL if (value === undefined) return UNDEFINED if (value === true) return TRUE if (value === false) return FALSE if (value === 0) return ZERO if (value === '') return EMPTYSTRING if (typeof value === 'object' || typeof value === 'function') { try { var then = value.then if (typeof then === 'function') { return new Promise(then.bind(value)) } } catch (ex) { return new Promise(function (resolve, reject) { reject(ex) }) } } return new ValuePromise(value) } Promise.from = Promise.cast = function (value) { var err = new Error('Promise.from and Promise.cast are deprecated, use Promise.resolve instead') err.name = 'Warning' console.warn(err.stack) return Promise.resolve(value) } Promise.denodeify = function (fn, argumentCount) { argumentCount = argumentCount || Infinity return function () { var self = this var args = Array.prototype.slice.call(arguments) return new Promise(function (resolve, reject) { while (args.length && args.length > argumentCount) { args.pop() } args.push(function (err, res) { if (err) reject(err) else resolve(res) }) fn.apply(self, args) }) } } Promise.nodeify = function (fn) { return function () { var args = Array.prototype.slice.call(arguments) var callback = typeof args[args.length - 1] === 'function' ? args.pop() : null try { return fn.apply(this, arguments).nodeify(callback) } catch (ex) { if (callback === null || typeof callback == 'undefined') { return new Promise(function (resolve, reject) { reject(ex) }) } else { asap(function () { callback(ex) }) } } } } Promise.all = function () { var calledWithArray = arguments.length === 1 && Array.isArray(arguments[0]) var args = Array.prototype.slice.call(calledWithArray ? arguments[0] : arguments) if (!calledWithArray) { var err = new Error('Promise.all should be called with a single array, calling it with multiple arguments is deprecated') err.name = 'Warning' console.warn(err.stack) } return new Promise(function (resolve, reject) { if (args.length === 0) return resolve([]) var remaining = args.length function res(i, val) { try { if (val && (typeof val === 'object' || typeof val === 'function')) { var then = val.then if (typeof then === 'function') { then.call(val, function (val) { res(i, val) }, reject) return } } args[i] = val if (--remaining === 0) { resolve(args); } } catch (ex) { reject(ex) } } for (var i = 0; i < args.length; i++) { res(i, args[i]) } }) } Promise.reject = function (value) { return new Promise(function (resolve, reject) { reject(value); }); } Promise.race = function (values) { return new Promise(function (resolve, reject) { values.forEach(function(value){ Promise.resolve(value).then(resolve, reject); }) }); } /* Prototype Methods */ Promise.prototype.done = function (onFulfilled, onRejected) { var self = arguments.length ? this.then.apply(this, arguments) : this self.then(null, function (err) { asap(function () { throw err }) }) } Promise.prototype.nodeify = function (callback) { if (typeof callback != 'function') return this this.then(function (value) { asap(function () { callback(null, value) }) }, function (err) { asap(function () { callback(err) }) }) } Promise.prototype['catch'] = function (onRejected) { return this.then(null, onRejected); } },{"./core.js":99,"asap":41}]},{},[1]);
docs/src/modules/components/HomeUsers.js
kybarg/material-ui
import React from 'react'; import PropTypes from 'prop-types'; import { useSelector } from 'react-redux'; import { withStyles } from '@material-ui/core/styles'; import NoSsr from '@material-ui/core/NoSsr'; import Divider from '@material-ui/core/Divider'; import Grid from '@material-ui/core/Grid'; import Container from '@material-ui/core/Container'; import Button from '@material-ui/core/Button'; import Typography from '@material-ui/core/Typography'; const users = [ { logo: 'nasa.png', caption: 'NASA', }, { logo: 'walmart-labs.png', caption: 'Walmart Labs', }, { logo: 'capgemini.png', caption: 'Capgemini', }, { logo: 'uniqlo.png', caption: 'Uniqlo', }, { logo: 'bethesda.png', caption: 'Bethesda', }, { logo: 'jpmorgan.png', caption: 'J.P. Morgan', }, ]; const styles = theme => ({ root: { padding: theme.spacing(2), minHeight: 160, paddingTop: theme.spacing(5), }, container: { paddingTop: theme.spacing(14), paddingBottom: theme.spacing(14), }, grid: { marginTop: theme.spacing(5), marginBottom: theme.spacing(5), }, img: { margin: '12px 24px', }, }); function HomeUsers(props) { const { classes } = props; const t = useSelector(state => state.options.t); return ( <div className={classes.root}> <Divider /> <NoSsr> <Container maxWidth="md" className={classes.container}> <Typography variant="h4" align="center" gutterBottom> {t('whosUsing')} </Typography> <Typography variant="body1" align="center" gutterBottom> {t('joinThese')} </Typography> <Grid container justify="center" className={classes.grid}> {users.map(user => ( <img key={user.caption} src={`/static/images/users/${user.logo}`} alt={user.caption} className={classes.img} /> ))} </Grid> <Typography variant="body1" align="center" gutterBottom> {t('usingMui')} </Typography> <Grid container justify="center"> <Button variant="outlined" href="https://spectrum.chat/material-ui/general/whos-using-material-ui~00e6687a-9b2d-454f-97a6-950d9fde71cf" rel="noopener nofollow" target="_blank" > {t('letUsKnow')} </Button> </Grid> </Container> </NoSsr> </div> ); } HomeUsers.propTypes = { classes: PropTypes.object.isRequired, }; export default withStyles(styles)(HomeUsers);
Console/app/node_modules/antd/lib/progress/progress.js
RisenEsports/RisenEsports.github.io
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends2 = require('babel-runtime/helpers/extends'); var _extends3 = _interopRequireDefault(_extends2); var _defineProperty2 = require('babel-runtime/helpers/defineProperty'); var _defineProperty3 = _interopRequireDefault(_defineProperty2); var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck'); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = require('babel-runtime/helpers/createClass'); var _createClass3 = _interopRequireDefault(_createClass2); var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn'); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = require('babel-runtime/helpers/inherits'); var _inherits3 = _interopRequireDefault(_inherits2); var _propTypes = require('prop-types'); var _propTypes2 = _interopRequireDefault(_propTypes); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _icon = require('../icon'); var _icon2 = _interopRequireDefault(_icon); var _rcProgress = require('rc-progress'); var _classnames = require('classnames'); var _classnames2 = _interopRequireDefault(_classnames); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var __rest = undefined && undefined.__rest || function (s, e) { var t = {}; for (var p in s) { if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; }if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0) t[p[i]] = s[p[i]]; }return t; }; var statusColorMap = { normal: '#108ee9', exception: '#ff5500', success: '#87d068' }; var Progress = function (_React$Component) { (0, _inherits3['default'])(Progress, _React$Component); function Progress() { (0, _classCallCheck3['default'])(this, Progress); return (0, _possibleConstructorReturn3['default'])(this, (Progress.__proto__ || Object.getPrototypeOf(Progress)).apply(this, arguments)); } (0, _createClass3['default'])(Progress, [{ key: 'render', value: function render() { var _classNames; var props = this.props; var prefixCls = props.prefixCls, className = props.className, _props$percent = props.percent, percent = _props$percent === undefined ? 0 : _props$percent, status = props.status, format = props.format, trailColor = props.trailColor, type = props.type, strokeWidth = props.strokeWidth, width = props.width, showInfo = props.showInfo, _props$gapDegree = props.gapDegree, gapDegree = _props$gapDegree === undefined ? 0 : _props$gapDegree, gapPosition = props.gapPosition, restProps = __rest(props, ["prefixCls", "className", "percent", "status", "format", "trailColor", "type", "strokeWidth", "width", "showInfo", "gapDegree", "gapPosition"]); var progressStatus = parseInt(percent.toString(), 10) >= 100 && !('status' in props) ? 'success' : status || 'normal'; var progressInfo = void 0; var progress = void 0; var textFormatter = format || function (percentNumber) { return percentNumber + '%'; }; if (showInfo) { var text = void 0; var iconType = type === 'circle' || type === 'dashboard' ? '' : '-circle'; if (progressStatus === 'exception') { text = format ? textFormatter(percent) : _react2['default'].createElement(_icon2['default'], { type: 'cross' + iconType }); } else if (progressStatus === 'success') { text = format ? textFormatter(percent) : _react2['default'].createElement(_icon2['default'], { type: 'check' + iconType }); } else { text = textFormatter(percent); } progressInfo = _react2['default'].createElement( 'span', { className: prefixCls + '-text' }, text ); } if (type === 'line') { var percentStyle = { width: percent + '%', height: strokeWidth || 10 }; progress = _react2['default'].createElement( 'div', null, _react2['default'].createElement( 'div', { className: prefixCls + '-outer' }, _react2['default'].createElement( 'div', { className: prefixCls + '-inner' }, _react2['default'].createElement('div', { className: prefixCls + '-bg', style: percentStyle }) ) ), progressInfo ); } else if (type === 'circle' || type === 'dashboard') { var circleSize = width || 132; var circleStyle = { width: circleSize, height: circleSize, fontSize: circleSize * 0.16 + 6 }; var circleWidth = strokeWidth || 6; var gapPos = gapPosition || type === 'dashboard' && 'bottom' || 'top'; var gapDeg = gapDegree || type === 'dashboard' && 75; progress = _react2['default'].createElement( 'div', { className: prefixCls + '-inner', style: circleStyle }, _react2['default'].createElement(_rcProgress.Circle, { percent: percent, strokeWidth: circleWidth, trailWidth: circleWidth, strokeColor: statusColorMap[progressStatus], trailColor: trailColor, prefixCls: prefixCls, gapDegree: gapDeg, gapPosition: gapPos }), progressInfo ); } var classString = (0, _classnames2['default'])(prefixCls, (_classNames = {}, (0, _defineProperty3['default'])(_classNames, prefixCls + '-' + (type === 'dashboard' && 'circle' || type), true), (0, _defineProperty3['default'])(_classNames, prefixCls + '-status-' + progressStatus, true), (0, _defineProperty3['default'])(_classNames, prefixCls + '-show-info', showInfo), _classNames), className); return _react2['default'].createElement( 'div', (0, _extends3['default'])({}, restProps, { className: classString }), progress ); } }]); return Progress; }(_react2['default'].Component); exports['default'] = Progress; Progress.defaultProps = { type: 'line', percent: 0, showInfo: true, trailColor: '#f3f3f3', prefixCls: 'ant-progress' }; Progress.propTypes = { status: _propTypes2['default'].oneOf(['normal', 'exception', 'active', 'success']), type: _propTypes2['default'].oneOf(['line', 'circle', 'dashboard']), showInfo: _propTypes2['default'].bool, percent: _propTypes2['default'].number, width: _propTypes2['default'].number, strokeWidth: _propTypes2['default'].number, trailColor: _propTypes2['default'].string, format: _propTypes2['default'].func, gapDegree: _propTypes2['default'].number }; module.exports = exports['default'];
node_modules/core-js/modules/es6.promise.js
hellarafa/ART405-REPFINDER-Project2
'use strict'; var LIBRARY = require('./_library') , global = require('./_global') , ctx = require('./_ctx') , classof = require('./_classof') , $export = require('./_export') , isObject = require('./_is-object') , aFunction = require('./_a-function') , anInstance = require('./_an-instance') , forOf = require('./_for-of') , speciesConstructor = require('./_species-constructor') , task = require('./_task').set , microtask = require('./_microtask')() , PROMISE = 'Promise' , TypeError = global.TypeError , process = global.process , $Promise = global[PROMISE] , process = global.process , isNode = classof(process) == 'process' , empty = function(){ /* empty */ } , Internal, GenericPromiseCapability, Wrapper; var USE_NATIVE = !!function(){ try { // correct subclassing with @@species support var promise = $Promise.resolve(1) , FakePromise = (promise.constructor = {})[require('./_wks')('species')] = function(exec){ exec(empty, empty); }; // unhandled rejections tracking support, NodeJS Promise without it fails @@species test return (isNode || typeof PromiseRejectionEvent == 'function') && promise.then(empty) instanceof FakePromise; } catch(e){ /* empty */ } }(); // helpers var sameConstructor = function(a, b){ // with library wrapper special case return a === b || a === $Promise && b === Wrapper; }; var isThenable = function(it){ var then; return isObject(it) && typeof (then = it.then) == 'function' ? then : false; }; var newPromiseCapability = function(C){ return sameConstructor($Promise, C) ? new PromiseCapability(C) : new GenericPromiseCapability(C); }; var PromiseCapability = GenericPromiseCapability = function(C){ var resolve, reject; this.promise = new C(function($$resolve, $$reject){ if(resolve !== undefined || reject !== undefined)throw TypeError('Bad Promise constructor'); resolve = $$resolve; reject = $$reject; }); this.resolve = aFunction(resolve); this.reject = aFunction(reject); }; var perform = function(exec){ try { exec(); } catch(e){ return {error: e}; } }; var notify = function(promise, isReject){ if(promise._n)return; promise._n = true; var chain = promise._c; microtask(function(){ var value = promise._v , ok = promise._s == 1 , i = 0; var run = function(reaction){ var handler = ok ? reaction.ok : reaction.fail , resolve = reaction.resolve , reject = reaction.reject , domain = reaction.domain , result, then; try { if(handler){ if(!ok){ if(promise._h == 2)onHandleUnhandled(promise); promise._h = 1; } if(handler === true)result = value; else { if(domain)domain.enter(); result = handler(value); if(domain)domain.exit(); } if(result === reaction.promise){ reject(TypeError('Promise-chain cycle')); } else if(then = isThenable(result)){ then.call(result, resolve, reject); } else resolve(result); } else reject(value); } catch(e){ reject(e); } }; while(chain.length > i)run(chain[i++]); // variable length - can't use forEach promise._c = []; promise._n = false; if(isReject && !promise._h)onUnhandled(promise); }); }; var onUnhandled = function(promise){ task.call(global, function(){ var value = promise._v , abrupt, handler, console; if(isUnhandled(promise)){ abrupt = perform(function(){ if(isNode){ process.emit('unhandledRejection', value, promise); } else if(handler = global.onunhandledrejection){ handler({promise: promise, reason: value}); } else if((console = global.console) && console.error){ console.error('Unhandled promise rejection', value); } }); // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should promise._h = isNode || isUnhandled(promise) ? 2 : 1; } promise._a = undefined; if(abrupt)throw abrupt.error; }); }; var isUnhandled = function(promise){ if(promise._h == 1)return false; var chain = promise._a || promise._c , i = 0 , reaction; while(chain.length > i){ reaction = chain[i++]; if(reaction.fail || !isUnhandled(reaction.promise))return false; } return true; }; var onHandleUnhandled = function(promise){ task.call(global, function(){ var handler; if(isNode){ process.emit('rejectionHandled', promise); } else if(handler = global.onrejectionhandled){ handler({promise: promise, reason: promise._v}); } }); }; var $reject = function(value){ var promise = this; if(promise._d)return; promise._d = true; promise = promise._w || promise; // unwrap promise._v = value; promise._s = 2; if(!promise._a)promise._a = promise._c.slice(); notify(promise, true); }; var $resolve = function(value){ var promise = this , then; if(promise._d)return; promise._d = true; promise = promise._w || promise; // unwrap try { if(promise === value)throw TypeError("Promise can't be resolved itself"); if(then = isThenable(value)){ microtask(function(){ var wrapper = {_w: promise, _d: false}; // wrap try { then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1)); } catch(e){ $reject.call(wrapper, e); } }); } else { promise._v = value; promise._s = 1; notify(promise, false); } } catch(e){ $reject.call({_w: promise, _d: false}, e); // wrap } }; // constructor polyfill if(!USE_NATIVE){ // 25.4.3.1 Promise(executor) $Promise = function Promise(executor){ anInstance(this, $Promise, PROMISE, '_h'); aFunction(executor); Internal.call(this); try { executor(ctx($resolve, this, 1), ctx($reject, this, 1)); } catch(err){ $reject.call(this, err); } }; Internal = function Promise(executor){ this._c = []; // <- awaiting reactions this._a = undefined; // <- checked in isUnhandled reactions this._s = 0; // <- state this._d = false; // <- done this._v = undefined; // <- value this._h = 0; // <- rejection state, 0 - default, 1 - handled, 2 - unhandled this._n = false; // <- notify }; Internal.prototype = require('./_redefine-all')($Promise.prototype, { // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected) then: function then(onFulfilled, onRejected){ var reaction = newPromiseCapability(speciesConstructor(this, $Promise)); reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true; reaction.fail = typeof onRejected == 'function' && onRejected; reaction.domain = isNode ? process.domain : undefined; this._c.push(reaction); if(this._a)this._a.push(reaction); if(this._s)notify(this, false); return reaction.promise; }, // 25.4.5.1 Promise.prototype.catch(onRejected) 'catch': function(onRejected){ return this.then(undefined, onRejected); } }); PromiseCapability = function(){ var promise = new Internal; this.promise = promise; this.resolve = ctx($resolve, promise, 1); this.reject = ctx($reject, promise, 1); }; } $export($export.G + $export.W + $export.F * !USE_NATIVE, {Promise: $Promise}); require('./_set-to-string-tag')($Promise, PROMISE); require('./_set-species')(PROMISE); Wrapper = require('./_core')[PROMISE]; // statics $export($export.S + $export.F * !USE_NATIVE, PROMISE, { // 25.4.4.5 Promise.reject(r) reject: function reject(r){ var capability = newPromiseCapability(this) , $$reject = capability.reject; $$reject(r); return capability.promise; } }); $export($export.S + $export.F * (LIBRARY || !USE_NATIVE), PROMISE, { // 25.4.4.6 Promise.resolve(x) resolve: function resolve(x){ // instanceof instead of internal slot check because we should fix it without replacement native Promise core if(x instanceof $Promise && sameConstructor(x.constructor, this))return x; var capability = newPromiseCapability(this) , $$resolve = capability.resolve; $$resolve(x); return capability.promise; } }); $export($export.S + $export.F * !(USE_NATIVE && require('./_iter-detect')(function(iter){ $Promise.all(iter)['catch'](empty); })), PROMISE, { // 25.4.4.1 Promise.all(iterable) all: function all(iterable){ var C = this , capability = newPromiseCapability(C) , resolve = capability.resolve , reject = capability.reject; var abrupt = perform(function(){ var values = [] , index = 0 , remaining = 1; forOf(iterable, false, function(promise){ var $index = index++ , alreadyCalled = false; values.push(undefined); remaining++; C.resolve(promise).then(function(value){ if(alreadyCalled)return; alreadyCalled = true; values[$index] = value; --remaining || resolve(values); }, reject); }); --remaining || resolve(values); }); if(abrupt)reject(abrupt.error); return capability.promise; }, // 25.4.4.4 Promise.race(iterable) race: function race(iterable){ var C = this , capability = newPromiseCapability(C) , reject = capability.reject; var abrupt = perform(function(){ forOf(iterable, false, function(promise){ C.resolve(promise).then(capability.resolve, reject); }); }); if(abrupt)reject(abrupt.error); return capability.promise; } });
src/components/Blocks/withAlignment.js
markdyousef/zen-editor
// @flow import React, { Component } from 'react'; import styled from 'styled-components'; import BoldIcon from '../../icons/image'; import ActionIcon from '../ActionIcon'; type DefaultProps = {}; type Props = { children?: Object }; type State = { inFocus: bool, style: ?Object, alignment: ?string }; export default (WrappedComponent: Function) => { return ( class AlignmentTool extends Component<DefaultProps, Props, State> { static defaultProps: DefaultProps = {}; state: State = { inFocus: false, style: null, alignment: null } props: Props; alignLeft = () => { this.setState({ style: { float: 'left' }, alignment: 'left' }); } alignCenter = () => { this.setState({ style: { marginLeft: 'auto', marginRight: 'auto' }, alignment: 'center' }); } alignRight = () => { this.setState({ style: { float: 'right' }, alignment: 'right' }); } render() { const { children } = this.props; const { inFocus, style, alignment } = this.state; return ( <WrappedComponent {...this.props} setFocus={() => this.setState({ inFocus: !inFocus })} inFocus={inFocus} style={style} alignLeft={this.alignLeft} alignCenter={this.alignCenter} alignRight={this.alignRight} alignment={alignment} > {children && children} </WrappedComponent> ); } } ); }; const Controls = styled.div` border: 1px solid #2D3438; background: #2D3438; border-radius: 2px; border-radius: 3px; box-shadow: 0 1px 3px 0 rgba(220, 220, 220, 1); box-sizing: border-box; display: flex; `; type AlignProps = { alignLeft?: () => void, alignCenter?: () => void, alignRight?: () => void } export const AlignmentTool = ({ alignLeft, alignCenter, alignRight }: AlignProps) => ( <Controls> <ActionIcon onClick={alignLeft}><BoldIcon /></ActionIcon> <ActionIcon onClick={alignCenter}><BoldIcon /></ActionIcon> <ActionIcon onClick={alignRight}><BoldIcon /></ActionIcon> </Controls> );
ajax/libs/jquery.fancytree/2.7.0/jquery.fancytree-all.js
idleberg/cdnjs
/*! * jquery.fancytree.js * Dynamic tree view control, with support for lazy loading of branches. * https://github.com/mar10/fancytree/ * * Copyright (c) 2006-2014, Martin Wendt (http://wwWendt.de) * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.7.0 * @date 2014-12-21T15:57 */ /** Core Fancytree module. */ // Start of local namespace ;(function($, window, document, undefined) { "use strict"; // prevent duplicate loading if ( $.ui && $.ui.fancytree ) { $.ui.fancytree.warn("Fancytree: ignored duplicate include"); return; } /* ***************************************************************************** * Private functions and variables */ function _assert(cond, msg){ // TODO: see qunit.js extractStacktrace() if(!cond){ msg = msg ? ": " + msg : ""; // consoleApply("assert", [!!cond, msg]); $.error("Fancytree assertion failed" + msg); } } _assert($.ui, "Fancytree requires jQuery UI (http://jqueryui.com)"); function consoleApply(method, args){ var i, s, fn = window.console ? window.console[method] : null; if(fn){ try{ fn.apply(window.console, args); } catch(e) { // IE 8? s = ""; for( i=0; i<args.length; i++){ s += args[i]; } fn(s); } } } /*Return true if x is a FancytreeNode.*/ function _isNode(x){ return !!(x.tree && x.statusNodeType !== undefined); } /** Return true if dotted version string is equal or higher than requested version. * * See http://jsfiddle.net/mar10/FjSAN/ */ function isVersionAtLeast(dottedVersion, major, minor, patch){ var i, v, t, verParts = $.map($.trim(dottedVersion).split("."), function(e){ return parseInt(e, 10); }), testParts = $.map(Array.prototype.slice.call(arguments, 1), function(e){ return parseInt(e, 10); }); for( i = 0; i < testParts.length; i++ ){ v = verParts[i] || 0; t = testParts[i] || 0; if( v !== t ){ return ( v > t ); } } return true; } /** Return a wrapper that calls sub.methodName() and exposes * this : tree * this._local : tree.ext.EXTNAME * this._super : base.methodName() */ function _makeVirtualFunction(methodName, tree, base, extension, extName){ // $.ui.fancytree.debug("_makeVirtualFunction", methodName, tree, base, extension, extName); // if(rexTestSuper && !rexTestSuper.test(func)){ // // extension.methodName() doesn't call _super(), so no wrapper required // return func; // } // Use an immediate function as closure var proxy = (function(){ var prevFunc = tree[methodName], // org. tree method or prev. proxy baseFunc = extension[methodName], // _local = tree.ext[extName], _super = function(){ return prevFunc.apply(tree, arguments); }; // Return the wrapper function return function(){ var prevLocal = tree._local, prevSuper = tree._super; try{ tree._local = _local; tree._super = _super; return baseFunc.apply(tree, arguments); }finally{ tree._local = prevLocal; tree._super = prevSuper; } }; })(); // end of Immediate Function return proxy; } /** * Subclass `base` by creating proxy functions */ function _subclassObject(tree, base, extension, extName){ // $.ui.fancytree.debug("_subclassObject", tree, base, extension, extName); for(var attrName in extension){ if(typeof extension[attrName] === "function"){ if(typeof tree[attrName] === "function"){ // override existing method tree[attrName] = _makeVirtualFunction(attrName, tree, base, extension, extName); }else if(attrName.charAt(0) === "_"){ // Create private methods in tree.ext.EXTENSION namespace tree.ext[extName][attrName] = _makeVirtualFunction(attrName, tree, base, extension, extName); }else{ $.error("Could not override tree." + attrName + ". Use prefix '_' to create tree." + extName + "._" + attrName); } }else{ // Create member variables in tree.ext.EXTENSION namespace if(attrName !== "options"){ tree.ext[extName][attrName] = extension[attrName]; } } } } function _getResolvedPromise(context, argArray){ if(context === undefined){ return $.Deferred(function(){this.resolve();}).promise(); }else{ return $.Deferred(function(){this.resolveWith(context, argArray);}).promise(); } } function _getRejectedPromise(context, argArray){ if(context === undefined){ return $.Deferred(function(){this.reject();}).promise(); }else{ return $.Deferred(function(){this.rejectWith(context, argArray);}).promise(); } } function _makeResolveFunc(deferred, context){ return function(){ deferred.resolveWith(context); }; } function _getElementDataAsDict($el){ // Evaluate 'data-NAME' attributes with special treatment for 'data-json'. var d = $.extend({}, $el.data()), json = d.json; delete d.fancytree; // added to container by widget factory if( json ) { delete d.json; // <li data-json='...'> is already returned as object (http://api.jquery.com/data/#data-html5) d = $.extend(d, json); } return d; } // TODO: use currying function _makeNodeTitleMatcher(s){ s = s.toLowerCase(); return function(node){ return node.title.toLowerCase().indexOf(s) >= 0; }; } function _makeNodeTitleStartMatcher(s){ var reMatch = new RegExp("^" + s, "i"); return function(node){ return reMatch.test(node.title); }; } var i, FT = null, // initialized below ENTITY_MAP = {"&": "&amp;", "<": "&lt;", ">": "&gt;", "\"": "&quot;", "'": "&#39;", "/": "&#x2F;"}, IGNORE_KEYCODES = { 16: true, 17: true, 18: true }, SPECIAL_KEYCODES = { 8: "backspace", 9: "tab", 10: "return", 13: "return", // 16: null, 17: null, 18: null, // ignore shift, ctrl, 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", 45: "insert", 46: "del", 59: ";", 61: "=", 96: "0", 97: "1", 98: "2", 99: "3", 100: "4", 101: "5", 102: "6", 103: "7", 104: "8", 105: "9", 106: "*", 107: "+", 109: "-", 110: ".", 111: "/", 112: "f1", 113: "f2", 114: "f3", 115: "f4", 116: "f5", 117: "f6", 118: "f7", 119: "f8", 120: "f9", 121: "f10", 122: "f11", 123: "f12", 144: "numlock", 145: "scroll", 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", 221: "]", 222: "'"}, //boolean attributes that can be set with equivalent class names in the LI tags CLASS_ATTRS = "active expanded focus folder hideCheckbox lazy selected unselectable".split(" "), CLASS_ATTR_MAP = {}, // Top-level Fancytree node attributes, that can be set by dict NODE_ATTRS = "expanded extraClasses folder hideCheckbox key lazy refKey selected title tooltip unselectable".split(" "), NODE_ATTR_MAP = {}, // Attribute names that should NOT be added to node.data NONE_NODE_DATA_MAP = {"active": true, "children": true, "data": true, "focus": true}; for(i=0; i<CLASS_ATTRS.length; i++){ CLASS_ATTR_MAP[CLASS_ATTRS[i]] = true; } for(i=0; i<NODE_ATTRS.length; i++){ NODE_ATTR_MAP[NODE_ATTRS[i]] = true; } /* ***************************************************************************** * FancytreeNode */ /** * Creates a new FancytreeNode * * @class FancytreeNode * @classdesc A FancytreeNode represents the hierarchical data model and operations. * * @param {FancytreeNode} parent * @param {NodeData} obj * * @property {Fancytree} tree The tree instance * @property {FancytreeNode} parent The parent node * @property {string} key Node id (must be unique inside the tree) * @property {string} title Display name (may contain HTML) * @property {object} data Contains all extra data that was passed on node creation * @property {FancytreeNode[] | null | undefined} children Array of child nodes.<br> * For lazy nodes, null or undefined means 'not yet loaded'. Use an empty array * to define a node that has no children. * @property {boolean} expanded Use isExpanded(), setExpanded() to access this property. * @property {string} extraClasses Addtional CSS classes, added to the node's `&lt;span>` * @property {boolean} folder Folder nodes have different default icons and click behavior.<br> * Note: Also non-folders may have children. * @property {string} statusNodeType null or type of temporarily generated system node like 'loading', or 'error'. * @property {boolean} lazy True if this node is loaded on demand, i.e. on first expansion. * @property {boolean} selected Use isSelected(), setSelected() to access this property. * @property {string} tooltip Alternative description used as hover banner */ function FancytreeNode(parent, obj){ var i, l, name, cl; this.parent = parent; this.tree = parent.tree; this.ul = null; this.li = null; // <li id='key' ftnode=this> tag this.statusNodeType = null; // if this is a temp. node to display the status of its parent this._isLoading = false; // if this node itself is loading this._error = null; // {message: '...'} if a load error occured this.data = {}; // TODO: merge this code with node.toDict() // copy attributes from obj object for(i=0, l=NODE_ATTRS.length; i<l; i++){ name = NODE_ATTRS[i]; this[name] = obj[name]; } // node.data += obj.data if(obj.data){ $.extend(this.data, obj.data); } // copy all other attributes to this.data.NAME for(name in obj){ if(!NODE_ATTR_MAP[name] && !$.isFunction(obj[name]) && !NONE_NODE_DATA_MAP[name]){ // node.data.NAME = obj.NAME this.data[name] = obj[name]; } } // Fix missing key if( this.key == null ){ // test for null OR undefined if( this.tree.options.defaultKey ) { this.key = this.tree.options.defaultKey(this); _assert(this.key, "defaultKey() must return a unique key"); } else { this.key = "_" + (FT._nextNodeKey++); } } else { this.key = "" + this.key; // Convert to string (#217) } // Fix tree.activeNode // TODO: not elegant: we use obj.active as marker to set tree.activeNode // when loading from a dictionary. if(obj.active){ _assert(this.tree.activeNode === null, "only one active node allowed"); this.tree.activeNode = this; } if( obj.selected ){ // #186 this.tree.lastSelectedNode = this; } // TODO: handle obj.focus = true // Create child nodes this.children = null; cl = obj.children; if(cl && cl.length){ this._setChildren(cl); } // Add to key/ref map (except for root node) // if( parent ) { this.tree._callHook("treeRegisterNode", this.tree, true, this); // } } FancytreeNode.prototype = /** @lends FancytreeNode# */{ /* Return the direct child FancytreeNode with a given key, index. */ _findDirectChild: function(ptr){ var i, l, cl = this.children; if(cl){ if(typeof ptr === "string"){ for(i=0, l=cl.length; i<l; i++){ if(cl[i].key === ptr){ return cl[i]; } } }else if(typeof ptr === "number"){ return this.children[ptr]; }else if(ptr.parent === this){ return ptr; } } return null; }, // TODO: activate() // TODO: activateSilently() /* Internal helper called in recursive addChildren sequence.*/ _setChildren: function(children){ _assert(children && (!this.children || this.children.length === 0), "only init supported"); this.children = []; for(var i=0, l=children.length; i<l; i++){ this.children.push(new FancytreeNode(this, children[i])); } }, /** * Append (or insert) a list of child nodes. * * @param {NodeData[]} children array of child node definitions (also single child accepted) * @param {FancytreeNode | string | Integer} [insertBefore] child node (or key or index of such). * If omitted, the new children are appended. * @returns {FancytreeNode} first child added * * @see FancytreeNode#applyPatch */ addChildren: function(children, insertBefore){ var i, l, pos, firstNode = null, nodeList = []; if($.isPlainObject(children) ){ children = [children]; } if(!this.children){ this.children = []; } for(i=0, l=children.length; i<l; i++){ nodeList.push(new FancytreeNode(this, children[i])); } firstNode = nodeList[0]; if(insertBefore == null){ this.children = this.children.concat(nodeList); }else{ insertBefore = this._findDirectChild(insertBefore); pos = $.inArray(insertBefore, this.children); _assert(pos >= 0, "insertBefore must be an existing child"); // insert nodeList after children[pos] this.children.splice.apply(this.children, [pos, 0].concat(nodeList)); } if( !this.parent || this.parent.ul || this.tr ){ // render if the parent was rendered (or this is a root node) this.render(); } if( this.tree.options.selectMode === 3 ){ this.fixSelection3FromEndNodes(); } return firstNode; }, /** * Append or prepend a node, or append a child node. * * This a convenience function that calls addChildren() * * @param {NodeData} node node definition * @param {string} [mode=child] 'before', 'after', 'firstChild', or 'child' ('over' is a synonym for 'child') * @returns {FancytreeNode} new node */ addNode: function(node, mode){ if(mode === undefined || mode === "over"){ mode = "child"; } switch(mode){ case "after": return this.getParent().addChildren(node, this.getNextSibling()); case "before": return this.getParent().addChildren(node, this); case "firstChild": // Insert before the first child if any var insertBefore = (this.children ? this.children[0] : null); return this.addChildren(node, insertBefore); case "child": case "over": return this.addChildren(node); } _assert(false, "Invalid mode: " + mode); }, /** * Append new node after this. * * This a convenience function that calls addNode(node, 'after') * * @param {NodeData} node node definition * @returns {FancytreeNode} new node */ appendSibling: function(node){ return this.addNode(node, "after"); }, /** * Modify existing child nodes. * * @param {NodePatch} patch * @returns {$.Promise} * @see FancytreeNode#addChildren */ applyPatch: function(patch) { // patch [key, null] means 'remove' if(patch === null){ this.remove(); return _getResolvedPromise(this); } // TODO: make sure that root node is not collapsed or modified // copy (most) attributes to node.ATTR or node.data.ATTR var name, promise, v, IGNORE_MAP = { children: true, expanded: true, parent: true }; // TODO: should be global for(name in patch){ v = patch[name]; if( !IGNORE_MAP[name] && !$.isFunction(v)){ if(NODE_ATTR_MAP[name]){ this[name] = v; }else{ this.data[name] = v; } } } // Remove and/or create children if(patch.hasOwnProperty("children")){ this.removeChildren(); if(patch.children){ // only if not null and not empty list // TODO: addChildren instead? this._setChildren(patch.children); } // TODO: how can we APPEND or INSERT child nodes? } if(this.isVisible()){ this.renderTitle(); this.renderStatus(); } // Expand collapse (final step, since this may be async) if(patch.hasOwnProperty("expanded")){ promise = this.setExpanded(patch.expanded); }else{ promise = _getResolvedPromise(this); } return promise; }, /** Collapse all sibling nodes. * @returns {$.Promise} */ collapseSiblings: function() { return this.tree._callHook("nodeCollapseSiblings", this); }, /** Copy this node as sibling or child of `node`. * * @param {FancytreeNode} node source node * @param {string} [mode=child] 'before' | 'after' | 'child' * @param {Function} [map] callback function(NodeData) that could modify the new node * @returns {FancytreeNode} new */ copyTo: function(node, mode, map) { return node.addNode(this.toDict(true, map), mode); }, /** Count direct and indirect children. * * @param {boolean} [deep=true] pass 'false' to only count direct children * @returns {int} number of child nodes */ countChildren: function(deep) { var cl = this.children, i, l, n; if( !cl ){ return 0; } n = cl.length; if(deep !== false){ for(i=0, l=n; i<l; i++){ n += cl[i].countChildren(); } } return n; }, // TODO: deactivate() /** Write to browser console if debugLevel >= 2 (prepending node info) * * @param {*} msg string or object or array of such */ debug: function(msg){ if( this.tree.options.debugLevel >= 2 ) { Array.prototype.unshift.call(arguments, this.toString()); consoleApply("log", arguments); } }, /** Deprecated. * @deprecated since 2014-02-16. Use resetLazy() instead. */ discard: function(){ this.warn("FancytreeNode.discard() is deprecated since 2014-02-16. Use .resetLazy() instead."); return this.resetLazy(); }, // TODO: expand(flag) /**Find all nodes that contain `match` in the title. * * @param {string | function(node)} match string to search for, of a function that * returns `true` if a node is matched. * @returns {FancytreeNode[]} array of nodes (may be empty) * @see FancytreeNode#findAll */ findAll: function(match) { match = $.isFunction(match) ? match : _makeNodeTitleMatcher(match); var res = []; this.visit(function(n){ if(match(n)){ res.push(n); } }); return res; }, /**Find first node that contains `match` in the title (not including self). * * @param {string | function(node)} match string to search for, of a function that * returns `true` if a node is matched. * @returns {FancytreeNode} matching node or null * @example * <b>fat</b> text */ findFirst: function(match) { match = $.isFunction(match) ? match : _makeNodeTitleMatcher(match); var res = null; this.visit(function(n){ if(match(n)){ res = n; return false; } }); return res; }, /* Apply selection state (internal use only) */ _changeSelectStatusAttrs: function (state) { var changed = false; switch(state){ case false: changed = ( this.selected || this.partsel ); this.selected = false; this.partsel = false; break; case true: changed = ( !this.selected || !this.partsel ); this.selected = true; this.partsel = true; break; case undefined: changed = ( this.selected || !this.partsel ); this.selected = false; this.partsel = true; break; default: _assert(false, "invalid state: " + state); } // this.debug("fixSelection3AfterLoad() _changeSelectStatusAttrs()", state, changed); if( changed ){ this.renderStatus(); } return changed; }, /** * Fix selection status, after this node was (de)selected in multi-hier mode. * This includes (de)selecting all children. */ fixSelection3AfterClick: function() { var flag = this.isSelected(); // this.debug("fixSelection3AfterClick()"); this.visit(function(node){ node._changeSelectStatusAttrs(flag); }); this.fixSelection3FromEndNodes(); }, /** * Fix selection status for multi-hier mode. * Only end-nodes are considered to update the descendants branch and parents. * Should be called after this node has loaded new children or after * children have been modified using the API. */ fixSelection3FromEndNodes: function() { // this.debug("fixSelection3FromEndNodes()"); _assert(this.tree.options.selectMode === 3, "expected selectMode 3"); // Visit all end nodes and adjust their parent's `selected` and `partsel` // attributes. Return selection state true, false, or undefined. function _walk(node){ var i, l, child, s, state, allSelected,someSelected, children = node.children; if( children && children.length ){ // check all children recursively allSelected = true; someSelected = false; for( i=0, l=children.length; i<l; i++ ){ child = children[i]; // the selection state of a node is not relevant; we need the end-nodes s = _walk(child); if( s !== false ) { someSelected = true; } if( s !== true ) { allSelected = false; } } state = allSelected ? true : (someSelected ? undefined : false); }else{ // This is an end-node: simply report the status // state = ( node.unselectable ) ? undefined : !!node.selected; state = !!node.selected; } node._changeSelectStatusAttrs(state); return state; } _walk(this); // Update parent's state this.visitParents(function(node){ var i, l, child, state, children = node.children, allSelected = true, someSelected = false; for( i=0, l=children.length; i<l; i++ ){ child = children[i]; // When fixing the parents, we trust the sibling status (i.e. // we don't recurse) if( child.selected || child.partsel ) { someSelected = true; } if( !child.unselectable && !child.selected ) { allSelected = false; } } state = allSelected ? true : (someSelected ? undefined : false); node._changeSelectStatusAttrs(state); }); }, // TODO: focus() /** * Update node data. If dict contains 'children', then also replace * the hole sub tree. * @param {NodeData} dict * * @see FancytreeNode#addChildren * @see FancytreeNode#applyPatch */ fromDict: function(dict) { // copy all other attributes to this.data.xxx for(var name in dict){ if(NODE_ATTR_MAP[name]){ // node.NAME = dict.NAME this[name] = dict[name]; }else if(name === "data"){ // node.data += dict.data $.extend(this.data, dict.data); }else if(!$.isFunction(dict[name]) && !NONE_NODE_DATA_MAP[name]){ // node.data.NAME = dict.NAME this.data[name] = dict[name]; } } if(dict.children){ // recursively set children and render this.removeChildren(); this.addChildren(dict.children); } this.renderTitle(); /* var children = dict.children; if(children === undefined){ this.data = $.extend(this.data, dict); this.render(); return; } dict = $.extend({}, dict); dict.children = undefined; this.data = $.extend(this.data, dict); this.removeChildren(); this.addChild(children); */ }, /** Return the list of child nodes (undefined for unexpanded lazy nodes). * @returns {FancytreeNode[] | undefined} */ getChildren: function() { if(this.hasChildren() === undefined){ // TODO: only required for lazy nodes? return undefined; // Lazy node: unloaded, currently loading, or load error } return this.children; }, /** Return the first child node or null. * @returns {FancytreeNode | null} */ getFirstChild: function() { return this.children ? this.children[0] : null; }, /** Return the 0-based child index. * @returns {int} */ getIndex: function() { // return this.parent.children.indexOf(this); return $.inArray(this, this.parent.children); // indexOf doesn't work in IE7 }, /** Return the hierarchical child index (1-based, e.g. '3.2.4'). * @returns {string} */ getIndexHier: function(separator) { separator = separator || "."; var res = []; $.each(this.getParentList(false, true), function(i, o){ res.push(o.getIndex() + 1); }); return res.join(separator); }, /** Return the parent keys separated by options.keyPathSeparator, e.g. "id_1/id_17/id_32". * @param {boolean} [excludeSelf=false] * @returns {string} */ getKeyPath: function(excludeSelf) { var path = [], sep = this.tree.options.keyPathSeparator; this.visitParents(function(n){ if(n.parent){ path.unshift(n.key); } }, !excludeSelf); return sep + path.join(sep); }, /** Return the last child of this node or null. * @returns {FancytreeNode | null} */ getLastChild: function() { return this.children ? this.children[this.children.length - 1] : null; }, /** Return node depth. 0: System root node, 1: visible top-level node, 2: first sub-level, ... . * @returns {int} */ getLevel: function() { var level = 0, dtn = this.parent; while( dtn ) { level++; dtn = dtn.parent; } return level; }, /** Return the successor node (under the same parent) or null. * @returns {FancytreeNode | null} */ getNextSibling: function() { // TODO: use indexOf, if available: (not in IE6) if( this.parent ){ var i, l, ac = this.parent.children; for(i=0, l=ac.length-1; i<l; i++){ // up to length-2, so next(last) = null if( ac[i] === this ){ return ac[i+1]; } } } return null; }, /** Return the parent node (null for the system root node). * @returns {FancytreeNode | null} */ getParent: function() { // TODO: return null for top-level nodes? return this.parent; }, /** Return an array of all parent nodes (top-down). * @param {boolean} [includeRoot=false] Include the invisible system root node. * @param {boolean} [includeSelf=false] Include the node itself. * @returns {FancytreeNode[]} */ getParentList: function(includeRoot, includeSelf) { var l = [], dtn = includeSelf ? this : this.parent; while( dtn ) { if( includeRoot || dtn.parent ){ l.unshift(dtn); } dtn = dtn.parent; } return l; }, /** Return the predecessor node (under the same parent) or null. * @returns {FancytreeNode | null} */ getPrevSibling: function() { if( this.parent ){ var i, l, ac = this.parent.children; for(i=1, l=ac.length; i<l; i++){ // start with 1, so prev(first) = null if( ac[i] === this ){ return ac[i-1]; } } } return null; }, /** Return true if node has children. Return undefined if not sure, i.e. the node is lazy and not yet loaded). * @returns {boolean | undefined} */ hasChildren: function() { if(this.lazy){ if(this.children == null ){ // null or undefined: Not yet loaded return undefined; }else if(this.children.length === 0){ // Loaded, but response was empty return false; }else if(this.children.length === 1 && this.children[0].isStatusNode() ){ // Currently loading or load error return undefined; } return true; } return !!( this.children && this.children.length ); }, /** Return true if node has keyboard focus. * @returns {boolean} */ hasFocus: function() { return (this.tree.hasFocus() && this.tree.focusNode === this); }, /** Write to browser console if debugLevel >= 1 (prepending node info) * * @param {*} msg string or object or array of such */ info: function(msg){ if( this.tree.options.debugLevel >= 1 ) { Array.prototype.unshift.call(arguments, this.toString()); consoleApply("info", arguments); } }, /** Return true if node is active (see also FancytreeNode#isSelected). * @returns {boolean} */ isActive: function() { return (this.tree.activeNode === this); }, /** Return true if node is a direct child of otherNode. * @param {FancytreeNode} otherNode * @returns {boolean} */ isChildOf: function(otherNode) { return (this.parent && this.parent === otherNode); }, /** Return true, if node is a direct or indirect sub node of otherNode. * @param {FancytreeNode} otherNode * @returns {boolean} */ isDescendantOf: function(otherNode) { if(!otherNode || otherNode.tree !== this.tree){ return false; } var p = this.parent; while( p ) { if( p === otherNode ){ return true; } p = p.parent; } return false; }, /** Return true if node is expanded. * @returns {boolean} */ isExpanded: function() { return !!this.expanded; }, /** Return true if node is the first node of its parent's children. * @returns {boolean} */ isFirstSibling: function() { var p = this.parent; return !p || p.children[0] === this; }, /** Return true if node is a folder, i.e. has the node.folder attribute set. * @returns {boolean} */ isFolder: function() { return !!this.folder; }, /** Return true if node is the last node of its parent's children. * @returns {boolean} */ isLastSibling: function() { var p = this.parent; return !p || p.children[p.children.length-1] === this; }, /** Return true if node is lazy (even if data was already loaded) * @returns {boolean} */ isLazy: function() { return !!this.lazy; }, /** Return true if node is lazy and loaded. For non-lazy nodes always return true. * @returns {boolean} */ isLoaded: function() { return !this.lazy || this.hasChildren() !== undefined; // Also checks if the only child is a status node }, /** Return true if children are currently beeing loaded, i.e. a Ajax request is pending. * @returns {boolean} */ isLoading: function() { return !!this._isLoading; }, /** * @deprecated since v2.4.0: Use isRootNode() instead */ isRoot: function() { return this.isRootNode(); }, /** Return true if this is the (invisible) system root node. * @returns {boolean} */ isRootNode: function() { return (this.tree.rootNode === this); }, /** Return true if node is selected, i.e. has a checkmark set (see also FancytreeNode#isActive). * @returns {boolean} */ isSelected: function() { return !!this.selected; }, /** Return true if this node is a temporarily generated system node like * 'loading', or 'error' (node.statusNodeType contains the type). * @returns {boolean} */ isStatusNode: function() { return !!this.statusNodeType; }, /** Return true if this a top level node, i.e. a direct child of the (invisible) system root node. * @returns {boolean} */ isTopLevel: function() { return (this.tree.rootNode === this.parent); }, /** Return true if node is lazy and not yet loaded. For non-lazy nodes always return false. * @returns {boolean} */ isUndefined: function() { return this.hasChildren() === undefined; // also checks if the only child is a status node }, /** Return true if all parent nodes are expanded. Note: this does not check * whether the node is scrolled into the visible part of the screen. * @returns {boolean} */ isVisible: function() { var i, l, parents = this.getParentList(false, false); for(i=0, l=parents.length; i<l; i++){ if( ! parents[i].expanded ){ return false; } } return true; }, /** Deprecated. * @deprecated since 2014-02-16: use load() instead. */ lazyLoad: function(discard) { this.warn("FancytreeNode.lazyLoad() is deprecated since 2014-02-16. Use .load() instead."); return this.load(discard); }, /** * Load all children of a lazy node if neccessary. The *expanded* state is maintained. * @param {boolean} [forceReload=false] Pass true to discard any existing nodes before. * @returns {$.Promise} */ load: function(forceReload) { var res, source, that = this; _assert( this.isLazy(), "load() requires a lazy node" ); // _assert( forceReload || this.isUndefined(), "Pass forceReload=true to re-load a lazy node" ); if( !forceReload && !this.isUndefined() ) { return _getResolvedPromise(this); } if( this.isLoaded() ){ this.resetLazy(); // also collapses } // This method is also called by setExpanded() and loadKeyPath(), so we // have to avoid recursion. source = this.tree._triggerNodeEvent("lazyLoad", this); if( source === false ) { // #69 return _getResolvedPromise(this); } _assert(typeof source !== "boolean", "lazyLoad event must return source in data.result"); res = this.tree._callHook("nodeLoadChildren", this, source); if( this.expanded ) { res.always(function(){ that.render(); }); } return res; }, /** Expand all parents and optionally scroll into visible area as neccessary. * Promise is resolved, when lazy loading and animations are done. * @param {object} [opts] passed to `setExpanded()`. * Defaults to {noAnimation: false, noEvents: false, scrollIntoView: true} * @returns {$.Promise} */ makeVisible: function(opts) { var i, that = this, deferreds = [], dfd = new $.Deferred(), parents = this.getParentList(false, false), len = parents.length, effects = !(opts && opts.noAnimation === true), scroll = !(opts && opts.scrollIntoView === false); // Expand bottom-up, so only the top node is animated for(i = len - 1; i >= 0; i--){ // that.debug("pushexpand" + parents[i]); deferreds.push(parents[i].setExpanded(true, opts)); } $.when.apply($, deferreds).done(function(){ // All expands have finished // that.debug("expand DONE", scroll); if( scroll ){ that.scrollIntoView(effects).done(function(){ // that.debug("scroll DONE"); dfd.resolve(); }); } else { dfd.resolve(); } }); return dfd.promise(); }, /** Move this node to targetNode. * @param {FancytreeNode} targetNode * @param {string} mode <pre> * 'child': append this node as last child of targetNode. * This is the default. To be compatble with the D'n'd * hitMode, we also accept 'over'. * 'before': add this node as sibling before targetNode. * 'after': add this node as sibling after targetNode.</pre> * @param {function} [map] optional callback(FancytreeNode) to allow modifcations */ moveTo: function(targetNode, mode, map) { if(mode === undefined || mode === "over"){ mode = "child"; } var pos, prevParent = this.parent, targetParent = (mode === "child") ? targetNode : targetNode.parent; if(this === targetNode){ return; }else if( !this.parent ){ throw "Cannot move system root"; }else if( targetParent.isDescendantOf(this) ){ throw "Cannot move a node to its own descendant"; } // Unlink this node from current parent if( this.parent.children.length === 1 ) { if( this.parent === targetParent ){ return; // #258 } this.parent.children = this.parent.lazy ? [] : null; this.parent.expanded = false; } else { pos = $.inArray(this, this.parent.children); _assert(pos >= 0); this.parent.children.splice(pos, 1); } // Remove from source DOM parent // if(this.parent.ul){ // this.parent.ul.removeChild(this.li); // } // Insert this node to target parent's child list this.parent = targetParent; if( targetParent.hasChildren() ) { switch(mode) { case "child": // Append to existing target children targetParent.children.push(this); break; case "before": // Insert this node before target node pos = $.inArray(targetNode, targetParent.children); _assert(pos >= 0); targetParent.children.splice(pos, 0, this); break; case "after": // Insert this node after target node pos = $.inArray(targetNode, targetParent.children); _assert(pos >= 0); targetParent.children.splice(pos+1, 0, this); break; default: throw "Invalid mode " + mode; } } else { targetParent.children = [ this ]; } // Parent has no <ul> tag yet: // if( !targetParent.ul ) { // // This is the parent's first child: create UL tag // // (Hidden, because it will be // targetParent.ul = document.createElement("ul"); // targetParent.ul.style.display = "none"; // targetParent.li.appendChild(targetParent.ul); // } // // Issue 319: Add to target DOM parent (only if node was already rendered(expanded)) // if(this.li){ // targetParent.ul.appendChild(this.li); // }^ // Let caller modify the nodes if( map ){ targetNode.visit(map, true); } // Handle cross-tree moves if( this.tree !== targetNode.tree ) { // Fix node.tree for all source nodes // _assert(false, "Cross-tree move is not yet implemented."); this.warn("Cross-tree moveTo is experimantal!"); this.visit(function(n){ // TODO: fix selection state and activation, ... n.tree = targetNode.tree; }, true); } // A collaposed node won't re-render children, so we have to remove it manually // if( !targetParent.expanded ){ // prevParent.ul.removeChild(this.li); // } // Update HTML markup if( !prevParent.isDescendantOf(targetParent)) { prevParent.render(); } if( !targetParent.isDescendantOf(prevParent) && targetParent !== prevParent) { targetParent.render(); } // TODO: fix selection state // TODO: fix active state /* var tree = this.tree; var opts = tree.options; var pers = tree.persistence; // Always expand, if it's below minExpandLevel // tree.logDebug ("%s._addChildNode(%o), l=%o", this, ftnode, ftnode.getLevel()); if ( opts.minExpandLevel >= ftnode.getLevel() ) { // tree.logDebug ("Force expand for %o", ftnode); this.bExpanded = true; } // In multi-hier mode, update the parents selection state // DT issue #82: only if not initializing, because the children may not exist yet // if( !ftnode.data.isStatusNode() && opts.selectMode==3 && !isInitializing ) // ftnode._fixSelectionState(); // In multi-hier mode, update the parents selection state if( ftnode.bSelected && opts.selectMode==3 ) { var p = this; while( p ) { if( !p.hasSubSel ) p._setSubSel(true); p = p.parent; } } // render this node and the new child if ( tree.bEnableUpdate ) this.render(); return ftnode; */ }, /** Set focus relative to this node and optionally activate. * * @param {number} where The keyCode that would normally trigger this move, * e.g. `$.ui.keyCode.LEFT` would collapse the node if it * is expanded or move to the parent oterwise. * @param {boolean} [activate=true] * @returns {$.Promise} */ // navigate: function(where, activate) { // console.time("navigate") // this._navigate(where, activate) // console.timeEnd("navigate") // }, navigate: function(where, activate) { var i, parents, handled = true, KC = $.ui.keyCode, sib = null; // Navigate to node function _goto(n){ if( n ){ try { n.makeVisible(); } catch(e) {} // #272 // Node may still be hidden by a filter if( ! $(n.span).is(":visible") ) { n.debug("Navigate: skipping hidden node"); n.navigate(where, activate); return; } return activate === false ? n.setFocus() : n.setActive(); } } switch( where ) { case KC.BACKSPACE: if( this.parent && this.parent.parent ) { _goto(this.parent); } break; case KC.LEFT: if( this.expanded ) { this.setExpanded(false); _goto(this); } else if( this.parent && this.parent.parent ) { _goto(this.parent); } break; case KC.RIGHT: if( !this.expanded && (this.children || this.lazy) ) { this.setExpanded(); _goto(this); } else if( this.children && this.children.length ) { _goto(this.children[0]); } break; case KC.UP: sib = this.getPrevSibling(); // #359: skip hidden sibling nodes, preventing a _goto() recursion while( sib && !$(sib.span).is(":visible") ) { sib = sib.getPrevSibling(); } while( sib && sib.expanded && sib.children && sib.children.length ) { sib = sib.children[sib.children.length - 1]; } if( !sib && this.parent && this.parent.parent ){ sib = this.parent; } _goto(sib); break; case KC.DOWN: if( this.expanded && this.children && this.children.length ) { sib = this.children[0]; } else { parents = this.getParentList(false, true); for(i=parents.length-1; i>=0; i--) { sib = parents[i].getNextSibling(); // #359: skip hidden sibling nodes, preventing a _goto() recursion while( sib && !$(sib.span).is(":visible") ) { sib = sib.getNextSibling(); } if( sib ){ break; } } } _goto(sib); break; default: handled = false; } }, /** * Remove this node (not allowed for system root). */ remove: function() { return this.parent.removeChild(this); }, /** * Remove childNode from list of direct children. * @param {FancytreeNode} childNode */ removeChild: function(childNode) { return this.tree._callHook("nodeRemoveChild", this, childNode); }, /** * Remove all child nodes and descendents. This converts the node into a leaf.<br> * If this was a lazy node, it is still considered 'loaded'; call node.resetLazy() * in order to trigger lazyLoad on next expand. */ removeChildren: function() { return this.tree._callHook("nodeRemoveChildren", this); }, /** * This method renders and updates all HTML markup that is required * to display this node in its current state.<br> * Note: * <ul> * <li>It should only be neccessary to call this method after the node object * was modified by direct access to its properties, because the common * API methods (node.setTitle(), moveTo(), addChildren(), remove(), ...) * already handle this. * <li> {@link FancytreeNode#renderTitle} and {@link FancytreeNode#renderStatus} * are implied. If changes are more local, calling only renderTitle() or * renderStatus() may be sufficient and faster. * <li>If a node was created/removed, node.render() must be called <i>on the parent</i>. * </ul> * * @param {boolean} [force=false] re-render, even if html markup was already created * @param {boolean} [deep=false] also render all descendants, even if parent is collapsed */ render: function(force, deep) { return this.tree._callHook("nodeRender", this, force, deep); }, /** Create HTML markup for the node's outer <span> (expander, checkbox, icon, and title). * @see Fancytree_Hooks#nodeRenderTitle */ renderTitle: function() { return this.tree._callHook("nodeRenderTitle", this); }, /** Update element's CSS classes according to node state. * @see Fancytree_Hooks#nodeRenderStatus */ renderStatus: function() { return this.tree._callHook("nodeRenderStatus", this); }, /** * Remove all children, collapse, and set the lazy-flag, so that the lazyLoad * event is triggered on next expand. */ resetLazy: function() { this.removeChildren(); this.expanded = false; this.lazy = true; this.children = undefined; this.renderStatus(); }, /** Schedule activity for delayed execution (cancel any pending request). * scheduleAction('cancel') will only cancel a pending request (if any). * @param {string} mode * @param {number} ms */ scheduleAction: function(mode, ms) { if( this.tree.timer ) { clearTimeout(this.tree.timer); // this.tree.debug("clearTimeout(%o)", this.tree.timer); } this.tree.timer = null; var self = this; // required for closures switch (mode) { case "cancel": // Simply made sure that timer was cleared break; case "expand": this.tree.timer = setTimeout(function(){ self.tree.debug("setTimeout: trigger expand"); self.setExpanded(true); }, ms); break; case "activate": this.tree.timer = setTimeout(function(){ self.tree.debug("setTimeout: trigger activate"); self.setActive(true); }, ms); break; default: throw "Invalid mode " + mode; } // this.tree.debug("setTimeout(%s, %s): %s", mode, ms, this.tree.timer); }, /** * * @param {boolean | PlainObject} [effects=false] animation options. * @param {object} [options=null] {topNode: null, effects: ..., parent: ...} this node will remain visible in * any case, even if `this` is outside the scroll pane. * @returns {$.Promise} */ scrollIntoView: function(effects, options) { if( options !== undefined && _isNode(options) ) { this.warn("scrollIntoView() with 'topNode' option is deprecated since 2014-05-08. Use 'options.topNode' instead."); options = {topNode: options}; } // this.$scrollParent = (this.options.scrollParent === "auto") ? $ul.scrollParent() : $(this.options.scrollParent); // this.$scrollParent = this.$scrollParent.length ? this.$scrollParent || this.$container; var topNodeY, nodeY, horzScrollbarHeight, containerOffsetTop, opts = $.extend({ effects: (effects === true) ? {duration: 200, queue: false} : effects, scrollOfs: this.tree.options.scrollOfs, scrollParent: this.tree.options.scrollParent || this.tree.$container, topNode: null }, options), dfd = new $.Deferred(), that = this, nodeHeight = $(this.span).height(), $container = $(opts.scrollParent), topOfs = opts.scrollOfs.top || 0, bottomOfs = opts.scrollOfs.bottom || 0, containerHeight = $container.height(),// - topOfs - bottomOfs, scrollTop = $container.scrollTop(), $animateTarget = $container, isParentWindow = $container[0] === window, topNode = opts.topNode || null, newScrollTop = null; // this.debug("scrollIntoView(), scrollTop=", scrollTop, opts.scrollOfs); _assert($(this.span).is(":visible"), "scrollIntoView node is invisible"); // otherwise we cannot calc offsets if( isParentWindow ) { nodeY = $(this.span).offset().top; topNodeY = (topNode && topNode.span) ? $(topNode.span).offset().top : 0; $animateTarget = $("html,body"); } else { _assert($container[0] !== document && $container[0] !== document.body, "scrollParent should be an simple element or `window`, not document or body."); containerOffsetTop = $container.offset().top, nodeY = $(this.span).offset().top - containerOffsetTop + scrollTop; // relative to scroll parent topNodeY = topNode ? $(topNode.span).offset().top - containerOffsetTop + scrollTop : 0; horzScrollbarHeight = Math.max(0, ($container.innerHeight() - $container[0].clientHeight)); containerHeight -= horzScrollbarHeight; } // this.debug(" scrollIntoView(), nodeY=", nodeY, "containerHeight=", containerHeight); if( nodeY < (scrollTop + topOfs) ){ // Node is above visible container area newScrollTop = nodeY - topOfs; // this.debug(" scrollIntoView(), UPPER newScrollTop=", newScrollTop); }else if((nodeY + nodeHeight) > (scrollTop + containerHeight - bottomOfs)){ newScrollTop = nodeY + nodeHeight - containerHeight + bottomOfs; // this.debug(" scrollIntoView(), LOWER newScrollTop=", newScrollTop); // If a topNode was passed, make sure that it is never scrolled // outside the upper border if(topNode){ _assert(topNode.isRoot() || $(topNode.span).is(":visible"), "topNode must be visible"); if( topNodeY < newScrollTop ){ newScrollTop = topNodeY - topOfs; // this.debug(" scrollIntoView(), TOP newScrollTop=", newScrollTop); } } } if(newScrollTop !== null){ // this.debug(" scrollIntoView(), SET newScrollTop=", newScrollTop); if(opts.effects){ opts.effects.complete = function(){ dfd.resolveWith(that); }; $animateTarget.stop(true).animate({ scrollTop: newScrollTop }, opts.effects); }else{ $animateTarget[0].scrollTop = newScrollTop; dfd.resolveWith(this); } }else{ dfd.resolveWith(this); } return dfd.promise(); }, /**Activate this node. * @param {boolean} [flag=true] pass false to deactivate * @param {object} [opts] additional options. Defaults to {noEvents: false} * @returns {$.Promise} */ setActive: function(flag, opts){ return this.tree._callHook("nodeSetActive", this, flag, opts); }, /**Expand or collapse this node. Promise is resolved, when lazy loading and animations are done. * @param {boolean} [flag=true] pass false to collapse * @param {object} [opts] additional options. Defaults to {noAnimation: false, noEvents: false} * @returns {$.Promise} */ setExpanded: function(flag, opts){ return this.tree._callHook("nodeSetExpanded", this, flag, opts); }, /**Set keyboard focus to this node. * @param {boolean} [flag=true] pass false to blur * @see Fancytree#setFocus */ setFocus: function(flag){ return this.tree._callHook("nodeSetFocus", this, flag); }, /**Select this node, i.e. check the checkbox. * @param {boolean} [flag=true] pass false to deselect */ setSelected: function(flag){ return this.tree._callHook("nodeSetSelected", this, flag); }, /**Mark a lazy node as 'error', 'loading', or 'ok'. * @param {string} status 'error', 'ok' * @param {string} [message] * @param {string} [details] */ setStatus: function(status, message, details){ return this.tree._callHook("nodeSetStatus", this, status, message, details); }, /**Rename this node. * @param {string} title */ setTitle: function(title){ this.title = title; this.renderTitle(); }, /**Sort child list by title. * @param {function} [cmp] custom compare function(a, b) that returns -1, 0, or 1 (defaults to sort by title). * @param {boolean} [deep=false] pass true to sort all descendant nodes */ sortChildren: function(cmp, deep) { var i,l, cl = this.children; if( !cl ){ return; } cmp = cmp || function(a, b) { var x = a.title.toLowerCase(), y = b.title.toLowerCase(); return x === y ? 0 : x > y ? 1 : -1; }; cl.sort(cmp); if( deep ){ for(i=0, l=cl.length; i<l; i++){ if( cl[i].children ){ cl[i].sortChildren(cmp, "$norender$"); } } } if( deep !== "$norender$" ){ this.render(); } }, /** Convert node (or whole branch) into a plain object. * * The result is compatible with node.addChildren(). * * @param {boolean} [recursive=false] include child nodes * @param {function} [callback] callback(dict) is called for every node, in order to allow modifications * @returns {NodeData} */ toDict: function(recursive, callback) { var i, l, node, dict = {}, self = this; $.each(NODE_ATTRS, function(i, a){ if(self[a] || self[a] === false){ dict[a] = self[a]; } }); if(!$.isEmptyObject(this.data)){ dict.data = $.extend({}, this.data); if($.isEmptyObject(dict.data)){ delete dict.data; } } if( callback ){ callback(dict); } if( recursive ) { if(this.hasChildren()){ dict.children = []; for(i=0, l=this.children.length; i<l; i++ ){ node = this.children[i]; if( !node.isStatusNode() ){ dict.children.push(node.toDict(true, callback)); } } }else{ // dict.children = null; } } return dict; }, /** Flip expanded status. */ toggleExpanded: function(){ return this.tree._callHook("nodeToggleExpanded", this); }, /** Flip selection status. */ toggleSelected: function(){ return this.tree._callHook("nodeToggleSelected", this); }, toString: function() { return "<FancytreeNode(#" + this.key + ", '" + this.title + "')>"; }, /** Call fn(node) for all child nodes.<br> * Stop iteration, if fn() returns false. Skip current branch, if fn() returns "skip".<br> * Return false if iteration was stopped. * * @param {function} fn the callback function. * Return false to stop iteration, return "skip" to skip this node and * its children only. * @param {boolean} [includeSelf=false] * @returns {boolean} */ visit: function(fn, includeSelf) { var i, l, res = true, children = this.children; if( includeSelf === true ) { res = fn(this); if( res === false || res === "skip" ){ return res; } } if(children){ for(i=0, l=children.length; i<l; i++){ res = children[i].visit(fn, true); if( res === false ){ break; } } } return res; }, /** Call fn(node) for all child nodes and recursively load lazy children.<br> * <b>Note:</b> If you need this method, you probably should consider to review * your architecture! Recursivley loading nodes is a perfect way for lazy * programmers to flood the server with requests ;-) * * @param {function} [fn] optional callback function. * Return false to stop iteration, return "skip" to skip this node and * its children only. * @param {boolean} [includeSelf=false] * @returns {$.Promise} */ visitAndLoad: function(fn, includeSelf, _recursion) { var dfd, res, loaders, node = this; // node.debug("visitAndLoad"); if( fn && includeSelf === true ) { res = fn(node); if( res === false || res === "skip" ) { return _recursion ? res : _getResolvedPromise(); } } if( !node.children && !node.lazy ) { return _getResolvedPromise(); } dfd = new $.Deferred(); loaders = []; // node.debug("load()..."); node.load().done(function(){ // node.debug("load()... done."); for(var i=0, l=node.children.length; i<l; i++){ res = node.children[i].visitAndLoad(fn, true, true); if( res === false ) { dfd.reject(); break; } else if ( res !== "skip" ) { loaders.push(res); // Add promise to the list } } $.when.apply(this, loaders).then(function(){ dfd.resolve(); }); }); return dfd.promise(); }, /** Call fn(node) for all parent nodes, bottom-up, including invisible system root.<br> * Stop iteration, if fn() returns false.<br> * Return false if iteration was stopped. * * @param {function} fn the callback function. * Return false to stop iteration, return "skip" to skip this node and children only. * @param {boolean} [includeSelf=false] * @returns {boolean} */ visitParents: function(fn, includeSelf) { // Visit parent nodes (bottom up) if(includeSelf && fn(this) === false){ return false; } var p = this.parent; while( p ) { if(fn(p) === false){ return false; } p = p.parent; } return true; }, /** Write warning to browser console (prepending node info) * * @param {*} msg string or object or array of such */ warn: function(msg){ Array.prototype.unshift.call(arguments, this.toString()); consoleApply("warn", arguments); } }; /* ***************************************************************************** * Fancytree */ /** * Construct a new tree object. * * @class Fancytree * @classdesc The controller behind a fancytree. * This class also contains 'hook methods': see {@link Fancytree_Hooks}. * * @param {Widget} widget * * @property {FancytreeOptions} options * @property {FancytreeNode} rootNode * @property {FancytreeNode} activeNode * @property {FancytreeNode} focusNode * @property {jQueryObject} $div * @property {object} widget * @property {object} ext * @property {object} data * @property {object} options * @property {string} _id * @property {string} statusClassPropName * @property {string} ariaPropName * @property {string} nodeContainerAttrName * @property {string} $container * @property {FancytreeNode} lastSelectedNode */ function Fancytree(widget) { this.widget = widget; this.$div = widget.element; this.options = widget.options; if( this.options ) { if( $.isFunction(this.options.lazyload ) && !$.isFunction(this.options.lazyLoad) ) { this.options.lazyLoad = function() { FT.warn("The 'lazyload' event is deprecated since 2014-02-25. Use 'lazyLoad' (with uppercase L) instead."); return widget.options.lazyload.apply(this, arguments); }; } if( $.isFunction(this.options.loaderror) ) { $.error("The 'loaderror' event was renamed since 2014-07-03. Use 'loadError' (with uppercase E) instead."); } if( this.options.fx !== undefined ) { FT.warn("The 'fx' options was replaced by 'toggleEffect' since 2014-11-30."); } } this.ext = {}; // Active extension instances // allow to init tree.data.foo from <div data-foo=''> this.data = _getElementDataAsDict(this.$div); this._id = $.ui.fancytree._nextId++; this._ns = ".fancytree-" + this._id; // append for namespaced events this.activeNode = null; this.focusNode = null; this._hasFocus = null; this.lastSelectedNode = null; this.systemFocusElement = null; this.lastQuicksearchTerm = ""; this.lastQuicksearchTime = 0; this.statusClassPropName = "span"; this.ariaPropName = "li"; this.nodeContainerAttrName = "li"; // Remove previous markup if any this.$div.find(">ul.fancytree-container").remove(); // Create a node without parent. var fakeParent = { tree: this }, $ul; this.rootNode = new FancytreeNode(fakeParent, { title: "root", key: "root_" + this._id, children: null, expanded: true }); this.rootNode.parent = null; // Create root markup $ul = $("<ul>", { "class": "ui-fancytree fancytree-container" }).appendTo(this.$div); this.$container = $ul; this.rootNode.ul = $ul[0]; if(this.options.debugLevel == null){ this.options.debugLevel = FT.debugLevel; } // Add container to the TAB chain // See http://www.w3.org/TR/wai-aria-practices/#focus_activedescendant this.$container.attr("tabindex", this.options.tabbable ? "0" : "-1"); if(this.options.aria){ this.$container .attr("role", "tree") .attr("aria-multiselectable", true); } } Fancytree.prototype = /** @lends Fancytree# */{ /* Return a context object that can be re-used for _callHook(). * @param {Fancytree | FancytreeNode | EventData} obj * @param {Event} originalEvent * @param {Object} extra * @returns {EventData} */ _makeHookContext: function(obj, originalEvent, extra) { var ctx, tree; if(obj.node !== undefined){ // obj is already a context object if(originalEvent && obj.originalEvent !== originalEvent){ $.error("invalid args"); } ctx = obj; }else if(obj.tree){ // obj is a FancytreeNode tree = obj.tree; ctx = { node: obj, tree: tree, widget: tree.widget, options: tree.widget.options, originalEvent: originalEvent }; }else if(obj.widget){ // obj is a Fancytree ctx = { node: null, tree: obj, widget: obj.widget, options: obj.widget.options, originalEvent: originalEvent }; }else{ $.error("invalid args"); } if(extra){ $.extend(ctx, extra); } return ctx; }, /* Trigger a hook function: funcName(ctx, [...]). * * @param {string} funcName * @param {Fancytree|FancytreeNode|EventData} contextObject * @param {any} [_extraArgs] optional additional arguments * @returns {any} */ _callHook: function(funcName, contextObject, _extraArgs) { var ctx = this._makeHookContext(contextObject), fn = this[funcName], args = Array.prototype.slice.call(arguments, 2); if(!$.isFunction(fn)){ $.error("_callHook('" + funcName + "') is not a function"); } args.unshift(ctx); // this.debug("_hook", funcName, ctx.node && ctx.node.toString() || ctx.tree.toString(), args); return fn.apply(this, args); }, /* Check if current extensions dependencies are met and throw an error if not. * * This method may be called inside the `treeInit` hook for custom extensions. * * @param {string} extension name of the required extension * @param {boolean} [required=true] pass `false` if the extension is optional, but we want to check for order if it is present * @param {boolean} [before] `true` if `name` must be included before this, `false` otherwise (use `null` if order doesn't matter) * @param {string} [message] optional error message (defaults to a descriptve error message) */ _requireExtension: function(name, required, before, message) { before = !!before; var thisName = this._local.name, extList = this.options.extensions, isBefore = $.inArray(name, extList) < $.inArray(thisName, extList), isMissing = required && this.ext[name] == null, badOrder = !isMissing && before != null && (before !== isBefore); _assert(thisName && thisName !== name); if( isMissing || badOrder ){ if( !message ){ if( isMissing || required ){ message = "'" + thisName + "' extension requires '" + name + "'"; if( badOrder ){ message += " to be registered " + (before ? "before" : "after") + " itself"; } }else{ message = "If used together, `" + name + "` must be registered " + (before ? "before" : "after") + " `" + thisName + "`"; } } $.error(message); return false; } return true; }, /** Activate node with a given key and fire focus and activate events. * * A prevously activated node will be deactivated. * If activeVisible option is set, all parents will be expanded as necessary. * Pass key = false, to deactivate the current node only. * @param {string} key * @returns {FancytreeNode} activated node (null, if not found) */ activateKey: function(key) { var node = this.getNodeByKey(key); if(node){ node.setActive(); }else if(this.activeNode){ this.activeNode.setActive(false); } return node; }, /** (experimental) * * @param {Array} patchList array of [key, NodePatch] arrays * @returns {$.Promise} resolved, when all patches have been applied * @see TreePatch */ applyPatch: function(patchList) { var dfd, i, p2, key, patch, node, patchCount = patchList.length, deferredList = []; for(i=0; i<patchCount; i++){ p2 = patchList[i]; _assert(p2.length === 2, "patchList must be an array of length-2-arrays"); key = p2[0]; patch = p2[1]; node = (key === null) ? this.rootNode : this.getNodeByKey(key); if(node){ dfd = new $.Deferred(); deferredList.push(dfd); node.applyPatch(patch).always(_makeResolveFunc(dfd, node)); }else{ this.warn("could not find node with key '" + key + "'"); } } // Return a promise that is resovled, when ALL patches were applied return $.when.apply($, deferredList).promise(); }, /* TODO: implement in dnd extension cancelDrag: function() { var dd = $.ui.ddmanager.current; if(dd){ dd.cancel(); } }, */ /** Return the number of nodes. * @returns {integer} */ count: function() { return this.rootNode.countChildren(); }, /** Write to browser console if debugLevel >= 2 (prepending tree name) * * @param {*} msg string or object or array of such */ debug: function(msg){ if( this.options.debugLevel >= 2 ) { Array.prototype.unshift.call(arguments, this.toString()); consoleApply("log", arguments); } }, // TODO: disable() // TODO: enable() // TODO: enableUpdate() /** Find the next visible node that starts with `match`, starting at `startNode` * and wrap-around at the end. * * @param {string|function} match * @param {FancytreeNode} [startNode] defaults to first node * @returns {FancytreeNode} matching node or null */ findNextNode: function(match, startNode, visibleOnly) { var stopNode = null, parentChildren = startNode.parent.children, matchingNode = null, walkVisible = function(parent, idx, fn) { var i, grandParent, parentChildren = parent.children, siblingCount = parentChildren.length, node = parentChildren[idx]; // visit node itself if( node && fn(node) === false ) { return false; } // visit descendants if( node && node.children && node.expanded ) { if( walkVisible(node, 0, fn) === false ) { return false; } } // visit subsequent siblings for( i = idx + 1; i < siblingCount; i++ ) { if( walkVisible(parent, i, fn) === false ) { return false; } } // visit parent's subsequent siblings grandParent = parent.parent; if( grandParent ) { return walkVisible(grandParent, grandParent.children.indexOf(parent) + 1, fn); } else { // wrap-around: restart with first node return walkVisible(parent, 0, fn); } }; match = (typeof match === "string") ? _makeNodeTitleStartMatcher(match) : match; startNode = startNode || this.getFirstChild(); walkVisible(startNode.parent, parentChildren.indexOf(startNode), function(node){ // Stop iteration if we see the start node a second time if( node === stopNode ) { return false; } stopNode = stopNode || node; // Ignore nodes hidden by a filter if( ! $(node.span).is(":visible") ) { node.debug("quicksearch: skipping hidden node"); return; } // Test if we found a match, but search for a second match if this // was the currently active node if( match(node) ) { // node.debug("quicksearch match " + node.title, startNode); matchingNode = node; if( matchingNode !== startNode ) { return false; } } }); return matchingNode; }, // TODO: fromDict /** * Generate INPUT elements that can be submitted with html forms. * * In selectMode 3 only the topmost selected nodes are considered. * * @param {boolean | string} [selected=true] * @param {boolean | string} [active=true] */ generateFormElements: function(selected, active) { // TODO: test case var nodeList, selectedName = (selected !== false) ? "ft_" + this._id + "[]" : selected, activeName = (active !== false) ? "ft_" + this._id + "_active" : active, id = "fancytree_result_" + this._id, $result = $("#" + id); if($result.length){ $result.empty(); }else{ $result = $("<div>", { id: id }).hide().insertAfter(this.$container); } if(selectedName){ nodeList = this.getSelectedNodes( this.options.selectMode === 3 ); $.each(nodeList, function(idx, node){ $result.append($("<input>", { type: "checkbox", name: selectedName, value: node.key, checked: true })); }); } if(activeName && this.activeNode){ $result.append($("<input>", { type: "radio", name: activeName, value: this.activeNode.key, checked: true })); } }, /** * Return the currently active node or null. * @returns {FancytreeNode} */ getActiveNode: function() { return this.activeNode; }, /** Return the first top level node if any (not the invisible root node). * @returns {FancytreeNode | null} */ getFirstChild: function() { return this.rootNode.getFirstChild(); }, /** * Return node that has keyboard focus. * @param {boolean} [ifTreeHasFocus=false] (not yet implemented) * @returns {FancytreeNode} */ getFocusNode: function(ifTreeHasFocus) { // TODO: implement ifTreeHasFocus return this.focusNode; }, /** * Return node with a given key or null if not found. * @param {string} key * @param {FancytreeNode} [searchRoot] only search below this node * @returns {FancytreeNode | null} */ getNodeByKey: function(key, searchRoot) { // Search the DOM by element ID (assuming this is faster than traversing all nodes). // $("#...") has problems, if the key contains '.', so we use getElementById() var el, match; if(!searchRoot){ el = document.getElementById(this.options.idPrefix + key); if( el ){ return el.ftnode ? el.ftnode : null; } } // Not found in the DOM, but still may be in an unrendered part of tree // TODO: optimize with specialized loop // TODO: consider keyMap? searchRoot = searchRoot || this.rootNode; match = null; searchRoot.visit(function(node){ // window.console.log("getNodeByKey(" + key + "): ", node.key); if(node.key === key) { match = node; return false; } }, true); return match; }, /** Return the invisible system root node. * @returns {FancytreeNode} */ getRootNode: function() { return this.rootNode; }, /** * Return an array of selected nodes. * @param {boolean} [stopOnParents=false] only return the topmost selected * node (useful with selectMode 3) * @returns {FancytreeNode[]} */ getSelectedNodes: function(stopOnParents) { var nodeList = []; this.rootNode.visit(function(node){ if( node.selected ) { nodeList.push(node); if( stopOnParents === true ){ return "skip"; // stop processing this branch } } }); return nodeList; }, /** Return true if the tree control has keyboard focus * @returns {boolean} */ hasFocus: function(){ return !!this._hasFocus; }, /** Write to browser console if debugLevel >= 1 (prepending tree name) * @param {*} msg string or object or array of such */ info: function(msg){ if( this.options.debugLevel >= 1 ) { Array.prototype.unshift.call(arguments, this.toString()); consoleApply("info", arguments); } }, /* TODO: isInitializing: function() { return ( this.phase=="init" || this.phase=="postInit" ); }, TODO: isReloading: function() { return ( this.phase=="init" || this.phase=="postInit" ) && this.options.persist && this.persistence.cookiesFound; }, TODO: isUserEvent: function() { return ( this.phase=="userEvent" ); }, */ /** * Make sure that a node with a given ID is loaded, by traversing - and * loading - its parents. This method is ment for lazy hierarchies. * A callback is executed for every node as we go. * @example * tree.loadKeyPath("/_3/_23/_26/_27", function(node, status){ * if(status === "loaded") { * console.log("loaded intermiediate node " + node); * }else if(status === "ok") { * node.activate(); * } * }); * * @param {string | string[]} keyPathList one or more key paths (e.g. '/3/2_1/7') * @param {function} callback callback(node, status) is called for every visited node ('loading', 'loaded', 'ok', 'error') * @returns {$.Promise} */ loadKeyPath: function(keyPathList, callback, _rootNode) { var deferredList, dfd, i, path, key, loadMap, node, root, segList, sep = this.options.keyPathSeparator, self = this; if(!$.isArray(keyPathList)){ keyPathList = [keyPathList]; } // Pass 1: handle all path segments for nodes that are already loaded // Collect distinct top-most lazy nodes in a map loadMap = {}; for(i=0; i<keyPathList.length; i++){ root = _rootNode || this.rootNode; path = keyPathList[i]; // strip leading slash if(path.charAt(0) === sep){ path = path.substr(1); } // traverse and strip keys, until we hit a lazy, unloaded node segList = path.split(sep); while(segList.length){ key = segList.shift(); // node = _findDirectChild(root, key); node = root._findDirectChild(key); if(!node){ this.warn("loadKeyPath: key not found: " + key + " (parent: " + root + ")"); callback.call(this, key, "error"); break; }else if(segList.length === 0){ callback.call(this, node, "ok"); break; }else if(!node.lazy || (node.hasChildren() !== undefined )){ callback.call(this, node, "loaded"); root = node; }else{ callback.call(this, node, "loaded"); // segList.unshift(key); if(loadMap[key]){ loadMap[key].push(segList.join(sep)); }else{ loadMap[key] = [segList.join(sep)]; } break; } } } // alert("loadKeyPath: loadMap=" + JSON.stringify(loadMap)); // Now load all lazy nodes and continue itearation for remaining paths deferredList = []; // Avoid jshint warning 'Don't make functions within a loop.': function __lazyload(key, node, dfd){ callback.call(self, node, "loading"); node.load().done(function(){ self.loadKeyPath.call(self, loadMap[key], callback, node).always(_makeResolveFunc(dfd, self)); }).fail(function(errMsg){ self.warn("loadKeyPath: error loading: " + key + " (parent: " + root + ")"); callback.call(self, node, "error"); dfd.reject(); }); } for(key in loadMap){ node = root._findDirectChild(key); // alert("loadKeyPath: lazy node(" + key + ") = " + node); dfd = new $.Deferred(); deferredList.push(dfd); __lazyload(key, node, dfd); } // Return a promise that is resovled, when ALL paths were loaded return $.when.apply($, deferredList).promise(); }, /** Re-fire beforeActivate and activate events. */ reactivate: function(setFocus) { var res, node = this.activeNode; if( !node ) { return _getResolvedPromise(); } this.activeNode = null; // Force re-activating res = node.setActive(); if( setFocus ){ node.setFocus(); } return res; }, /** Reload tree from source and return a promise. * @param [source] optional new source (defaults to initial source data) * @returns {$.Promise} */ reload: function(source) { this._callHook("treeClear", this); return this._callHook("treeLoad", this, source); }, /**Render tree (i.e. create DOM elements for all top-level nodes). * @param {boolean} [force=false] create DOM elemnts, even is parent is collapsed * @param {boolean} [deep=false] */ render: function(force, deep) { return this.rootNode.render(force, deep); }, // TODO: selectKey: function(key, select) // TODO: serializeArray: function(stopOnParents) /** * @param {boolean} [flag=true] */ setFocus: function(flag) { return this._callHook("treeSetFocus", this, flag); }, /** * Return all nodes as nested list of {@link NodeData}. * * @param {boolean} [includeRoot=false] Returns the hidden system root node (and its children) * @param {function} [callback(node)] Called for every node * @returns {Array | object} * @see FancytreeNode#toDict */ toDict: function(includeRoot, callback){ var res = this.rootNode.toDict(true, callback); return includeRoot ? res : res.children; }, /* Implicitly called for string conversions. * @returns {string} */ toString: function(){ return "<Fancytree(#" + this._id + ")>"; }, /* _trigger a widget event with additional node ctx. * @see EventData */ _triggerNodeEvent: function(type, node, originalEvent, extra) { // this.debug("_trigger(" + type + "): '" + ctx.node.title + "'", ctx); var ctx = this._makeHookContext(node, originalEvent, extra), res = this.widget._trigger(type, originalEvent, ctx); if(res !== false && ctx.result !== undefined){ return ctx.result; } return res; }, /* _trigger a widget event with additional tree data. */ _triggerTreeEvent: function(type, originalEvent, extra) { // this.debug("_trigger(" + type + ")", ctx); var ctx = this._makeHookContext(this, originalEvent, extra), res = this.widget._trigger(type, originalEvent, ctx); if(res !== false && ctx.result !== undefined){ return ctx.result; } return res; }, /** Call fn(node) for all nodes. * * @param {function} fn the callback function. * Return false to stop iteration, return "skip" to skip this node and children only. * @returns {boolean} false, if the iterator was stopped. */ visit: function(fn) { return this.rootNode.visit(fn, false); }, /** Write warning to browser console (prepending tree info) * * @param {*} msg string or object or array of such */ warn: function(msg){ Array.prototype.unshift.call(arguments, this.toString()); consoleApply("warn", arguments); } }; /** * These additional methods of the {@link Fancytree} class are 'hook functions' * that can be used and overloaded by extensions. * (See <a href="https://github.com/mar10/fancytree/wiki/TutorialExtensions">writing extensions</a>.) * @mixin Fancytree_Hooks */ $.extend(Fancytree.prototype, /** @lends Fancytree_Hooks# */ { /** Default handling for mouse click events. * * @param {EventData} ctx */ nodeClick: function(ctx) { // this.tree.logDebug("ftnode.onClick(" + event.type + "): ftnode:" + this + ", button:" + event.button + ", which: " + event.which); var activate, expand, // event = ctx.originalEvent, targetType = ctx.targetType, node = ctx.node; // TODO: use switch // TODO: make sure clicks on embedded <input> doesn't steal focus (see table sample) if( targetType === "expander" ) { // Clicking the expander icon always expands/collapses this._callHook("nodeToggleExpanded", ctx); } else if( targetType === "checkbox" ) { // Clicking the checkbox always (de)selects this._callHook("nodeToggleSelected", ctx); if( ctx.options.focusOnSelect ) { // #358 this._callHook("nodeSetFocus", ctx, true); } } else { // Honor `clickFolderMode` for expand = false; activate = true; if( node.folder ) { switch( ctx.options.clickFolderMode ) { case 2: // expand only expand = true; activate = false; break; case 3: // expand and activate activate = true; expand = true; //!node.isExpanded(); break; // else 1 or 4: just activate } } if( activate ) { this.nodeSetFocus(ctx); this._callHook("nodeSetActive", ctx, true); } if( expand ) { if(!activate){ // this._callHook("nodeSetFocus", ctx); } // this._callHook("nodeSetExpanded", ctx, true); this._callHook("nodeToggleExpanded", ctx); } } // Make sure that clicks stop, otherwise <a href='#'> jumps to the top // if(event.target.localName === "a" && event.target.className === "fancytree-title"){ // event.preventDefault(); // } // TODO: return promise? }, /** Collapse all other children of same parent. * * @param {EventData} ctx * @param {object} callOpts */ nodeCollapseSiblings: function(ctx, callOpts) { // TODO: return promise? var ac, i, l, node = ctx.node; if( node.parent ){ ac = node.parent.children; for (i=0, l=ac.length; i<l; i++) { if ( ac[i] !== node && ac[i].expanded ){ this._callHook("nodeSetExpanded", ac[i], false, callOpts); } } } }, /** Default handling for mouse douleclick events. * @param {EventData} ctx */ nodeDblclick: function(ctx) { // TODO: return promise? if( ctx.targetType === "title" && ctx.options.clickFolderMode === 4) { // this.nodeSetFocus(ctx); // this._callHook("nodeSetActive", ctx, true); this._callHook("nodeToggleExpanded", ctx); } // TODO: prevent text selection on dblclicks if( ctx.targetType === "title" ) { ctx.originalEvent.preventDefault(); } }, /** Default handling for mouse keydown events. * * NOTE: this may be called with node == null if tree (but no node) has focus. * @param {EventData} ctx */ nodeKeydown: function(ctx) { // TODO: return promise? var matchNode, stamp, res, event = ctx.originalEvent, node = ctx.node, tree = ctx.tree, opts = ctx.options, which = event.which, whichChar = String.fromCharCode(which), clean = !(event.altKey || event.ctrlKey || event.metaKey || event.shiftKey), $target = $(event.target), handled = true, activate = !(event.ctrlKey || !opts.autoActivate ); // node.debug("ftnode.nodeKeydown(" + event.type + "): ftnode:" + this + ", charCode:" + event.charCode + ", keyCode: " + event.keyCode + ", which: " + event.which); // FT.debug("keyEventToString", which, '"' + String.fromCharCode(which) + '"', '"' + FT.keyEventToString(event) + '"'); // Set focus to first node, if no other node has the focus yet if( !node ){ this.getFirstChild().setFocus(); node = ctx.node = this.focusNode; node.debug("Keydown force focus on first node"); } if( opts.quicksearch && clean && /\w/.test(whichChar) && !$target.is(":input:enabled") ) { // Allow to search for longer streaks if typed in quickly stamp = new Date().getTime(); if( stamp - tree.lastQuicksearchTime > 500 ) { tree.lastQuicksearchTerm = ""; } tree.lastQuicksearchTime = stamp; tree.lastQuicksearchTerm += whichChar; // tree.debug("quicksearch find", tree.lastQuicksearchTerm); matchNode = tree.findNextNode(tree.lastQuicksearchTerm, tree.getActiveNode()); if( matchNode ) { matchNode.setActive(); } event.preventDefault(); return; } switch( FT.keyEventToString(event) ) { case "+": case "=": // 187: '+' @ Chrome, Safari tree.nodeSetExpanded(ctx, true); break; case "-": tree.nodeSetExpanded(ctx, false); break; case "space": if(opts.checkbox){ tree.nodeToggleSelected(ctx); }else{ tree.nodeSetActive(ctx, true); } break; case "enter": tree.nodeSetActive(ctx, true); break; case "backspace": case "left": case "right": case "up": case "down": res = node.navigate(event.which, activate); break; default: handled = false; } if(handled){ event.preventDefault(); } }, // /** Default handling for mouse keypress events. */ // nodeKeypress: function(ctx) { // var event = ctx.originalEvent; // }, // /** Trigger lazyLoad event (async). */ // nodeLazyLoad: function(ctx) { // var node = ctx.node; // if(this._triggerNodeEvent()) // }, /** Load child nodes (async). * * @param {EventData} ctx * @param {object[]|object|string|$.Promise|function} source * @returns {$.Promise} The deferred will be resolved as soon as the (ajax) * data was rendered. */ nodeLoadChildren: function(ctx, source) { var ajax, delay, dfd, tree = ctx.tree, node = ctx.node; if($.isFunction(source)){ source = source(); } // TOTHINK: move to 'ajax' extension? if(source.url){ // `source` is an Ajax options object ajax = $.extend({}, ctx.options.ajax, source); if(ajax.debugDelay){ // simulate a slow server delay = ajax.debugDelay; if($.isArray(delay)){ // random delay range [min..max] delay = delay[0] + Math.random() * (delay[1] - delay[0]); } node.debug("nodeLoadChildren waiting debug delay " + Math.round(delay) + "ms"); ajax.debugDelay = false; dfd = $.Deferred(function (dfd) { setTimeout(function () { $.ajax(ajax) .done(function () { dfd.resolveWith(this, arguments); }) .fail(function () { dfd.rejectWith(this, arguments); }); }, delay); }); }else{ dfd = $.ajax(ajax); } // Defer the deferred: we want to be able to reject, even if ajax // resolved ok. source = new $.Deferred(); dfd.done(function (data, textStatus, jqXHR) { var errorObj, res; if(typeof data === "string"){ $.error("Ajax request returned a string (did you get the JSON dataType wrong?)."); } // postProcess is similar to the standard ajax dataFilter hook, // but it is also called for JSONP if( ctx.options.postProcess ){ res = tree._triggerNodeEvent("postProcess", ctx, ctx.originalEvent, {response: data, error: null, dataType: this.dataType}); if( res.error ) { errorObj = $.isPlainObject(res.error) ? res.error : {message: res.error}; errorObj = tree._makeHookContext(node, null, errorObj); source.rejectWith(this, [errorObj]); return; } data = $.isArray(res) ? res : data; } else if (data && data.hasOwnProperty("d") && ctx.options.enableAspx ) { // Process ASPX WebMethod JSON object inside "d" property data = (typeof data.d === "string") ? $.parseJSON(data.d) : data.d; } source.resolveWith(this, [data]); }).fail(function (jqXHR, textStatus, errorThrown) { var errorObj = tree._makeHookContext(node, null, { error: jqXHR, args: Array.prototype.slice.call(arguments), message: errorThrown, details: jqXHR.status + ": " + errorThrown }); source.rejectWith(this, [errorObj]); }); } if($.isFunction(source.promise)){ // `source` is a deferred, i.e. ajax request _assert(!node.isLoading()); // node._isLoading = true; tree.nodeSetStatus(ctx, "loading"); source.done(function (children) { tree.nodeSetStatus(ctx, "ok"); }).fail(function(error){ var ctxErr; if (error.node && error.error && error.message) { // error is already a context object ctxErr = error; } else { ctxErr = tree._makeHookContext(node, null, { error: error, // it can be jqXHR or any custom error args: Array.prototype.slice.call(arguments), message: error ? (error.message || error.toString()) : "" }); } if( tree._triggerNodeEvent("loadError", ctxErr, null) !== false ) { tree.nodeSetStatus(ctx, "error", ctxErr.message, ctxErr.details); } }); } // $.when(source) resolves also for non-deferreds return $.when(source).done(function(children){ var metaData; if( $.isPlainObject(children) ){ // We got {foo: 'abc', children: [...]} // Copy extra properties to tree.data.foo _assert($.isArray(children.children), "source must contain (or be) an array of children"); _assert(node.isRoot(), "source may only be an object for root nodes"); metaData = children; children = children.children; delete metaData.children; $.extend(tree.data, metaData); } _assert($.isArray(children), "expected array of children"); node._setChildren(children); // trigger fancytreeloadchildren tree._triggerNodeEvent("loadChildren", node); // }).always(function(){ // node._isLoading = false; }); }, /** [Not Implemented] */ nodeLoadKeyPath: function(ctx, keyPathList) { // TODO: implement and improve // http://code.google.com/p/dynatree/issues/detail?id=222 }, /** * Remove a single direct child of ctx.node. * @param {EventData} ctx * @param {FancytreeNode} childNode dircect child of ctx.node */ nodeRemoveChild: function(ctx, childNode) { var idx, node = ctx.node, opts = ctx.options, subCtx = $.extend({}, ctx, {node: childNode}), children = node.children; // FT.debug("nodeRemoveChild()", node.toString(), childNode.toString()); if( children.length === 1 ) { _assert(childNode === children[0]); return this.nodeRemoveChildren(ctx); } if( this.activeNode && (childNode === this.activeNode || this.activeNode.isDescendantOf(childNode))){ this.activeNode.setActive(false); // TODO: don't fire events } if( this.focusNode && (childNode === this.focusNode || this.focusNode.isDescendantOf(childNode))){ this.focusNode = null; } // TODO: persist must take care to clear select and expand cookies this.nodeRemoveMarkup(subCtx); this.nodeRemoveChildren(subCtx); idx = $.inArray(childNode, children); _assert(idx >= 0); // Unlink to support GC childNode.visit(function(n){ n.parent = null; }, true); this._callHook("treeRegisterNode", this, false, childNode); if ( opts.removeNode ){ opts.removeNode.call(ctx.tree, {type: "removeNode"}, subCtx); } // remove from child list children.splice(idx, 1); }, /**Remove HTML markup for all descendents of ctx.node. * @param {EventData} ctx */ nodeRemoveChildMarkup: function(ctx) { var node = ctx.node; // FT.debug("nodeRemoveChildMarkup()", node.toString()); // TODO: Unlink attr.ftnode to support GC if(node.ul){ if( node.isRoot() ) { $(node.ul).empty(); } else { $(node.ul).remove(); node.ul = null; } node.visit(function(n){ n.li = n.ul = null; }); } }, /**Remove all descendants of ctx.node. * @param {EventData} ctx */ nodeRemoveChildren: function(ctx) { var subCtx, tree = ctx.tree, node = ctx.node, children = node.children, opts = ctx.options; // FT.debug("nodeRemoveChildren()", node.toString()); if(!children){ return; } if( this.activeNode && this.activeNode.isDescendantOf(node)){ this.activeNode.setActive(false); // TODO: don't fire events } if( this.focusNode && this.focusNode.isDescendantOf(node)){ this.focusNode = null; } // TODO: persist must take care to clear select and expand cookies this.nodeRemoveChildMarkup(ctx); // Unlink children to support GC // TODO: also delete this.children (not possible using visit()) subCtx = $.extend({}, ctx); node.visit(function(n){ n.parent = null; tree._callHook("treeRegisterNode", tree, false, n); if ( opts.removeNode ){ subCtx.node = n; opts.removeNode.call(ctx.tree, {type: "removeNode"}, subCtx); } }); if( node.lazy ){ // 'undefined' would be interpreted as 'not yet loaded' for lazy nodes node.children = []; } else{ node.children = null; } this.nodeRenderStatus(ctx); }, /**Remove HTML markup for ctx.node and all its descendents. * @param {EventData} ctx */ nodeRemoveMarkup: function(ctx) { var node = ctx.node; // FT.debug("nodeRemoveMarkup()", node.toString()); // TODO: Unlink attr.ftnode to support GC if(node.li){ $(node.li).remove(); node.li = null; } this.nodeRemoveChildMarkup(ctx); }, /** * Create `&lt;li>&lt;span>..&lt;/span> .. &lt;/li>` tags for this node. * * This method takes care that all HTML markup is created that is required * to display this node in it's current state. * * Call this method to create new nodes, or after the strucuture * was changed (e.g. after moving this node or adding/removing children) * nodeRenderTitle() and nodeRenderStatus() are implied. * * Note: if a node was created/removed, nodeRender() must be called for the * parent. * <code> * <li id='KEY' ftnode=NODE> * <span class='fancytree-node fancytree-expanded fancytree-has-children fancytree-lastsib fancytree-exp-el fancytree-ico-e'> * <span class="fancytree-expander"></span> * <span class="fancytree-checkbox"></span> // only present in checkbox mode * <span class="fancytree-icon"></span> * <a href="#" class="fancytree-title"> Node 1 </a> * </span> * <ul> // only present if node has children * <li id='KEY' ftnode=NODE> child1 ... </li> * <li id='KEY' ftnode=NODE> child2 ... </li> * </ul> * </li> * </code> * * @param {EventData} ctx * @param {boolean} [force=false] re-render, even if html markup was already created * @param {boolean} [deep=false] also render all descendants, even if parent is collapsed * @param {boolean} [collapsed=false] force root node to be collapsed, so we can apply animated expand later */ nodeRender: function(ctx, force, deep, collapsed, _recursive) { /* This method must take care of all cases where the current data mode * (i.e. node hierarchy) does not match the current markup. * * - node was not yet rendered: * create markup * - node was rendered: exit fast * - children have been added * - childern have been removed */ var childLI, childNode1, childNode2, i, l, next, subCtx, node = ctx.node, tree = ctx.tree, opts = ctx.options, aria = opts.aria, firstTime = false, parent = node.parent, isRootNode = !parent, children = node.children; // FT.debug("nodeRender(" + !!force + ", " + !!deep + ")", node.toString()); if( ! isRootNode && ! parent.ul ) { // Calling node.collapse on a deep, unrendered node return; } _assert(isRootNode || parent.ul, "parent UL must exist"); // Render the node if( !isRootNode ){ // Discard markup on force-mode, or if it is not linked to parent <ul> if(node.li && (force || (node.li.parentNode !== node.parent.ul) ) ){ if(node.li.parentNode !== node.parent.ul){ // May happen, when a top-level node was dropped over another this.debug("Unlinking " + node + " (must be child of " + node.parent + ")"); } // this.debug("nodeRemoveMarkup..."); this.nodeRemoveMarkup(ctx); } // Create <li><span /> </li> // node.debug("render..."); if( !node.li ) { // node.debug("render... really"); firstTime = true; node.li = document.createElement("li"); node.li.ftnode = node; if(aria){ // TODO: why doesn't this work: // node.li.role = "treeitem"; // $(node.li).attr("role", "treeitem") // .attr("aria-labelledby", "ftal_" + node.key); } if( node.key && opts.generateIds ){ node.li.id = opts.idPrefix + node.key; } node.span = document.createElement("span"); node.span.className = "fancytree-node"; if(aria){ $(node.span).attr("aria-labelledby", "ftal_" + node.key); } node.li.appendChild(node.span); // Create inner HTML for the <span> (expander, checkbox, icon, and title) this.nodeRenderTitle(ctx); // Allow tweaking and binding, after node was created for the first time if ( opts.createNode ){ opts.createNode.call(tree, {type: "createNode"}, ctx); } }else{ // this.nodeRenderTitle(ctx); this.nodeRenderStatus(ctx); } // Allow tweaking after node state was rendered if ( opts.renderNode ){ opts.renderNode.call(tree, {type: "renderNode"}, ctx); } } // Visit child nodes if( children ){ if( isRootNode || node.expanded || deep === true ) { // Create a UL to hold the children if( !node.ul ){ node.ul = document.createElement("ul"); if((collapsed === true && !_recursive) || !node.expanded){ // hide top UL, so we can use an animation to show it later node.ul.style.display = "none"; } if(aria){ $(node.ul).attr("role", "group"); } if ( node.li ) { // issue #67 node.li.appendChild(node.ul); } else { node.tree.$div.append(node.ul); } } // Add child markup for(i=0, l=children.length; i<l; i++) { subCtx = $.extend({}, ctx, {node: children[i]}); this.nodeRender(subCtx, force, deep, false, true); } // Remove <li> if nodes have moved to another parent childLI = node.ul.firstChild; while( childLI ){ childNode2 = childLI.ftnode; if( childNode2 && childNode2.parent !== node ) { node.debug("_fixParent: remove missing " + childNode2, childLI); next = childLI.nextSibling; childLI.parentNode.removeChild(childLI); childLI = next; }else{ childLI = childLI.nextSibling; } } // Make sure, that <li> order matches node.children order. childLI = node.ul.firstChild; for(i=0, l=children.length-1; i<l; i++) { childNode1 = children[i]; childNode2 = childLI.ftnode; if( childNode1 !== childNode2 ) { // node.debug("_fixOrder: mismatch at index " + i + ": " + childNode1 + " != " + childNode2); node.ul.insertBefore(childNode1.li, childNode2.li); } else { childLI = childLI.nextSibling; } } } }else{ // No children: remove markup if any if( node.ul ){ // alert("remove child markup for " + node); this.warn("remove child markup for " + node); this.nodeRemoveChildMarkup(ctx); } } if( !isRootNode ){ // Update element classes according to node state // this.nodeRenderStatus(ctx); // Finally add the whole structure to the DOM, so the browser can render if(firstTime){ parent.ul.appendChild(node.li); } } }, /** Create HTML for the node's outer <span> (expander, checkbox, icon, and title). * * nodeRenderStatus() is implied. * @param {EventData} ctx * @param {string} [title] optinal new title */ nodeRenderTitle: function(ctx, title) { // set node connector images, links and text var id, iconSpanClass, nodeTitle, role, tabindex, tooltip, node = ctx.node, tree = ctx.tree, opts = ctx.options, aria = opts.aria, level = node.getLevel(), ares = [], iconSrc = node.data.icon; if(title !== undefined){ node.title = title; } if(!node.span){ // Silently bail out if node was not rendered yet, assuming // node.render() will be called as the node becomes visible return; } // connector (expanded, expandable or simple) // TODO: optimize this if clause if( level < opts.minExpandLevel ) { if( !node.lazy ) { node.expanded = true; } if(level > 1){ if(aria){ ares.push("<span role='button' class='fancytree-expander fancytree-expander-fixed'></span>"); }else{ ares.push("<span class='fancytree-expander fancytree-expander-fixed''></span>"); } } // .. else (i.e. for root level) skip expander/connector alltogether } else { if(aria){ ares.push("<span role='button' class='fancytree-expander'></span>"); }else{ ares.push("<span class='fancytree-expander'></span>"); } } // Checkbox mode if( opts.checkbox && node.hideCheckbox !== true && !node.isStatusNode() ) { if(aria){ ares.push("<span role='checkbox' class='fancytree-checkbox'></span>"); }else{ ares.push("<span class='fancytree-checkbox'></span>"); } } // folder or doctype icon role = aria ? " role='img'" : ""; if( iconSrc === true || (iconSrc !== false && opts.icons !== false) ) { // opts.icons defines the default behavior, node.icon == true/false can override this if ( iconSrc && typeof iconSrc === "string" ) { // node.icon is an image url iconSrc = (iconSrc.charAt(0) === "/") ? iconSrc : ((opts.imagePath || "") + iconSrc); ares.push("<img src='" + iconSrc + "' class='fancytree-icon' alt='' />"); } else { // See if node.iconClass or opts.iconClass() define a class name iconSpanClass = (opts.iconClass && opts.iconClass.call(tree, node, ctx)) || node.data.iconclass || null; if( iconSpanClass ) { ares.push("<span " + role + " class='fancytree-custom-icon " + iconSpanClass + "'></span>"); } else { ares.push("<span " + role + " class='fancytree-icon'></span>"); } } } // node title nodeTitle = ""; if ( opts.renderTitle ){ nodeTitle = opts.renderTitle.call(tree, {type: "renderTitle"}, ctx) || ""; } if(!nodeTitle){ tooltip = node.tooltip ? " title='" + FT.escapeHtml(node.tooltip) + "'" : ""; id = aria ? " id='ftal_" + node.key + "'" : ""; role = aria ? " role='treeitem'" : ""; tabindex = opts.titlesTabbable ? " tabindex='0'" : ""; nodeTitle = "<span " + role + " class='fancytree-title'" + id + tooltip + tabindex + ">" + node.title + "</span>"; } ares.push(nodeTitle); // Note: this will trigger focusout, if node had the focus //$(node.span).html(ares.join("")); // it will cleanup the jQuery data currently associated with SPAN (if any), but it executes more slowly node.span.innerHTML = ares.join(""); // Update CSS classes this.nodeRenderStatus(ctx); }, /** Update element classes according to node state. * @param {EventData} ctx */ nodeRenderStatus: function(ctx) { // Set classes for current status var node = ctx.node, tree = ctx.tree, opts = ctx.options, // nodeContainer = node[tree.nodeContainerAttrName], hasChildren = node.hasChildren(), isLastSib = node.isLastSibling(), aria = opts.aria, // $ariaElem = aria ? $(node[tree.ariaPropName]) : null, $ariaElem = $(node.span).find(".fancytree-title"), cn = opts._classNames, cnList = [], statusElem = node[tree.statusClassPropName]; if( !statusElem ){ // if this function is called for an unrendered node, ignore it (will be updated on nect render anyway) return; } // Build a list of class names that we will add to the node <span> cnList.push(cn.node); if( tree.activeNode === node ){ cnList.push(cn.active); // $(">span.fancytree-title", statusElem).attr("tabindex", "0"); // tree.$container.removeAttr("tabindex"); // }else{ // $(">span.fancytree-title", statusElem).removeAttr("tabindex"); // tree.$container.attr("tabindex", "0"); } if( tree.focusNode === node ){ cnList.push(cn.focused); if(aria){ // $(">span.fancytree-title", statusElem).attr("tabindex", "0"); // $(">span.fancytree-title", statusElem).attr("tabindex", "-1"); // TODO: is this the right element for this attribute? $ariaElem .attr("aria-activedescendant", true); // .attr("tabindex", "-1"); } }else if(aria){ // $(">span.fancytree-title", statusElem).attr("tabindex", "-1"); $ariaElem .removeAttr("aria-activedescendant"); // .removeAttr("tabindex"); } if( node.expanded ){ cnList.push(cn.expanded); if(aria){ $ariaElem.attr("aria-expanded", true); } }else if(aria){ $ariaElem.removeAttr("aria-expanded"); } if( node.folder ){ cnList.push(cn.folder); } if( hasChildren !== false ){ cnList.push(cn.hasChildren); } // TODO: required? if( isLastSib ){ cnList.push(cn.lastsib); } if( node.lazy && node.children == null ){ cnList.push(cn.lazy); } if( node.partsel ){ cnList.push(cn.partsel); } if( node.unselectable ){ cnList.push(cn.unselectable); } if( node._isLoading ){ cnList.push(cn.loading); } if( node._error ){ cnList.push(cn.error); } if( node.selected ){ cnList.push(cn.selected); if(aria){ $ariaElem.attr("aria-selected", true); } }else if(aria){ $ariaElem.attr("aria-selected", false); } if( node.extraClasses ){ cnList.push(node.extraClasses); } // IE6 doesn't correctly evaluate multiple class names, // so we create combined class names that can be used in the CSS if( hasChildren === false ){ cnList.push(cn.combinedExpanderPrefix + "n" + (isLastSib ? "l" : "") ); }else{ cnList.push(cn.combinedExpanderPrefix + (node.expanded ? "e" : "c") + (node.lazy && node.children == null ? "d" : "") + (isLastSib ? "l" : "") ); } cnList.push(cn.combinedIconPrefix + (node.expanded ? "e" : "c") + (node.folder ? "f" : "") ); // node.span.className = cnList.join(" "); statusElem.className = cnList.join(" "); // TODO: we should not set this in the <span> tag also, if we set it here: // Maybe most (all) of the classes should be set in LI instead of SPAN? if(node.li){ node.li.className = isLastSib ? cn.lastsib : ""; } }, /** Activate node. * flag defaults to true. * If flag is true, the node is activated (must be a synchronous operation) * If flag is false, the node is deactivated (must be a synchronous operation) * @param {EventData} ctx * @param {boolean} [flag=true] * @param {object} [opts] additional options. Defaults to {noEvents: false} * @returns {$.Promise} */ nodeSetActive: function(ctx, flag, callOpts) { // Handle user click / [space] / [enter], according to clickFolderMode. callOpts = callOpts || {}; var subCtx, node = ctx.node, tree = ctx.tree, opts = ctx.options, noEvents = (callOpts.noEvents === true), isActive = (node === tree.activeNode); // flag defaults to true flag = (flag !== false); // node.debug("nodeSetActive", flag); if(isActive === flag){ // Nothing to do return _getResolvedPromise(node); }else if(flag && !noEvents && this._triggerNodeEvent("beforeActivate", node, ctx.originalEvent) === false ){ // Callback returned false return _getRejectedPromise(node, ["rejected"]); } if(flag){ if(tree.activeNode){ _assert(tree.activeNode !== node, "node was active (inconsistency)"); subCtx = $.extend({}, ctx, {node: tree.activeNode}); tree.nodeSetActive(subCtx, false); _assert(tree.activeNode === null, "deactivate was out of sync?"); } if(opts.activeVisible){ // tree.nodeMakeVisible(ctx); node.makeVisible({scrollIntoView: false}); // nodeSetFocus will scroll } tree.activeNode = node; tree.nodeRenderStatus(ctx); tree.nodeSetFocus(ctx); if( !noEvents ) { tree._triggerNodeEvent("activate", node, ctx.originalEvent); } }else{ _assert(tree.activeNode === node, "node was not active (inconsistency)"); tree.activeNode = null; this.nodeRenderStatus(ctx); if( !noEvents ) { ctx.tree._triggerNodeEvent("deactivate", node, ctx.originalEvent); } } }, /** Expand or collapse node, return Deferred.promise. * * @param {EventData} ctx * @param {boolean} [flag=true] * @param {object} [opts] additional options. Defaults to {noAnimation: false, noEvents: false} * @returns {$.Promise} The deferred will be resolved as soon as the (lazy) * data was retrieved, rendered, and the expand animation finshed. */ nodeSetExpanded: function(ctx, flag, callOpts) { callOpts = callOpts || {}; var _afterLoad, dfd, i, l, parents, prevAC, node = ctx.node, tree = ctx.tree, opts = ctx.options, noAnimation = (callOpts.noAnimation === true), noEvents = (callOpts.noEvents === true); // flag defaults to true flag = (flag !== false); // node.debug("nodeSetExpanded(" + flag + ")"); if((node.expanded && flag) || (!node.expanded && !flag)){ // Nothing to do // node.debug("nodeSetExpanded(" + flag + "): nothing to do"); return _getResolvedPromise(node); }else if(flag && !node.lazy && !node.hasChildren() ){ // Prevent expanding of empty nodes // return _getRejectedPromise(node, ["empty"]); return _getResolvedPromise(node); }else if( !flag && node.getLevel() < opts.minExpandLevel ) { // Prevent collapsing locked levels return _getRejectedPromise(node, ["locked"]); }else if ( !noEvents && this._triggerNodeEvent("beforeExpand", node, ctx.originalEvent) === false ){ // Callback returned false return _getRejectedPromise(node, ["rejected"]); } // If this node inside a collpased node, no animation and scrolling is needed if( !noAnimation && !node.isVisible() ) { noAnimation = callOpts.noAnimation = true; } dfd = new $.Deferred(); // Auto-collapse mode: collapse all siblings if( flag && !node.expanded && opts.autoCollapse ) { parents = node.getParentList(false, true); prevAC = opts.autoCollapse; try{ opts.autoCollapse = false; for(i=0, l=parents.length; i<l; i++){ // TODO: should return promise? this._callHook("nodeCollapseSiblings", parents[i], callOpts); } }finally{ opts.autoCollapse = prevAC; } } // Trigger expand/collapse after expanding dfd.done(function(){ if( flag && opts.autoScroll && !noAnimation ) { // Scroll down to last child, but keep current node visible node.getLastChild().scrollIntoView(true, {topNode: node}).always(function(){ if( !noEvents ) { ctx.tree._triggerNodeEvent(flag ? "expand" : "collapse", ctx); } }); } else { if( !noEvents ) { ctx.tree._triggerNodeEvent(flag ? "expand" : "collapse", ctx); } } }); // vvv Code below is executed after loading finished: _afterLoad = function(callback){ var isVisible, isExpanded, effect = opts.toggleEffect; node.expanded = flag; // Create required markup, but make sure the top UL is hidden, so we // can animate later tree._callHook("nodeRender", ctx, false, false, true); // If the currently active node is now hidden, deactivate it // if( opts.activeVisible && this.activeNode && ! this.activeNode.isVisible() ) { // this.activeNode.deactivate(); // } // Expanding a lazy node: set 'loading...' and call callback // if( bExpand && this.data.isLazy && this.childList === null && !this._isLoading ) { // this._loadContent(); // return; // } // Hide children, if node is collapsed if( node.ul ) { isVisible = (node.ul.style.display !== "none"); isExpanded = !!node.expanded; if ( isVisible === isExpanded ) { node.warn("nodeSetExpanded: UL.style.display already set"); } else if ( !effect || noAnimation ) { node.ul.style.display = ( node.expanded || !parent ) ? "" : "none"; } else { // The UI toggle() effect works with the ext-wide extension, // while jQuery.animate() has problems when the title span // has positon: absolute // duration = opts.fx.duration || 200; // easing = opts.fx.easing; // $(node.ul).animate(opts.fx, duration, easing, function(){ // node.debug("nodeSetExpanded: animate start..."); $(node.ul).toggle(effect.effect, effect.options, effect.duration, function(){ // node.debug("nodeSetExpanded: animate done"); callback(); }); return; } } callback(); }; // ^^^ Code above is executed after loading finshed. // Load lazy nodes, if any. Then continue with _afterLoad() if(flag && node.lazy && node.hasChildren() === undefined){ // node.debug("nodeSetExpanded: load start..."); node.load().done(function(){ // node.debug("nodeSetExpanded: load done"); if(dfd.notifyWith){ // requires jQuery 1.6+ dfd.notifyWith(node, ["loaded"]); } _afterLoad(function () { dfd.resolveWith(node); }); }).fail(function(errMsg){ _afterLoad(function () { dfd.rejectWith(node, ["load failed (" + errMsg + ")"]); }); }); /* var source = tree._triggerNodeEvent("lazyLoad", node, ctx.originalEvent); _assert(typeof source !== "boolean", "lazyLoad event must return source in data.result"); node.debug("nodeSetExpanded: load start..."); this._callHook("nodeLoadChildren", ctx, source).done(function(){ node.debug("nodeSetExpanded: load done"); if(dfd.notifyWith){ // requires jQuery 1.6+ dfd.notifyWith(node, ["loaded"]); } _afterLoad.call(tree); }).fail(function(errMsg){ dfd.rejectWith(node, ["load failed (" + errMsg + ")"]); }); */ }else{ _afterLoad(function () { dfd.resolveWith(node); }); } // node.debug("nodeSetExpanded: returns"); return dfd.promise(); }, /** Focus ot blur this node. * @param {EventData} ctx * @param {boolean} [flag=true] */ nodeSetFocus: function(ctx, flag) { // ctx.node.debug("nodeSetFocus(" + flag + ")"); var ctx2, tree = ctx.tree, node = ctx.node; flag = (flag !== false); // Blur previous node if any if(tree.focusNode){ if(tree.focusNode === node && flag){ // node.debug("nodeSetFocus(" + flag + "): nothing to do"); return; } ctx2 = $.extend({}, ctx, {node: tree.focusNode}); tree.focusNode = null; this._triggerNodeEvent("blur", ctx2); this._callHook("nodeRenderStatus", ctx2); } // Set focus to container and node if(flag){ if( !this.hasFocus() ){ node.debug("nodeSetFocus: forcing container focus"); // Note: we pass _calledByNodeSetFocus=true this._callHook("treeSetFocus", ctx, true, true); } // this.nodeMakeVisible(ctx); node.makeVisible({scrollIntoView: false}); tree.focusNode = node; // node.debug("FOCUS..."); // $(node.span).find(".fancytree-title").focus(); this._triggerNodeEvent("focus", ctx); // if(ctx.options.autoActivate){ // tree.nodeSetActive(ctx, true); // } if(ctx.options.autoScroll){ node.scrollIntoView(); } this._callHook("nodeRenderStatus", ctx); } }, /** (De)Select node, return new status (sync). * * @param {EventData} ctx * @param {boolean} [flag=true] */ nodeSetSelected: function(ctx, flag) { var node = ctx.node, tree = ctx.tree, opts = ctx.options; // flag defaults to true flag = (flag !== false); node.debug("nodeSetSelected(" + flag + ")", ctx); if( node.unselectable){ return; } // TODO: !!node.expanded is nicer, but doesn't pass jshint // https://github.com/jshint/jshint/issues/455 // if( !!node.expanded === !!flag){ if((node.selected && flag) || (!node.selected && !flag)){ return !!node.selected; }else if ( this._triggerNodeEvent("beforeSelect", node, ctx.originalEvent) === false ){ return !!node.selected; } if(flag && opts.selectMode === 1){ // single selection mode if(tree.lastSelectedNode){ tree.lastSelectedNode.setSelected(false); } }else if(opts.selectMode === 3){ // multi.hier selection mode node.selected = flag; // this._fixSelectionState(node); node.fixSelection3AfterClick(); } node.selected = flag; this.nodeRenderStatus(ctx); tree.lastSelectedNode = flag ? node : null; tree._triggerNodeEvent("select", ctx); }, /** Show node status (ok, loading, error) using styles and a dummy child node. * * @param {EventData} ctx * @param status * @param message * @param details */ nodeSetStatus: function(ctx, status, message, details) { var node = ctx.node, tree = ctx.tree; // cn = ctx.options._classNames; function _clearStatusNode() { // Remove dedicated dummy node, if any var firstChild = ( node.children ? node.children[0] : null ); if ( firstChild && firstChild.isStatusNode() ) { try{ // I've seen exceptions here with loadKeyPath... if(node.ul){ node.ul.removeChild(firstChild.li); firstChild.li = null; // avoid leaks (DT issue 215) } }catch(e){} if( node.children.length === 1 ){ node.children = []; }else{ node.children.shift(); } } } function _setStatusNode(data, type) { // Create/modify the dedicated dummy node for 'loading...' or // 'error!' status. (only called for direct child of the invisible // system root) var firstChild = ( node.children ? node.children[0] : null ); if ( firstChild && firstChild.isStatusNode() ) { $.extend(firstChild, data); // tree._callHook("nodeRender", firstChild); tree._callHook("nodeRenderTitle", firstChild); } else { data.key = "_statusNode"; node._setChildren([data]); node.children[0].statusNodeType = type; tree.render(); } return node.children[0]; } switch( status ){ case "ok": _clearStatusNode(); // $(node.span).removeClass(cn.loading).removeClass(cn.error); node._isLoading = false; node._error = null; node.renderStatus(); break; case "loading": // $(node.span).removeClass(cn.error).addClass(cn.loading); if( !node.parent ) { _setStatusNode({ title: tree.options.strings.loading + (message ? " (" + message + ") " : ""), tooltip: details, extraClasses: "fancytree-statusnode-wait" }, status); } node._isLoading = true; node._error = null; node.renderStatus(); break; case "error": // $(node.span).removeClass(cn.loading).addClass(cn.error); _setStatusNode({ title: tree.options.strings.loadError + (message ? " (" + message + ") " : ""), tooltip: details, extraClasses: "fancytree-statusnode-error" }, status); node._isLoading = false; node._error = { message: message, details: details }; node.renderStatus(); break; default: $.error("invalid node status " + status); } }, /** * * @param {EventData} ctx */ nodeToggleExpanded: function(ctx) { return this.nodeSetExpanded(ctx, !ctx.node.expanded); }, /** * @param {EventData} ctx */ nodeToggleSelected: function(ctx) { return this.nodeSetSelected(ctx, !ctx.node.selected); }, /** Remove all nodes. * @param {EventData} ctx */ treeClear: function(ctx) { var tree = ctx.tree; tree.activeNode = null; tree.focusNode = null; tree.$div.find(">ul.fancytree-container").empty(); // TODO: call destructors and remove reference loops tree.rootNode.children = null; }, /** Widget was created (called only once, even it re-initialized). * @param {EventData} ctx */ treeCreate: function(ctx) { }, /** Widget was destroyed. * @param {EventData} ctx */ treeDestroy: function(ctx) { }, /** Widget was (re-)initialized. * @param {EventData} ctx */ treeInit: function(ctx) { //this.debug("Fancytree.treeInit()"); this.treeLoad(ctx); }, /** Parse Fancytree from source, as configured in the options. * @param {EventData} ctx * @param {object} [source] optional new source (use last data otherwise) */ treeLoad: function(ctx, source) { var type, $ul, tree = ctx.tree, $container = ctx.widget.element, dfd, // calling context for root node rootCtx = $.extend({}, ctx, {node: this.rootNode}); if(tree.rootNode.children){ this.treeClear(ctx); } source = source || this.options.source; if(!source){ type = $container.data("type") || "html"; switch(type){ case "html": $ul = $container.find(">ul:first"); $ul.addClass("ui-fancytree-source ui-helper-hidden"); source = $.ui.fancytree.parseHtml($ul); // allow to init tree.data.foo from <ul data-foo=''> this.data = $.extend(this.data, _getElementDataAsDict($ul)); break; case "json": // $().addClass("ui-helper-hidden"); source = $.parseJSON($container.text()); if(source.children){ if(source.title){tree.title = source.title;} source = source.children; } break; default: $.error("Invalid data-type: " + type); } }else if(typeof source === "string"){ // TODO: source is an element ID $.error("Not implemented"); } // $container.addClass("ui-widget ui-widget-content ui-corner-all"); // Trigger fancytreeinit after nodes have been loaded dfd = this.nodeLoadChildren(rootCtx, source).done(function(){ tree.render(); if( ctx.options.selectMode === 3 ){ tree.rootNode.fixSelection3FromEndNodes(); } tree._triggerTreeEvent("init", null, { status: true }); }).fail(function(){ tree.render(); tree._triggerTreeEvent("init", null, { status: false }); }); return dfd; }, /** Node was inserted into or removed from the tree. * @param {EventData} ctx * @param {boolean} add * @param {FancytreeNode} node */ treeRegisterNode: function(ctx, add, node) { }, /** Widget got focus. * @param {EventData} ctx * @param {boolean} [flag=true] */ treeSetFocus: function(ctx, flag, _calledByNodeSetFocus) { flag = (flag !== false); // this.debug("treeSetFocus(" + flag + "), _calledByNodeSetFocus: " + _calledByNodeSetFocus); // this.debug(" focusNode: " + this.focusNode); // this.debug(" activeNode: " + this.activeNode); if( flag !== this.hasFocus() ){ this._hasFocus = flag; this.$container.toggleClass("fancytree-treefocus", flag); this._triggerTreeEvent(flag ? "focusTree" : "blurTree"); } } }); /* ****************************************************************************** * jQuery UI widget boilerplate */ /** * The plugin (derrived from <a href=" http://api.jqueryui.com/jQuery.widget/">jQuery.Widget</a>).<br> * This constructor is not called directly. Use `$(selector).fancytree({})` * to initialize the plugin instead.<br> * <pre class="sh_javascript sunlight-highlight-javascript">// Access widget methods and members: * var tree = $("#tree").fancytree("getTree"); * var node = $("#tree").fancytree("getActiveNode", "1234"); * </pre> * * @mixin Fancytree_Widget */ $.widget("ui.fancytree", /** @lends Fancytree_Widget# */ { /**These options will be used as defaults * @type {FancytreeOptions} */ options: { activeVisible: true, ajax: { type: "GET", cache: false, // false: Append random '_' argument to the request url to prevent caching. // timeout: 0, // >0: Make sure we get an ajax error if server is unreachable dataType: "json" // Expect json format and pass json object to callbacks. }, // aria: false, // TODO: default to true autoActivate: true, autoCollapse: false, // autoFocus: false, autoScroll: false, checkbox: false, /**defines click behavior*/ clickFolderMode: 4, debugLevel: null, // 0..2 (null: use global setting $.ui.fancytree.debugInfo) disabled: false, // TODO: required anymore? enableAspx: true, // TODO: document extensions: [], // fx: { height: "toggle", duration: 200 }, // toggleEffect: { effect: "drop", options: {direction: "left"}, duration: 200 }, // toggleEffect: { effect: "slide", options: {direction: "up"}, duration: 200 }, toggleEffect: { effect: "blind", options: {direction: "vertical", scale: "box"}, duration: 200 }, generateIds: false, icons: true, idPrefix: "ft_", focusOnSelect: false, keyboard: true, keyPathSeparator: "/", minExpandLevel: 1, quicksearch: false, scrollOfs: {top: 0, bottom: 0}, scrollParent: null, selectMode: 2, strings: { loading: "Loading&#8230;", loadError: "Load error!" }, tabbable: true, titlesTabbable: false, _classNames: { node: "fancytree-node", folder: "fancytree-folder", combinedExpanderPrefix: "fancytree-exp-", combinedIconPrefix: "fancytree-ico-", hasChildren: "fancytree-has-children", active: "fancytree-active", selected: "fancytree-selected", expanded: "fancytree-expanded", lazy: "fancytree-lazy", focused: "fancytree-focused", partsel: "fancytree-partsel", unselectable: "fancytree-unselectable", lastsib: "fancytree-lastsib", loading: "fancytree-loading", error: "fancytree-error" }, // events lazyLoad: null, postProcess: null }, /* Set up the widget, Called on first $().fancytree() */ _create: function() { this.tree = new Fancytree(this); this.$source = this.source || this.element.data("type") === "json" ? this.element : this.element.find(">ul:first"); // Subclass Fancytree instance with all enabled extensions var extension, extName, i, extensions = this.options.extensions, base = this.tree; for(i=0; i<extensions.length; i++){ extName = extensions[i]; extension = $.ui.fancytree._extensions[extName]; if(!extension){ $.error("Could not apply extension '" + extName + "' (it is not registered, did you forget to include it?)"); } // Add extension options as tree.options.EXTENSION // _assert(!this.tree.options[extName], "Extension name must not exist as option name: " + extName); this.tree.options[extName] = $.extend(true, {}, extension.options, this.tree.options[extName]); // Add a namespace tree.ext.EXTENSION, to hold instance data _assert(this.tree.ext[extName] === undefined, "Extension name must not exist as Fancytree.ext attribute: '" + extName + "'"); // this.tree[extName] = extension; this.tree.ext[extName] = {}; // Subclass Fancytree methods using proxies. _subclassObject(this.tree, base, extension, extName); // current extension becomes base for the next extension base = extension; } // this.tree._callHook("treeCreate", this.tree); // Note: 'fancytreecreate' event is fired by widget base class // this.tree._triggerTreeEvent("create"); }, /* Called on every $().fancytree() */ _init: function() { this.tree._callHook("treeInit", this.tree); // TODO: currently we call bind after treeInit, because treeInit // might change tree.$container. // It would be better, to move ebent binding into hooks altogether this._bind(); }, /* Use the _setOption method to respond to changes to options */ _setOption: function(key, value) { var callDefault = true, rerender = false; switch( key ) { case "aria": case "checkbox": case "icons": case "minExpandLevel": case "tabbable": // case "nolink": this.tree._callHook("treeCreate", this.tree); rerender = true; break; case "source": callDefault = false; this.tree._callHook("treeLoad", this.tree, value); break; } this.tree.debug("set option " + key + "=" + value + " <" + typeof(value) + ">"); if(callDefault){ // In jQuery UI 1.8, you have to manually invoke the _setOption method from the base widget $.Widget.prototype._setOption.apply(this, arguments); // TODO: In jQuery UI 1.9 and above, you use the _super method instead // this._super( "_setOption", key, value ); } if(rerender){ this.tree.render(true, false); // force, not-deep } }, /** Use the destroy method to clean up any modifications your widget has made to the DOM */ destroy: function() { this._unbind(); this.tree._callHook("treeDestroy", this.tree); // this.element.removeClass("ui-widget ui-widget-content ui-corner-all"); this.tree.$div.find(">ul.fancytree-container").remove(); this.$source && this.$source.removeClass("ui-helper-hidden"); // In jQuery UI 1.8, you must invoke the destroy method from the base widget $.Widget.prototype.destroy.call(this); // TODO: delete tree and nodes to make garbage collect easier? // TODO: In jQuery UI 1.9 and above, you would define _destroy instead of destroy and not call the base method }, // ------------------------------------------------------------------------- /* Remove all event handlers for our namespace */ _unbind: function() { var ns = this.tree._ns; this.element.unbind(ns); this.tree.$container.unbind(ns); $(document).unbind(ns); }, /* Add mouse and kyboard handlers to the container */ _bind: function() { var that = this, opts = this.options, tree = this.tree, ns = tree._ns // selstartEvent = ( $.support.selectstart ? "selectstart" : "mousedown" ) ; // Remove all previuous handlers for this tree this._unbind(); //alert("keydown" + ns + "foc=" + tree.hasFocus() + tree.$container); // tree.debug("bind events; container: ", tree.$container); tree.$container.on("focusin" + ns + " focusout" + ns, function(event){ var node = FT.getNode(event), flag = (event.type === "focusin"); // tree.debug("Tree container got event " + event.type, node, event); // tree.treeOnFocusInOut.call(tree, event); if(node){ // For example clicking into an <input> that is part of a node tree._callHook("nodeSetFocus", node, flag); }else{ tree._callHook("treeSetFocus", tree, flag); } }).on("selectstart" + ns, "span.fancytree-title", function(event){ // prevent mouse-drags to select text ranges // tree.debug("<span title> got event " + event.type); event.preventDefault(); }).on("keydown" + ns, function(event){ // TODO: also bind keyup and keypress // tree.debug("got event " + event.type + ", hasFocus:" + tree.hasFocus()); // if(opts.disabled || opts.keyboard === false || !tree.hasFocus() ){ if(opts.disabled || opts.keyboard === false ){ return true; } var res, node = tree.focusNode, // node may be null ctx = tree._makeHookContext(node || tree, event), prevPhase = tree.phase; try { tree.phase = "userEvent"; // If a 'fancytreekeydown' handler returns false, skip the default // handling (implemented by tree.nodeKeydown()). if(node){ res = tree._triggerNodeEvent("keydown", node, event); }else{ res = tree._triggerTreeEvent("keydown", event); } if ( res === "preventNav" ){ res = true; // prevent keyboard navigation, but don't prevent default handling of embedded input controls } else if ( res !== false ){ res = tree._callHook("nodeKeydown", ctx); } return res; } finally { tree.phase = prevPhase; } }).on("click" + ns + " dblclick" + ns, function(event){ if(opts.disabled){ return true; } var ctx, et = FT.getEventTarget(event), node = et.node, tree = that.tree, prevPhase = tree.phase; if( !node ){ return true; // Allow bubbling of other events } ctx = tree._makeHookContext(node, event); // that.tree.debug("event(" + event.type + "): node: ", node); try { tree.phase = "userEvent"; switch(event.type) { case "click": ctx.targetType = et.type; return ( tree._triggerNodeEvent("click", ctx, event) === false ) ? false : tree._callHook("nodeClick", ctx); case "dblclick": ctx.targetType = et.type; return ( tree._triggerNodeEvent("dblclick", ctx, event) === false ) ? false : tree._callHook("nodeDblclick", ctx); } // } catch(e) { // // var _ = null; // DT issue 117 // TODO // $.error(e); } finally { tree.phase = prevPhase; } }); }, /** Return the active node or null. * @returns {FancytreeNode} */ getActiveNode: function() { return this.tree.activeNode; }, /** Return the matching node or null. * @param {string} key * @returns {FancytreeNode} */ getNodeByKey: function(key) { return this.tree.getNodeByKey(key); }, /** Return the invisible system root node. * @returns {FancytreeNode} */ getRootNode: function() { return this.tree.rootNode; }, /** Return the current tree instance. * @returns {Fancytree} */ getTree: function() { return this.tree; } }); // $.ui.fancytree was created by the widget factory. Create a local shortcut: FT = $.ui.fancytree; /** * Static members in the `$.ui.fancytree` namespace.<br> * <br> * <pre class="sh_javascript sunlight-highlight-javascript">// Access static members: * var node = $.ui.fancytree.getNode(element); * alert($.ui.fancytree.version); * </pre> * * @mixin Fancytree_Static */ $.extend($.ui.fancytree, /** @lends Fancytree_Static# */ { /** @type {string} */ version: "2.7.0", // Set to semver by 'grunt release' /** @type {string} */ buildType: "production", // Set to 'production' by 'grunt build' /** @type {int} */ debugLevel: 1, // Set to 1 by 'grunt build' // Used by $.ui.fancytree.debug() and as default for tree.options.debugLevel _nextId: 1, _nextNodeKey: 1, _extensions: {}, // focusTree: null, /** Expose class object as $.ui.fancytree._FancytreeClass */ _FancytreeClass: Fancytree, /** Expose class object as $.ui.fancytree._FancytreeNodeClass */ _FancytreeNodeClass: FancytreeNode, /* Feature checks to provide backwards compatibility */ jquerySupports: { // http://jqueryui.com/upgrade-guide/1.9/#deprecated-offset-option-merged-into-my-and-at positionMyOfs: isVersionAtLeast($.ui.version, 1, 9) }, /** Throw an error if condition fails (debug method). * @param {boolean} cond * @param {string} msg */ assert: function(cond, msg){ return _assert(cond, msg); }, /** Return a function that executes *fn* at most every *timeout* ms. * @param {integer} timeout * @param {function} fn * @param {boolean} [invokeAsap=false] * @param {any} [ctx] */ debounce: function(timeout, fn, invokeAsap, ctx) { var timer; if(arguments.length === 3 && typeof invokeAsap !== "boolean") { ctx = invokeAsap; invokeAsap = false; } return function() { var args = arguments; ctx = ctx || this; invokeAsap && !timer && fn.apply(ctx, args); clearTimeout(timer); timer = setTimeout(function() { invokeAsap || fn.apply(ctx, args); timer = null; }, timeout); }; }, /** Write message to console if debugLevel >= 2 * @param {string} msg */ debug: function(msg){ /*jshint expr:true */ ($.ui.fancytree.debugLevel >= 2) && consoleApply("log", arguments); }, /** Write error message to console. * @param {string} msg */ error: function(msg){ consoleApply("error", arguments); }, /** Convert &lt;, &gt;, &amp;, &quot;, &#39;, &#x2F; to the equivalent entitites. * * @param {string} s * @returns {string} */ escapeHtml: function(s){ return ("" + s).replace(/[&<>"'\/]/g, function (s) { return ENTITY_MAP[s]; }); }, /** Return a {node: FancytreeNode, type: TYPE} object for a mouse event. * * @param {Event} event Mouse event, e.g. click, ... * @returns {string} 'title' | 'prefix' | 'expander' | 'checkbox' | 'icon' | undefined */ getEventTargetType: function(event){ return this.getEventTarget(event).type; }, /** Return a {node: FancytreeNode, type: TYPE} object for a mouse event. * * @param {Event} event Mouse event, e.g. click, ... * @returns {object} Return a {node: FancytreeNode, type: TYPE} object * TYPE: 'title' | 'prefix' | 'expander' | 'checkbox' | 'icon' | undefined */ getEventTarget: function(event){ var tcn = event && event.target ? event.target.className : "", res = {node: this.getNode(event.target), type: undefined}; // We use a fast version of $(res.node).hasClass() // See http://jsperf.com/test-for-classname/2 if( /\bfancytree-title\b/.test(tcn) ){ res.type = "title"; }else if( /\bfancytree-expander\b/.test(tcn) ){ res.type = (res.node.hasChildren() === false ? "prefix" : "expander"); }else if( /\bfancytree-checkbox\b/.test(tcn) || /\bfancytree-radio\b/.test(tcn) ){ res.type = "checkbox"; }else if( /\bfancytree-icon\b/.test(tcn) ){ res.type = "icon"; }else if( /\bfancytree-node\b/.test(tcn) ){ // Somewhere near the title res.type = "title"; }else if( event && event.target && $(event.target).closest(".fancytree-title").length ) { // #228: clicking an embedded element inside a title res.type = "title"; } return res; }, /** Return a FancytreeNode instance from element. * * @param {Element | jQueryObject | Event} el * @returns {FancytreeNode} matching node or null */ getNode: function(el){ if(el instanceof FancytreeNode){ return el; // el already was a FancytreeNode }else if(el.selector !== undefined){ el = el[0]; // el was a jQuery object: use the DOM element }else if(el.originalEvent !== undefined){ el = el.target; // el was an Event } while( el ) { if(el.ftnode) { return el.ftnode; } el = el.parentNode; } return null; }, /* Return a Fancytree instance from element. * TODO: this function could help to get around the data('fancytree') / data('ui-fancytree') problem * @param {Element | jQueryObject | Event} el * @returns {Fancytree} matching tree or null * / getTree: function(el){ if(el instanceof Fancytree){ return el; // el already was a Fancytree }else if(el.selector !== undefined){ el = el[0]; // el was a jQuery object: use the DOM element }else if(el.originalEvent !== undefined){ el = el.target; // el was an Event } ... return null; }, */ /** Write message to console if debugLevel >= 1 * @param {string} msg */ info: function(msg){ /*jshint expr:true */ ($.ui.fancytree.debugLevel >= 1) && consoleApply("info", arguments); }, /** Convert a keydown event to a string like 'ctrl+a', 'ctrl+shift+f2'. * @param {event} * @returns {string} */ keyEventToString: function(event) { // Poor-man's hotkeys. See here for a complete implementation: // https://github.com/jeresig/jquery.hotkeys var which = event.which, s = []; if( event.altKey ) { s.push("alt"); } if( event.ctrlKey ) { s.push("ctrl"); } if( event.metaKey ) { s.push("meta"); } if( event.shiftKey ) { s.push("shift"); } if( !IGNORE_KEYCODES[which] ) { s.push( SPECIAL_KEYCODES[which] || String.fromCharCode(which).toLowerCase() ); } return s.join("+"); }, /** * Parse tree data from HTML <ul> markup * * @param {jQueryObject} $ul * @returns {NodeData[]} */ parseHtml: function($ul) { // TODO: understand this: /*jshint validthis:true */ var extraClasses, i, l, iPos, tmp, tmp2, classes, className, $children = $ul.find(">li"), children = []; $children.each(function() { var allData, $li = $(this), $liSpan = $li.find(">span:first", this), $liA = $liSpan.length ? null : $li.find(">a:first"), d = { tooltip: null, data: {} }; if( $liSpan.length ) { d.title = $liSpan.html(); } else if( $liA && $liA.length ) { // If a <li><a> tag is specified, use it literally and extract href/target. d.title = $liA.html(); d.data.href = $liA.attr("href"); d.data.target = $liA.attr("target"); d.tooltip = $liA.attr("title"); } else { // If only a <li> tag is specified, use the trimmed string up to // the next child <ul> tag. d.title = $li.html(); iPos = d.title.search(/<ul/i); if( iPos >= 0 ){ d.title = d.title.substring(0, iPos); } } d.title = $.trim(d.title); // Make sure all fields exist for(i=0, l=CLASS_ATTRS.length; i<l; i++){ d[CLASS_ATTRS[i]] = undefined; } // Initialize to `true`, if class is set and collect extraClasses classes = this.className.split(" "); extraClasses = []; for(i=0, l=classes.length; i<l; i++){ className = classes[i]; if(CLASS_ATTR_MAP[className]){ d[className] = true; }else{ extraClasses.push(className); } } d.extraClasses = extraClasses.join(" "); // Parse node options from ID, title and class attributes tmp = $li.attr("title"); if( tmp ){ d.tooltip = tmp; // overrides <a title='...'> } tmp = $li.attr("id"); if( tmp ){ d.key = tmp; } // Add <li data-NAME='...'> as node.data.NAME allData = _getElementDataAsDict($li); if(allData && !$.isEmptyObject(allData)) { // #56: Allow to set special node.attributes from data-... for(i=0, l=NODE_ATTRS.length; i<l; i++){ tmp = NODE_ATTRS[i]; tmp2 = allData[tmp]; if( tmp2 != null ) { delete allData[tmp]; d[tmp] = tmp2; } } // All other data-... goes to node.data... $.extend(d.data, allData); } // Recursive reading of child nodes, if LI tag contains an UL tag $ul = $li.find(">ul:first"); if( $ul.length ) { d.children = $.ui.fancytree.parseHtml($ul); }else{ d.children = d.lazy ? undefined : null; } children.push(d); // FT.debug("parse ", d, children); }); return children; }, /** Add Fancytree extension definition to the list of globally available extensions. * * @param {object} definition */ registerExtension: function(definition){ _assert(definition.name != null, "extensions must have a `name` property."); _assert(definition.version != null, "extensions must have a `version` property."); $.ui.fancytree._extensions[definition.name] = definition; }, /** Inverse of escapeHtml(). * * @param {string} s * @returns {string} */ unescapeHtml: function(s){ var e = document.createElement("div"); e.innerHTML = s; return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue; }, /** Write warning message to console. * @param {string} msg */ warn: function(msg){ consoleApply("warn", arguments); } }); }(jQuery, window, document)); // Extending Fancytree // =================== // // See also the [live demo](http://wwwendt.de/tech/fancytree/demo/sample-ext-childcounter.html) of this code. // // Every extension should have a comment header containing some information // about the author, copyright and licensing. Also a pointer to the latest // source code. // Prefix with `/*!` so the comment is not removed by the minifier. /*! * jquery.fancytree.childcounter.js * * Add a child counter bubble to tree nodes. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/) * * Copyright (c) 2014, Martin Wendt (http://wwWendt.de) * * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.7.0 * @date 2014-12-21T15:57 */ // To keep the global namespace clean, we wrap everything in a closure ;(function($, undefined) { // Consider to use [strict mode](http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/) "use strict"; // The [coding guidelines](http://contribute.jquery.org/style-guide/js/) // require jshint compliance. // But for this sample, we want to allow unused variables for demonstration purpose. /*jshint unused:false */ // Adding methods // -------------- // New member functions can be added to the `Fancytree` class. // This function will be available for every tree instance. // // var tree = $("#tree").fancytree("getTree"); // tree.countSelected(false); $.ui.fancytree._FancytreeClass.prototype.countSelected = function(topOnly){ var tree = this, treeOptions = tree.options; return tree.getSelectedNodes(topOnly).length; }; // The `FancytreeNode` class can also be easily extended. This would be called // like // // node.toUpper(); $.ui.fancytree._FancytreeNodeClass.prototype.toUpper = function(){ var node = this; return node.setTitle(node.title.toUpperCase()); }; // Finally, we can extend the widget API and create functions that are called // like so: // // $("#tree").fancytree("widgetMethod1", "abc"); $.ui.fancytree.prototype.widgetMethod1 = function(arg1){ var tree = this.tree; return arg1; }; // Register a Fancytree extension // ------------------------------ // A full blown extension, extension is available for all trees and can be // enabled like so (see also the [live demo](http://wwwendt.de/tech/fancytree/demo/sample-ext-childcounter.html)): // // <script src="../src/jquery.fancytree.js" type="text/javascript"></script> // <script src="../src/jquery.fancytree.childcounter.js" type="text/javascript"></script> // ... // // $("#tree").fancytree({ // extensions: ["childcounter"], // childcounter: { // hideExpanded: true // }, // ... // }); // /* 'childcounter' extension */ $.ui.fancytree.registerExtension({ // Every extension must be registered by a unique name. name: "childcounter", // Version information should be compliant with [semver](http://semver.org) version: "1.0.0", // Extension specific options and their defaults. // This options will be available as `tree.options.childcounter.hideExpanded` options: { deep: true, hideZeros: true, hideExpanded: false }, // Attributes other than `options` (or functions) can be defined here, and // will be added to the tree.ext.EXTNAME namespace, in this case `tree.ext.childcounter.foo`. // They can also be accessed as `this._local.foo` from within the extension // methods. foo: 42, // Local functions are prefixed with an underscore '_'. // Callable as `this._local._appendCounter()`. _appendCounter: function(bar){ var tree = this; }, // **Override virtual methods for this extension.** // // Fancytree implements a number of 'hook methods', prefixed by 'node...' or 'tree...'. // with a `ctx` argument (see [EventData](http://www.wwwendt.de/tech/fancytree/doc/jsdoc/global.html#EventData) // for details) and an extended calling context:<br> // `this` : the Fancytree instance<br> // `this._local`: the namespace that contains extension attributes and private methods (same as this.ext.EXTNAME)<br> // `this._super`: the virtual function that was overridden (member of previous extension or Fancytree) // // See also the [complete list of available hook functions](http://www.wwwendt.de/tech/fancytree/doc/jsdoc/Fancytree_Hooks.html). /* Init */ // `treeInit` is triggered when a tree is initalized. We can set up classes or // bind event handlers here... treeInit: function(ctx){ var tree = this, // same as ctx.tree, opts = ctx.options, extOpts = ctx.options.childcounter; // Optionally check for dependencies with other extensions /* this._requireExtension("glyph", false, false); */ // Call the base implementation this._super(ctx); // Add a class to the tree container this.$container.addClass("fancytree-ext-childcounter"); }, // Destroy this tree instance (we only call the default implementation, so // this method could as well be omitted). treeDestroy: function(ctx){ this._super(ctx); }, // Overload the `renderTitle` hook, to append a counter badge nodeRenderTitle: function(ctx, title) { var node = ctx.node, extOpts = ctx.options.childcounter, count = (node.data.childCounter == null) ? node.countChildren(extOpts.deep) : +node.data.childCounter; // Let the base implementation render the title this._super(ctx, title); // Append a counter badge if( (count || ! extOpts.hideZeros) && (!node.isExpanded() || !extOpts.hideExpanded) ){ $("span.fancytree-icon", node.span).append($("<span class='fancytree-childcounter'/>").text(count)); } }, // Overload the `setExpanded` hook, so the counters are updated nodeSetExpanded: function(ctx, flag, opts) { var tree = ctx.tree, node = ctx.node; // Let the base implementation expand/collapse the node, then redraw the title // after the animation has finished return this._super(ctx, flag, opts).always(function(){ tree.nodeRenderTitle(ctx); }); } // End of extension definition }); // End of namespace closure }(jQuery)); /*! * * jquery.fancytree.clones.js * Support faster lookup of nodes by key and shared ref-ids. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/) * * Copyright (c) 2014, Martin Wendt (http://wwWendt.de) * * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.7.0 * @date 2014-12-21T15:57 */ ;(function($, window, document, undefined) { "use strict"; /******************************************************************************* * Private functions and variables */ function _assert(cond, msg){ // TODO: see qunit.js extractStacktrace() if(!cond){ msg = msg ? ": " + msg : ""; $.error("Assertion failed" + msg); } } /* Return first occurrence of member from array. */ function _removeArrayMember(arr, elem) { // TODO: use Array.indexOf for IE >= 9 var i; for (i = arr.length - 1; i >= 0; i--) { if (arr[i] === elem) { arr.splice(i, 1); return true; } } return false; } // /** // * Calculate a 32 bit FNV-1a hash // * Found here: https://gist.github.com/vaiorabbit/5657561 // * Ref.: http://isthe.com/chongo/tech/comp/fnv/ // * // * @param {string} str the input value // * @param {boolean} [asString=false] set to true to return the hash value as // * 8-digit hex string instead of an integer // * @param {integer} [seed] optionally pass the hash of the previous chunk // * @returns {integer | string} // */ // function hashFnv32a(str, asString, seed) { // /*jshint bitwise:false */ // var i, l, // hval = (seed === undefined) ? 0x811c9dc5 : seed; // for (i = 0, l = str.length; i < l; i++) { // hval ^= str.charCodeAt(i); // hval += (hval << 1) + (hval << 4) + (hval << 7) + (hval << 8) + (hval << 24); // } // if( asString ){ // // Convert to 8 digit hex string // return ("0000000" + (hval >>> 0).toString(16)).substr(-8); // } // return hval >>> 0; // } /** * JS Implementation of MurmurHash3 (r136) (as of May 20, 2011) * * @author <a href="mailto:[email protected]">Gary Court</a> * @see http://github.com/garycourt/murmurhash-js * @author <a href="mailto:[email protected]">Austin Appleby</a> * @see http://sites.google.com/site/murmurhash/ * * @param {string} key ASCII only * @param {boolean} [asString=false] * @param {number} seed Positive integer only * @return {number} 32-bit positive integer hash */ function hashMurmur3(key, asString, seed) { /*jshint bitwise:false */ var h1b, k1, remainder = key.length & 3, bytes = key.length - remainder, h1 = seed, c1 = 0xcc9e2d51, c2 = 0x1b873593, i = 0; while (i < bytes) { k1 = ((key.charCodeAt(i) & 0xff)) | ((key.charCodeAt(++i) & 0xff) << 8) | ((key.charCodeAt(++i) & 0xff) << 16) | ((key.charCodeAt(++i) & 0xff) << 24); ++i; k1 = ((((k1 & 0xffff) * c1) + ((((k1 >>> 16) * c1) & 0xffff) << 16))) & 0xffffffff; k1 = (k1 << 15) | (k1 >>> 17); k1 = ((((k1 & 0xffff) * c2) + ((((k1 >>> 16) * c2) & 0xffff) << 16))) & 0xffffffff; h1 ^= k1; h1 = (h1 << 13) | (h1 >>> 19); h1b = ((((h1 & 0xffff) * 5) + ((((h1 >>> 16) * 5) & 0xffff) << 16))) & 0xffffffff; h1 = (((h1b & 0xffff) + 0x6b64) + ((((h1b >>> 16) + 0xe654) & 0xffff) << 16)); } k1 = 0; switch (remainder) { /*jshint -W086:true */ case 3: k1 ^= (key.charCodeAt(i + 2) & 0xff) << 16; case 2: k1 ^= (key.charCodeAt(i + 1) & 0xff) << 8; case 1: k1 ^= (key.charCodeAt(i) & 0xff); k1 = (((k1 & 0xffff) * c1) + ((((k1 >>> 16) * c1) & 0xffff) << 16)) & 0xffffffff; k1 = (k1 << 15) | (k1 >>> 17); k1 = (((k1 & 0xffff) * c2) + ((((k1 >>> 16) * c2) & 0xffff) << 16)) & 0xffffffff; h1 ^= k1; } h1 ^= key.length; h1 ^= h1 >>> 16; h1 = (((h1 & 0xffff) * 0x85ebca6b) + ((((h1 >>> 16) * 0x85ebca6b) & 0xffff) << 16)) & 0xffffffff; h1 ^= h1 >>> 13; h1 = ((((h1 & 0xffff) * 0xc2b2ae35) + ((((h1 >>> 16) * 0xc2b2ae35) & 0xffff) << 16))) & 0xffffffff; h1 ^= h1 >>> 16; if( asString ){ // Convert to 8 digit hex string return ("0000000" + (h1 >>> 0).toString(16)).substr(-8); } return h1 >>> 0; } // console.info(hashMurmur3("costarring")); // console.info(hashMurmur3("costarring", true)); // console.info(hashMurmur3("liquid")); // console.info(hashMurmur3("liquid", true)); /* * Return a unique key for node by calculationg the hash of the parents refKey-list */ function calcUniqueKey(node) { var key, path = $.map(node.getParentList(false, true), function(e){ return e.refKey || e.key; }); path = path.join("/"); key = "id_" + hashMurmur3(path, true); // node.debug(path + " -> " + key); return key; } /** * [ext-clones] Return a list of clone-nodes or null. * @param {boolean} [includeSelf=false] * @returns {FancytreeNode[] | null} * * @alias FancytreeNode#getCloneList * @requires jquery.fancytree.clones.js */ $.ui.fancytree._FancytreeNodeClass.prototype.getCloneList = function(includeSelf){ var key, tree = this.tree, refList = tree.refMap[this.refKey] || null, keyMap = tree.keyMap; if( refList ) { key = this.key; // Convert key list to node list if( includeSelf ) { refList = $.map(refList, function(val){ return keyMap[val]; }); } else { refList = $.map(refList, function(val){ return val === key ? null : keyMap[val]; }); if( refList.length < 1 ) { refList = null; } } } return refList; }; /** * [ext-clones] Return true if this node has at least another clone with same refKey. * @returns {boolean} * * @alias FancytreeNode#isClone * @requires jquery.fancytree.clones.js */ $.ui.fancytree._FancytreeNodeClass.prototype.isClone = function(){ var refKey = this.refKey || null, refList = refKey && this.tree.refMap[refKey] || null; return !!(refList && refList.length > 1); }; /** * [ext-clones] Update key and/or refKey for an existing node. * @param {string} key * @param {string} refKey * @returns {boolean} * * @alias FancytreeNode#reRegister * @requires jquery.fancytree.clones.js */ $.ui.fancytree._FancytreeNodeClass.prototype.reRegister = function(key, refKey){ key = (key == null) ? null : "" + key; refKey = (refKey == null) ? null : "" + refKey; // this.debug("reRegister", key, refKey); var tree = this.tree, prevKey = this.key, prevRefKey = this.refKey, keyMap = tree.keyMap, refMap = tree.refMap, refList = refMap[prevRefKey] || null, // curCloneKeys = refList ? node.getCloneList(true), modified = false; // Key has changed: update all references if( key != null && key !== this.key ) { if( keyMap[key] ) { $.error("[ext-clones] reRegister(" + key + "): already exists: " + this); } // Update keyMap delete keyMap[prevKey]; keyMap[key] = this; // Update refMap if( refList ) { refMap[prevRefKey] = $.map(refList, function(e){ return e === prevKey ? key : e; }); } this.key = key; modified = true; } // refKey has changed if( refKey != null && refKey !== this.refKey ) { // Remove previous refKeys if( refList ){ if( refList.length === 1 ){ delete refMap[prevRefKey]; }else{ refMap[prevRefKey] = $.map(refList, function(e){ return e === prevKey ? null : e; }); } } // Add refKey if( refMap[refKey] ) { refMap[refKey].append(key); }else{ refMap[refKey] = [ this.key ]; } this.refKey = refKey; modified = true; } return modified; }; /** * [ext-clones] Return all nodes with a given refKey (null if not found). * @param {string} refKey * @param {FancytreeNode} [rootNode] optionally restrict results to descendants of this node * @returns {FancytreeNode[] | null} * @alias Fancytree#getNodesByRef * @requires jquery.fancytree.clones.js */ $.ui.fancytree._FancytreeClass.prototype.getNodesByRef = function(refKey, rootNode){ var keyMap = this.keyMap, refList = this.refMap[refKey] || null; if( refList ) { // Convert key list to node list if( rootNode ) { refList = $.map(refList, function(val){ var node = keyMap[val]; return node.isDescendantOf(rootNode) ? node : null; }); }else{ refList = $.map(refList, function(val){ return keyMap[val]; }); } if( refList.length < 1 ) { refList = null; } } return refList; }; /** * [ext-clones] Replace a refKey with a new one. * @param {string} oldRefKey * @param {string} newRefKey * @alias Fancytree#changeRefKey * @requires jquery.fancytree.clones.js */ $.ui.fancytree._FancytreeClass.prototype.changeRefKey = function(oldRefKey, newRefKey) { var i, node, keyMap = this.keyMap, refList = this.refMap[oldRefKey] || null; if (refList) { for (i = 0; i < refList.length; i++) { node = keyMap[refList[i]]; node.refKey = newRefKey; } delete this.refMap[oldRefKey]; this.refMap[newRefKey] = refList; } }; /******************************************************************************* * Extension code */ $.ui.fancytree.registerExtension({ name: "clones", version: "0.0.3", // Default options for this extension. options: { highlightActiveClones: true, // set 'fancytree-active-clone' on active clones and all peers highlightClones: false // set 'fancytree-clone' class on any node that has at least one clone }, treeCreate: function(ctx){ this._super(ctx); ctx.tree.refMap = {}; ctx.tree.keyMap = {}; }, treeInit: function(ctx){ this.$container.addClass("fancytree-ext-clones"); _assert(ctx.options.defaultKey == null); // Generate unique / reproducible default keys ctx.options.defaultKey = function(node){ return calcUniqueKey(node); }; // The default implementation loads initial data this._super(ctx); }, treeClear: function(ctx){ ctx.tree.refMap = {}; ctx.tree.keyMap = {}; return this._super(ctx); }, treeRegisterNode: function(ctx, add, node) { var refList, len, tree = ctx.tree, keyMap = tree.keyMap, refMap = tree.refMap, key = node.key, refKey = (node && node.refKey != null) ? "" + node.refKey : null; // ctx.tree.debug("clones.treeRegisterNode", add, node); if( key === "_statusNode" ){ return this._super(ctx, add, node); } if( add ) { if( keyMap[node.key] != null ) { $.error("clones.treeRegisterNode: node.key already exists: " + node); } keyMap[key] = node; if( refKey ) { refList = refMap[refKey]; if( refList ) { refList.push(key); if( refList.length === 2 && ctx.options.clones.highlightClones ) { // Mark peer node, if it just became a clone (no need to // mark current node, since it will be rendered later anyway) keyMap[refList[0]].renderStatus(); } } else { refMap[refKey] = [key]; } // node.debug("clones.treeRegisterNode: add clone =>", refMap[refKey]); } }else { if( keyMap[key] == null ) { $.error("clones.treeRegisterNode: node.key not registered: " + node.key); } delete keyMap[key]; if( refKey ) { refList = refMap[refKey]; // node.debug("clones.treeRegisterNode: remove clone BEFORE =>", refMap[refKey]); if( refList ) { len = refList.length; if( len <= 1 ){ _assert(len === 1); _assert(refList[0] === key); delete refMap[refKey]; }else{ _removeArrayMember(refList, key); // Unmark peer node, if this was the only clone if( len === 2 && ctx.options.clones.highlightClones ) { // node.debug("clones.treeRegisterNode: last =>", node.getCloneList()); keyMap[refList[0]].renderStatus(); } } // node.debug("clones.treeRegisterNode: remove clone =>", refMap[refKey]); } } } return this._super(ctx, add, node); }, nodeRenderStatus: function(ctx) { var $span, res, node = ctx.node; res = this._super(ctx); if( ctx.options.clones.highlightClones ) { $span = $(node[ctx.tree.statusClassPropName]); // Only if span already exists if( $span.length && node.isClone() ){ // node.debug("clones.nodeRenderStatus: ", ctx.options.clones.highlightClones); $span.addClass("fancytree-clone"); } } return res; }, nodeSetActive: function(ctx, flag) { var res, scpn = ctx.tree.statusClassPropName, node = ctx.node; res = this._super(ctx, flag); if( ctx.options.clones.highlightActiveClones && node.isClone() ) { $.each(node.getCloneList(true), function(idx, n){ // n.debug("clones.nodeSetActive: ", flag !== false); $(n[scpn]).toggleClass("fancytree-active-clone", flag !== false); }); } return res; } }); }(jQuery, window, document)); /*! * jquery.fancytree.dnd.js * * Drag-and-drop support. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/) * * Copyright (c) 2014, Martin Wendt (http://wwWendt.de) * * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.7.0 * @date 2014-12-21T15:57 */ ;(function($, window, document, undefined) { "use strict"; /* ***************************************************************************** * Private functions and variables */ var didRegisterDnd = false; /* Convert number to string and prepend +/-; return empty string for 0.*/ function offsetString(n){ return n === 0 ? "" : (( n > 0 ) ? ("+" + n) : ("" + n)); } /* ***************************************************************************** * Drag and drop support */ function _initDragAndDrop(tree) { var dnd = tree.options.dnd || null; // Register 'connectToFancytree' option with ui.draggable if( dnd ) { _registerDnd(); } // Attach ui.draggable to this Fancytree instance if(dnd && dnd.dragStart ) { tree.widget.element.draggable($.extend({ addClasses: false, // DT issue 244: helper should be child of scrollParent: appendTo: tree.$container, // appendTo: "body", containment: false, delay: 0, distance: 4, revert: false, scroll: true, // to disable, also set css 'position: inherit' on ul.fancytree-container scrollSpeed: 7, scrollSensitivity: 10, // Delegate draggable.start, drag, and stop events to our handler connectToFancytree: true, // Let source tree create the helper element helper: function(event) { var $helper, sourceNode = $.ui.fancytree.getNode(event.target), $nodeTag = $(sourceNode.span); if(!sourceNode){ // DT issue 211: might happen, if dragging a table *header* return "<div>ERROR?: helper requested but sourceNode not found</div>"; } // Only event and node argument is available $helper = $("<div class='fancytree-drag-helper'><span class='fancytree-drag-helper-img' /></div>") .css({zIndex: 3, position: "relative"}) // so it appears above ext-wide selection bar .append($nodeTag.find("span.fancytree-title").clone()); // Attach node reference to helper object $helper.data("ftSourceNode", sourceNode); // we return an unconnected element, so `draggable` will add this // to the parent specified as `appendTo` option return $helper; }, start: function(event, ui) { var sourceNode = ui.helper.data("ftSourceNode"); return !!sourceNode; // Abort dragging if no node could be found } }, tree.options.dnd.draggable)); } // Attach ui.droppable to this Fancytree instance if(dnd && dnd.dragDrop) { tree.widget.element.droppable($.extend({ addClasses: false, tolerance: "intersect", greedy: false /* activate: function(event, ui) { tree.debug("droppable - activate", event, ui, this); }, create: function(event, ui) { tree.debug("droppable - create", event, ui); }, deactivate: function(event, ui) { tree.debug("droppable - deactivate", event, ui); }, drop: function(event, ui) { tree.debug("droppable - drop", event, ui); }, out: function(event, ui) { tree.debug("droppable - out", event, ui); }, over: function(event, ui) { tree.debug("droppable - over", event, ui); } */ }, tree.options.dnd.droppable)); } } //--- Extend ui.draggable event handling -------------------------------------- function _registerDnd() { if(didRegisterDnd){ return; } // Register proxy-functions for draggable.start/drag/stop $.ui.plugin.add("draggable", "connectToFancytree", { start: function(event, ui) { // 'draggable' was renamed to 'ui-draggable' since jQueryUI 1.10 var draggable = $(this).data("ui-draggable") || $(this).data("draggable"), sourceNode = ui.helper.data("ftSourceNode") || null; if(sourceNode) { // Adjust helper offset, so cursor is slightly outside top/left corner draggable.offset.click.top = -2; draggable.offset.click.left = + 16; // Trigger dragStart event // TODO: when called as connectTo..., the return value is ignored(?) return sourceNode.tree.ext.dnd._onDragEvent("start", sourceNode, null, event, ui, draggable); } }, drag: function(event, ui) { var isHelper, logObject, // 'draggable' was renamed to 'ui-draggable' since jQueryUI 1.10 draggable = $(this).data("ui-draggable") || $(this).data("draggable"), sourceNode = ui.helper.data("ftSourceNode") || null, prevTargetNode = ui.helper.data("ftTargetNode") || null, targetNode = $.ui.fancytree.getNode(event.target); if(event.target && !targetNode){ // We got a drag event, but the targetNode could not be found // at the event location. This may happen, // 1. if the mouse jumped over the drag helper, // 2. or if a non-fancytree element is dragged // We ignore it: isHelper = $(event.target).closest("div.fancytree-drag-helper,#fancytree-drop-marker").length > 0; if(isHelper){ logObject = sourceNode || prevTargetNode || $.ui.fancytree; logObject.debug("Drag event over helper: ignored."); return; } } ui.helper.data("ftTargetNode", targetNode); // Leaving a tree node if(prevTargetNode && prevTargetNode !== targetNode ) { prevTargetNode.tree.ext.dnd._onDragEvent("leave", prevTargetNode, sourceNode, event, ui, draggable); } if(targetNode){ if(!targetNode.tree.options.dnd.dragDrop) { // not enabled as drop target } else if(targetNode === prevTargetNode) { // Moving over same node targetNode.tree.ext.dnd._onDragEvent("over", targetNode, sourceNode, event, ui, draggable); }else{ // Entering this node first time targetNode.tree.ext.dnd._onDragEvent("enter", targetNode, sourceNode, event, ui, draggable); } } // else go ahead with standard event handling }, stop: function(event, ui) { // 'draggable' was renamed to 'ui-draggable' since jQueryUI 1.10 var logObject, draggable = $(this).data("ui-draggable") || $(this).data("draggable"), sourceNode = ui.helper.data("ftSourceNode") || null, targetNode = ui.helper.data("ftTargetNode") || null, // mouseDownEvent = draggable._mouseDownEvent, eventType = event.type, dropped = (eventType === "mouseup" && event.which === 1); if(!dropped){ logObject = sourceNode || targetNode || $.ui.fancytree; logObject.debug("Drag was cancelled"); } if(targetNode) { if(dropped){ targetNode.tree.ext.dnd._onDragEvent("drop", targetNode, sourceNode, event, ui, draggable); } targetNode.tree.ext.dnd._onDragEvent("leave", targetNode, sourceNode, event, ui, draggable); } if(sourceNode){ sourceNode.tree.ext.dnd._onDragEvent("stop", sourceNode, null, event, ui, draggable); } } }); didRegisterDnd = true; } /* ***************************************************************************** * */ $.ui.fancytree.registerExtension({ name: "dnd", version: "0.1.0", // Default options for this extension. options: { // Make tree nodes accept draggables autoExpandMS: 1000, // Expand nodes after n milliseconds of hovering. draggable: null, // Additional options passed to jQuery draggable droppable: null, // Additional options passed to jQuery droppable focusOnClick: false, // Focus, although draggable cancels mousedown event (#270) // helper: null, // Callback // helperParent: null, // jQuery object (defaults to Fancytree container) preventVoidMoves: true, // Prevent dropping nodes 'before self', etc. preventRecursiveMoves: true, // Prevent dropping nodes on own descendants // Events (drag support) dragStart: null, // Callback(sourceNode, data), return true, to enable dnd dragStop: null, // Callback(sourceNode, data) // Events (drop support) dragEnter: null, // Callback(targetNode, data) dragOver: null, // Callback(targetNode, data) dragDrop: null, // Callback(targetNode, data) dragLeave: null // Callback(targetNode, data) }, treeInit: function(ctx){ var tree = ctx.tree; this._super(ctx); // issue #270: draggable eats mousedown events if( tree.options.dnd.dragStart ){ tree.$container.on("mousedown", function(event){ if( !tree.hasFocus() && ctx.options.dnd.focusOnClick ) { var node = $.ui.fancytree.getNode(event); node.debug("Re-enable focus that was prevented by jQuery UI draggable."); // node.setFocus(); // $(node.span).closest(":tabbable").focus(); // $(event.target).trigger("focus"); // $(event.target).closest(":tabbable").trigger("focus"); setTimeout(function() { // #300 $(event.target).closest(":tabbable").focus(); }, 10); } }); } _initDragAndDrop(tree); }, /* Override key handler in order to cancel dnd on escape.*/ nodeKeydown: function(ctx) { var event = ctx.originalEvent; if( event.which === $.ui.keyCode.ESCAPE) { this._local._cancelDrag(); } return this._super(ctx); }, nodeClick: function(ctx) { // if( ctx.options.dnd.dragStart ){ // ctx.tree.$container.focus(); // } return this._super(ctx); }, /* Display drop marker according to hitMode ('after', 'before', 'over', 'out', 'start', 'stop'). */ _setDndStatus: function(sourceNode, targetNode, helper, hitMode, accept) { var posOpts, markerOffsetX = 0, markerAt = "center", instData = this._local, $source = sourceNode ? $(sourceNode.span) : null, $target = $(targetNode.span); if( !instData.$dropMarker ) { instData.$dropMarker = $("<div id='fancytree-drop-marker'></div>") .hide() .css({"z-index": 1000}) .prependTo($(this.$div).parent()); // .prependTo("body"); } // this.$dropMarker.attr("class", hitMode); if(hitMode === "after" || hitMode === "before" || hitMode === "over"){ // $source && $source.addClass("fancytree-drag-source"); // $target.addClass("fancytree-drop-target"); switch(hitMode){ case "before": instData .$dropMarker.removeClass("fancytree-drop-after fancytree-drop-over") .addClass("fancytree-drop-before"); markerAt = "top"; break; case "after": instData.$dropMarker.removeClass("fancytree-drop-before fancytree-drop-over") .addClass("fancytree-drop-after"); markerAt = "bottom"; break; default: instData.$dropMarker.removeClass("fancytree-drop-after fancytree-drop-before") .addClass("fancytree-drop-over"); $target.addClass("fancytree-drop-target"); markerOffsetX = 8; } if( $.ui.fancytree.jquerySupports.positionMyOfs ){ posOpts = { my: "left" + offsetString(markerOffsetX) + " center", at: "left " + markerAt, of: $target }; } else { posOpts = { my: "left center", at: "left " + markerAt, of: $target, offset: "" + markerOffsetX + " 0" }; } instData.$dropMarker .show() .position(posOpts); // helper.addClass("fancytree-drop-hover"); } else { // $source && $source.removeClass("fancytree-drag-source"); $target.removeClass("fancytree-drop-target"); instData.$dropMarker.hide(); // helper.removeClass("fancytree-drop-hover"); } if(hitMode === "after"){ $target.addClass("fancytree-drop-after"); } else { $target.removeClass("fancytree-drop-after"); } if(hitMode === "before"){ $target.addClass("fancytree-drop-before"); } else { $target.removeClass("fancytree-drop-before"); } if(accept === true){ if($source){ $source.addClass("fancytree-drop-accept"); } $target.addClass("fancytree-drop-accept"); helper.addClass("fancytree-drop-accept"); }else{ if($source){ $source.removeClass("fancytree-drop-accept"); } $target.removeClass("fancytree-drop-accept"); helper.removeClass("fancytree-drop-accept"); } if(accept === false){ if($source){ $source.addClass("fancytree-drop-reject"); } $target.addClass("fancytree-drop-reject"); helper.addClass("fancytree-drop-reject"); }else{ if($source){ $source.removeClass("fancytree-drop-reject"); } $target.removeClass("fancytree-drop-reject"); helper.removeClass("fancytree-drop-reject"); } }, /* * Handles drag'n'drop functionality. * * A standard jQuery drag-and-drop process may generate these calls: * * draggable helper(): * _onDragEvent("helper", sourceNode, null, event, null, null); * start: * _onDragEvent("start", sourceNode, null, event, ui, draggable); * drag: * _onDragEvent("leave", prevTargetNode, sourceNode, event, ui, draggable); * _onDragEvent("over", targetNode, sourceNode, event, ui, draggable); * _onDragEvent("enter", targetNode, sourceNode, event, ui, draggable); * stop: * _onDragEvent("drop", targetNode, sourceNode, event, ui, draggable); * _onDragEvent("leave", targetNode, sourceNode, event, ui, draggable); * _onDragEvent("stop", sourceNode, null, event, ui, draggable); */ _onDragEvent: function(eventName, node, otherNode, event, ui, draggable) { if(eventName !== "over"){ this.debug("tree.ext.dnd._onDragEvent(%s, %o, %o) - %o", eventName, node, otherNode, this); } var /*$helper, $helperParent,*/ nodeOfs, relPos, relPos2, enterResponse, hitMode, r, opts = this.options, dnd = opts.dnd, ctx = this._makeHookContext(node, event, {otherNode: otherNode, ui: ui, draggable: draggable}), res = null, $nodeTag = $(node.span); switch (eventName) { // case "helper": // // Only event and node argument is available // $helper = $("<div class='fancytree-drag-helper'><span class='fancytree-drag-helper-img' /></div>") // .css({zIndex: 3, position: "relative"}) // so it appears above ext-wide selection bar // .append($nodeTag.find("span.fancytree-title").clone()); // // #345: helper parent is now set using draggable.appendTo // // $helperParent = dnd.helperParent || $("ul.fancytree-container", node.tree.$div); // // DT issue 244: helper should be child of scrollParent // // $helperParent.append($helper); // // Attach node reference to helper object // $helper.data("ftSourceNode", node); // // this.debug("helper=%o", $helper); // // this.debug("helper.sourceNode=%o", $helper.data("ftSourceNode")); // res = $helper; // break; case "start": if( node.isStatusNode() ) { res = false; } else if(dnd.dragStart) { res = dnd.dragStart(node, ctx); } if(res === false) { this.debug("tree.dragStart() cancelled"); //draggable._clear(); // NOTE: the return value seems to be ignored (drag is not canceled, when false is returned) // TODO: call this._cancelDrag()? ui.helper.trigger("mouseup") .hide(); } else { $nodeTag.addClass("fancytree-drag-source"); } break; case "enter": if(dnd.preventRecursiveMoves && node.isDescendantOf(otherNode)){ r = false; }else{ r = dnd.dragEnter ? dnd.dragEnter(node, ctx) : null; } if(!r){ // convert null, undefined, false to false res = false; }else if ( $.isArray(r) ) { // TODO: also accept passing an object of this format directly res = { over: ($.inArray("over", r) >= 0), before: ($.inArray("before", r) >= 0), after: ($.inArray("after", r) >= 0) }; }else{ res = { over: ((r === true) || (r === "over")), before: ((r === true) || (r === "before")), after: ((r === true) || (r === "after")) }; } ui.helper.data("enterResponse", res); this.debug("helper.enterResponse: %o", res); break; case "over": enterResponse = ui.helper.data("enterResponse"); hitMode = null; if(enterResponse === false){ // Don't call dragOver if onEnter returned false. // break; } else if(typeof enterResponse === "string") { // Use hitMode from onEnter if provided. hitMode = enterResponse; } else { // Calculate hitMode from relative cursor position. nodeOfs = $nodeTag.offset(); relPos = { x: event.pageX - nodeOfs.left, y: event.pageY - nodeOfs.top }; relPos2 = { x: relPos.x / $nodeTag.width(), y: relPos.y / $nodeTag.height() }; if( enterResponse.after && relPos2.y > 0.75 ){ hitMode = "after"; } else if(!enterResponse.over && enterResponse.after && relPos2.y > 0.5 ){ hitMode = "after"; } else if(enterResponse.before && relPos2.y <= 0.25) { hitMode = "before"; } else if(!enterResponse.over && enterResponse.before && relPos2.y <= 0.5) { hitMode = "before"; } else if(enterResponse.over) { hitMode = "over"; } // Prevent no-ops like 'before source node' // TODO: these are no-ops when moving nodes, but not in copy mode if( dnd.preventVoidMoves ){ if(node === otherNode){ this.debug(" drop over source node prevented"); hitMode = null; }else if(hitMode === "before" && otherNode && node === otherNode.getNextSibling()){ this.debug(" drop after source node prevented"); hitMode = null; }else if(hitMode === "after" && otherNode && node === otherNode.getPrevSibling()){ this.debug(" drop before source node prevented"); hitMode = null; }else if(hitMode === "over" && otherNode && otherNode.parent === node && otherNode.isLastSibling() ){ this.debug(" drop last child over own parent prevented"); hitMode = null; } } // this.debug("hitMode: %s - %s - %s", hitMode, (node.parent === otherNode), node.isLastSibling()); ui.helper.data("hitMode", hitMode); } // Auto-expand node (only when 'over' the node, not 'before', or 'after') if(hitMode === "over" && dnd.autoExpandMS && node.hasChildren() !== false && !node.expanded) { node.scheduleAction("expand", dnd.autoExpandMS); } if(hitMode && dnd.dragOver){ // TODO: http://code.google.com/p/dynatree/source/detail?r=625 ctx.hitMode = hitMode; res = dnd.dragOver(node, ctx); } // DT issue 332 // this._setDndStatus(otherNode, node, ui.helper, hitMode, res!==false); this._local._setDndStatus(otherNode, node, ui.helper, hitMode, res!==false && hitMode !== null); break; case "drop": hitMode = ui.helper.data("hitMode"); if(hitMode && dnd.dragDrop){ ctx.hitMode = hitMode; dnd.dragDrop(node, ctx); } break; case "leave": // Cancel pending expand request node.scheduleAction("cancel"); ui.helper.data("enterResponse", null); ui.helper.data("hitMode", null); this._local._setDndStatus(otherNode, node, ui.helper, "out", undefined); if(dnd.dragLeave){ dnd.dragLeave(node, ctx); } break; case "stop": $nodeTag.removeClass("fancytree-drag-source"); if(dnd.dragStop){ dnd.dragStop(node, ctx); } break; default: $.error("Unsupported drag event: " + eventName); } return res; }, _cancelDrag: function() { var dd = $.ui.ddmanager.current; if(dd){ dd.cancel(); } } }); }(jQuery, window, document)); /*! * jquery.fancytree.edit.js * * Make node titles editable. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/) * * Copyright (c) 2014, Martin Wendt (http://wwWendt.de) * * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.7.0 * @date 2014-12-21T15:57 */ ;(function($, window, document, undefined) { "use strict"; /******************************************************************************* * Private functions and variables */ var isMac = /Mac/.test(navigator.platform), escapeHtml = $.ui.fancytree.escapeHtml, unescapeHtml = $.ui.fancytree.unescapeHtml; /** * [ext-edit] Start inline editing of current node title. * * @alias FancytreeNode#editStart * @requires Fancytree */ $.ui.fancytree._FancytreeNodeClass.prototype.editStart = function(){ var $input, node = this, tree = this.tree, local = tree.ext.edit, instOpts = tree.options.edit, $title = $(".fancytree-title", node.span), eventData = { node: node, tree: tree, options: tree.options, isNew: $(node.span).hasClass("fancytree-edit-new"), orgTitle: node.title, input: null, dirty: false }; // beforeEdit may want to modify the title before editing if( instOpts.beforeEdit.call(node, {type: "beforeEdit"}, eventData) === false ) { return false; } $.ui.fancytree.assert(!local.currentNode, "recursive edit"); local.currentNode = this; local.eventData = eventData; // Disable standard Fancytree mouse- and key handling tree.widget._unbind(); // #116: ext-dnd prevents the blur event, so we have to catch outer clicks $(document).on("mousedown.fancytree-edit", function(event){ if( ! $(event.target).hasClass("fancytree-edit-input") ){ node.editEnd(true, event); } }); // Replace node with <input> $input = $("<input />", { "class": "fancytree-edit-input", type: "text", value: unescapeHtml(eventData.orgTitle) }); local.eventData.input = $input; if ( instOpts.adjustWidthOfs != null ) { $input.width($title.width() + instOpts.adjustWidthOfs); } if ( instOpts.inputCss != null ) { $input.css(instOpts.inputCss); } $title.html($input); // Focus <input> and bind keyboard handler $input .focus() .change(function(event){ $input.addClass("fancytree-edit-dirty"); }).keydown(function(event){ switch( event.which ) { case $.ui.keyCode.ESCAPE: node.editEnd(false, event); break; case $.ui.keyCode.ENTER: node.editEnd(true, event); return false; // so we don't start editmode on Mac } event.stopPropagation(); }).blur(function(event){ return node.editEnd(true, event); }); instOpts.edit.call(node, {type: "edit"}, eventData); }; /** * [ext-edit] Stop inline editing. * @param {Boolean} [applyChanges=false] false: cancel edit, true: save (if modified) * @alias FancytreeNode#editEnd * @requires jquery.fancytree.edit.js */ $.ui.fancytree._FancytreeNodeClass.prototype.editEnd = function(applyChanges, _event){ var newVal, node = this, tree = this.tree, local = tree.ext.edit, eventData = local.eventData, instOpts = tree.options.edit, $title = $(".fancytree-title", node.span), $input = $title.find("input.fancytree-edit-input"); // eventData.isNew = $(node.span).hasClass("fancytree-edit-new"); if( instOpts.trim ) { $input.val($.trim($input.val())); } newVal = $input.val(); // eventData.dirty = $input.hasClass("fancytree-edit-dirty") || ; eventData.dirty = ( newVal !== node.title ); // Find out, if saving is required if( applyChanges === false ) { // If true/false was passed, honor this (except in rename mode, if unchanged) eventData.save = false; } else if( eventData.isNew ) { // In create mode, we save everyting, except for empty text eventData.save = (newVal !== ""); } else { // In rename mode, we save everyting, except for empty or unchanged text eventData.save = eventData.dirty && (newVal !== ""); } // Allow to break (keep editor open), modify input, or re-define data.save if( instOpts.beforeClose.call(node, {type: "beforeClose"}, eventData) === false){ return false; } if( eventData.save && instOpts.save.call(node, {type: "save"}, eventData) === false){ return false; } $input .removeClass("fancytree-edit-dirty") .unbind(); // Unbind outer-click handler $(document).off(".fancytree-edit"); if( eventData.save ) { node.setTitle( escapeHtml(newVal) ); // $(node.span).removeClass("fancytree-edit-new"); node.setFocus(); }else{ if( eventData.isNew ) { node.remove(); node = eventData.node = null; local.relatedNode.setFocus(); } else { node.renderTitle(); node.setFocus(); } } local.eventData = null; local.currentNode = null; local.relatedNode = null; // Re-enable mouse and keyboard handling tree.widget._bind(); // Set keyboard focus, even if setFocus() claims 'nothing to do' $(tree.$container).focus(); eventData.input = null; instOpts.close.call(node, {type: "close"}, eventData); return true; }; /** * [ext-edit] Create a new child or sibling node and start edit mode. * * @param {String} [mode='child'] 'before', 'after', or 'child' * @param {Object} [init] NodeData (or simple title string) * @alias FancytreeNode#editCreateNode * @requires jquery.fancytree.edit.js */ $.ui.fancytree._FancytreeNodeClass.prototype.editCreateNode = function(mode, init){ var newNode, that = this; mode = mode || "child"; if( init == null ) { init = { title: "" }; } else if( typeof init === "string" ) { init = { title: init }; } else { $.ui.fancytree.assert($.isPlainObject(init)); } // Make sure node is expanded (and loaded) in 'child' mode if( mode === "child" && !this.isExpanded() && this.hasChildren() !== false ) { this.setExpanded().done(function(){ that.editCreateNode(mode, init); }); return; } newNode = this.addNode(init, mode); newNode.makeVisible(); $(newNode.span).addClass("fancytree-edit-new"); this.tree.ext.edit.relatedNode = this; newNode.editStart(); }; /** * [ext-edit] Check if any node in this tree in edit mode. * * @returns {FancytreeNode | null} * @alias Fancytree#isEditing * @requires jquery.fancytree.edit.js */ $.ui.fancytree._FancytreeClass.prototype.isEditing = function(){ return this.ext.edit.currentNode; }; /** * [ext-edit] Check if this node is in edit mode. * @returns {Boolean} true if node is currently beeing edited * @alias FancytreeNode#isEditing * @requires jquery.fancytree.edit.js */ $.ui.fancytree._FancytreeNodeClass.prototype.isEditing = function(){ return this.tree.ext.edit.currentNode === this; }; /******************************************************************************* * Extension code */ $.ui.fancytree.registerExtension({ name: "edit", version: "0.2.0", // Default options for this extension. options: { adjustWidthOfs: 4, // null: don't adjust input size to content allowEmpty: false, // Prevent empty input inputCss: {minWidth: "3em"}, triggerCancel: ["esc", "tab", "click"], // triggerStart: ["f2", "dblclick", "shift+click", "mac+enter"], triggerStart: ["f2", "shift+click", "mac+enter"], trim: true, // Trim whitespace before save // Events: beforeClose: $.noop, // Return false to prevent cancel/save (data.input is available) beforeEdit: $.noop, // Return false to prevent edit mode close: $.noop, // Editor was removed edit: $.noop, // Editor was opened (available as data.input) // keypress: $.noop, // Not yet implemented save: $.noop // Save data.input.val() or return false to keep editor open }, // Local attributes currentNode: null, treeInit: function(ctx){ this._super(ctx); this.$container.addClass("fancytree-ext-edit"); }, nodeClick: function(ctx) { if( $.inArray("shift+click", ctx.options.edit.triggerStart) >= 0 ){ if( ctx.originalEvent.shiftKey ){ ctx.node.editStart(); return false; } } return this._super(ctx); }, nodeDblclick: function(ctx) { if( $.inArray("dblclick", ctx.options.edit.triggerStart) >= 0 ){ ctx.node.editStart(); return false; } return this._super(ctx); }, nodeKeydown: function(ctx) { switch( ctx.originalEvent.which ) { case 113: // [F2] if( $.inArray("f2", ctx.options.edit.triggerStart) >= 0 ){ ctx.node.editStart(); return false; } break; case $.ui.keyCode.ENTER: if( $.inArray("mac+enter", ctx.options.edit.triggerStart) >= 0 && isMac ){ ctx.node.editStart(); return false; } break; } return this._super(ctx); } }); }(jQuery, window, document)); /*! * jquery.fancytree.filter.js * * Remove or highlight tree nodes, based on a filter. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/) * * Copyright (c) 2014, Martin Wendt (http://wwWendt.de) * * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.7.0 * @date 2014-12-21T15:57 */ ;(function($, window, document, undefined) { "use strict"; /******************************************************************************* * Private functions and variables */ function _escapeRegex(str){ /*jshint regexdash:true */ return (str + "").replace(/([.?*+\^\$\[\]\\(){}|-])/g, "\\$1"); } $.ui.fancytree._FancytreeClass.prototype._applyFilterImpl = function(filter, branchMode, leavesOnly){ var match, re, count = 0, hideMode = this.options.filter.mode === "hide"; // leavesOnly = !branchMode && this.options.filter.leavesOnly; leavesOnly = !!leavesOnly && !branchMode; // Default to 'match title substring (not case sensitive)' if(typeof filter === "string"){ match = _escapeRegex(filter); // make sure a '.' is treated literally re = new RegExp(".*" + match + ".*", "i"); filter = function(node){ return !!re.exec(node.title); }; } this.enableFilter = true; this.lastFilterArgs = arguments; this.$div.addClass("fancytree-ext-filter"); if( hideMode ){ this.$div.addClass("fancytree-ext-filter-hide"); } else { this.$div.addClass("fancytree-ext-filter-dimm"); } // Reset current filter this.visit(function(node){ delete node.match; delete node.subMatch; }); // Adjust node.hide, .match, .subMatch flags this.visit(function(node){ if ((!leavesOnly || node.children == null) && filter(node)) { count++; node.match = true; node.visitParents(function(p){ p.subMatch = true; }); if( branchMode ) { node.visit(function(p){ p.match = true; }); return "skip"; } } }); // Redraw this.render(); return count; }; /** * [ext-filter] Dimm or hide nodes. * * @param {function | string} filter * @param {boolean} [leavesOnly=false] * @returns {integer} count * @alias Fancytree#filterNodes * @requires jquery.fancytree.filter.js */ $.ui.fancytree._FancytreeClass.prototype.filterNodes = function(filter, leavesOnly){ return this._applyFilterImpl(filter, false, leavesOnly); }; /** * @deprecated */ $.ui.fancytree._FancytreeClass.prototype.applyFilter = function(filter){ this.warn("Fancytree.applyFilter() is deprecated since 2014-05-10. Use .filterNodes() instead."); return this.filterNodes.apply(this, arguments); }; /** * [ext-filter] Dimm or hide whole branches. * * @param {function | string} filter * @returns {integer} count * @alias Fancytree#filterBranches * @requires jquery.fancytree.filter.js */ $.ui.fancytree._FancytreeClass.prototype.filterBranches = function(filter){ return this._applyFilterImpl(filter, true, null); }; /** * [ext-filter] Reset the filter. * * @alias Fancytree#clearFilter * @requires jquery.fancytree.filter.js */ $.ui.fancytree._FancytreeClass.prototype.clearFilter = function(){ this.visit(function(node){ delete node.match; delete node.subMatch; }); this.enableFilter = false; this.lastFilterArgs = null; this.$div.removeClass("fancytree-ext-filter fancytree-ext-filter-dimm fancytree-ext-filter-hide"); this.render(); }; /******************************************************************************* * Extension code */ $.ui.fancytree.registerExtension({ name: "filter", version: "0.3.0", // Default options for this extension. options: { autoApply: true, // re-apply last filter if lazy data is loaded mode: "dimm" }, treeInit: function(ctx){ this._super(ctx); }, nodeLoadChildren: function(ctx, source) { return this._super(ctx, source).done(function() { if( ctx.tree.enableFilter && ctx.tree.lastFilterArgs && ctx.options.filter.autoApply ) { ctx.tree._applyFilterImpl.apply(ctx.tree, ctx.tree.lastFilterArgs); } }); }, nodeRenderStatus: function(ctx) { // Set classes for current status var res, node = ctx.node, tree = ctx.tree, $span = $(node[tree.statusClassPropName]); res = this._super(ctx); // nothing to do, if node was not yet rendered if( !$span.length || !tree.enableFilter ) { return res; } $span .toggleClass("fancytree-match", !!node.match) .toggleClass("fancytree-submatch", !!node.subMatch) .toggleClass("fancytree-hide", !(node.match || node.subMatch)); return res; } }); }(jQuery, window, document)); /*! * jquery.fancytree.glyph.js * * Use glyph fonts as instead of icon sprites. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/) * * Copyright (c) 2014, Martin Wendt (http://wwWendt.de) * * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.7.0 * @date 2014-12-21T15:57 */ ;(function($, window, document, undefined) { "use strict"; /* ***************************************************************************** * Private functions and variables */ function _getIcon(opts, type){ return opts.map[type]; } $.ui.fancytree.registerExtension({ name: "glyph", version: "0.2.0", // Default options for this extension. options: { map: { checkbox: "icon-check-empty", checkboxSelected: "icon-check", checkboxUnknown: "icon-check icon-muted", error: "icon-exclamation-sign", expanderClosed: "icon-caret-right", expanderLazy: "icon-angle-right", expanderOpen: "icon-caret-down", doc: "icon-file-alt", noExpander: "", // Default node icons. // (Use tree.options.iconClass(node) callback to define custom icons // based on node data) docOpen: "icon-file-alt", loading: "icon-refresh icon-spin", folder: "icon-folder-close-alt", folderOpen: "icon-folder-open-alt" } }, treeInit: function(ctx){ var tree = ctx.tree; this._super(ctx); tree.$container.addClass("fancytree-ext-glyph"); }, nodeRenderStatus: function(ctx) { var icon, span, node = ctx.node, $span = $(node.span), opts = ctx.options.glyph, // callback = opts.icon, map = opts.map // $span = $(node.span) ; this._super(ctx); if( node.isRoot() ){ return; } span = $span.children("span.fancytree-expander").get(0); if( span ){ if( node.isLoading() ){ icon = "loading"; }else if( node.expanded ){ icon = "expanderOpen"; }else if( node.isUndefined() ){ icon = "expanderLazy"; }else if( node.hasChildren() ){ icon = "expanderClosed"; }else{ icon = "noExpander"; } span.className = "fancytree-expander " + map[icon]; } if( node.tr ){ span = $("td", node.tr).children("span.fancytree-checkbox").get(0); }else{ span = $span.children("span.fancytree-checkbox").get(0); } if( span ){ icon = node.selected ? "checkboxSelected" : (node.partsel ? "checkboxUnknown" : "checkbox"); span.className = "fancytree-checkbox " + map[icon]; } // Icon (note that this does not match .fancytree-custom-icon, that might // be set by opts.iconClass) span = $span.children("span.fancytree-icon").get(0); if( span ){ if( node.folder ){ icon = node.expanded ? _getIcon(opts, "folderOpen") : _getIcon(opts, "folder"); }else{ icon = node.expanded ? _getIcon(opts, "docOpen") : _getIcon(opts, "doc"); } span.className = "fancytree-icon " + icon; } }, nodeSetStatus: function(ctx, status, message, details) { var span, opts = ctx.options.glyph, node = ctx.node; this._super(ctx, status, message, details); if(node.parent){ span = $("span.fancytree-expander", node.span).get(0); }else{ span = $(".fancytree-statusnode-wait, .fancytree-statusnode-error", node[this.nodeContainerAttrName]) .find("span.fancytree-expander").get(0); } if( status === "loading"){ // $("span.fancytree-expander", ctx.node.span).addClass(_getIcon(opts, "loading")); span.className = "fancytree-expander " + _getIcon(opts, "loading"); }else if( status === "error"){ span.className = "fancytree-expander " + _getIcon(opts, "error"); } } }); }(jQuery, window, document)); /*! * jquery.fancytree.gridnav.js * * Support keyboard navigation for trees with embedded input controls. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/) * * Copyright (c) 2014, Martin Wendt (http://wwWendt.de) * * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.7.0 * @date 2014-12-21T15:57 */ ;(function($, window, document, undefined) { "use strict"; /******************************************************************************* * Private functions and variables */ // Allow these navigation keys even when input controls are focused var KC = $.ui.keyCode, // which keys are *not* handled by embedded control, but passed to tree // navigation handler: NAV_KEYS = { "text": [KC.UP, KC.DOWN], "checkbox": [KC.UP, KC.DOWN, KC.LEFT, KC.RIGHT], "radiobutton": [KC.UP, KC.DOWN, KC.LEFT, KC.RIGHT], "select-one": [KC.LEFT, KC.RIGHT], "select-multiple": [KC.LEFT, KC.RIGHT] }; /* Calculate TD column index (considering colspans).*/ function getColIdx($tr, $td) { var colspan, td = $td.get(0), idx = 0; $tr.children().each(function () { if( this === td ) { return false; } colspan = $(this).prop("colspan"); idx += colspan ? colspan : 1; }); return idx; } /* Find TD at given column index (considering colspans).*/ function findTdAtColIdx($tr, colIdx) { var colspan, res = null, idx = 0; $tr.children().each(function () { if( idx >= colIdx ) { res = $(this); return false; } colspan = $(this).prop("colspan"); idx += colspan ? colspan : 1; }); return res; } /* Find adjacent cell for a given direction. Skip empty cells and consider merged cells */ function findNeighbourTd($target, keyCode){ var $tr, colIdx, $td = $target.closest("td"), $tdNext = null; switch( keyCode ){ case KC.LEFT: $tdNext = $td.prev(); break; case KC.RIGHT: $tdNext = $td.next(); break; case KC.UP: case KC.DOWN: $tr = $td.parent(); colIdx = getColIdx($tr, $td); while( true ) { $tr = (keyCode === KC.UP) ? $tr.prev() : $tr.next(); if( !$tr.length ) { break; } // Skip hidden rows if( $tr.is(":hidden") ) { continue; } // Find adjacent cell in the same column $tdNext = findTdAtColIdx($tr, colIdx); // Skip cells that don't conatain a focusable element if( $tdNext && $tdNext.find(":input").length ) { break; } } break; } return $tdNext; } /******************************************************************************* * Extension code */ $.ui.fancytree.registerExtension({ name: "gridnav", version: "0.0.1", // Default options for this extension. options: { autofocusInput: false, // Focus first embedded input if node gets activated handleCursorKeys: true // Allow UP/DOWN in inputs to move to prev/next node }, treeInit: function(ctx){ // gridnav requires the table extension to be loaded before itself this._requireExtension("table", true, true); this._super(ctx); this.$container.addClass("fancytree-ext-gridnav"); // Activate node if embedded input gets focus (due to a click) this.$container.on("focusin", function(event){ var ctx2, node = $.ui.fancytree.getNode(event.target); if( node && !node.isActive() ){ // Call node.setActive(), but also pass the event ctx2 = ctx.tree._makeHookContext(node, event); ctx.tree._callHook("nodeSetActive", ctx2, true); } }); }, nodeSetActive: function(ctx, flag) { var $outer, opts = ctx.options.gridnav, node = ctx.node, event = ctx.originalEvent || {}, triggeredByInput = $(event.target).is(":input"); flag = (flag !== false); this._super(ctx, flag); if( flag ){ if( ctx.options.titlesTabbable ){ if( !triggeredByInput ) { $(node.span).find("span.fancytree-title").focus(); node.setFocus(); } // If one node is tabbable, the container no longer needs to be ctx.tree.$container.attr("tabindex", "-1"); // ctx.tree.$container.removeAttr("tabindex"); } else if( opts.autofocusInput && !triggeredByInput ){ // Set focus to input sub input (if node was clicked, but not // when TAB was pressed ) $outer = $(node.tr || node.span); $outer.find(":input:enabled:first").focus(); } } }, nodeKeydown: function(ctx) { var inputType, handleKeys, $td, opts = ctx.options.gridnav, event = ctx.originalEvent, $target = $(event.target); // jQuery inputType = $target.is(":input:enabled") ? $target.prop("type") : null; // ctx.tree.debug("ext-gridnav nodeKeydown", event, inputType); if( inputType && opts.handleCursorKeys ){ handleKeys = NAV_KEYS[inputType]; if( handleKeys && $.inArray(event.which, handleKeys) >= 0 ){ $td = findNeighbourTd($target, event.which); // ctx.node.debug("ignore keydown in input", event.which, handleKeys); if( $td && $td.length ) { $td.find(":input:enabled").focus(); // Prevent Fancytree default navigation return false; } } return true; } ctx.tree.debug("ext-gridnav NOT HANDLED", event, inputType); return this._super(ctx); } }); }(jQuery, window, document)); /*! * jquery.fancytree.persist.js * * Persist tree status in cookiesRemove or highlight tree nodes, based on a filter. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/) * * @depends: jquery.cookie.js * * Copyright (c) 2014, Martin Wendt (http://wwWendt.de) * * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.7.0 * @date 2014-12-21T15:57 */ ;(function($, window, document, undefined) { "use strict"; /******************************************************************************* * Private functions and variables */ var _assert = $.ui.fancytree.assert, ACTIVE = "active", EXPANDED = "expanded", FOCUS = "focus", SELECTED = "selected"; /* Recursively load lazy nodes * @param {string} mode 'load', 'expand', false */ function _loadLazyNodes(tree, local, keyList, mode, dfd) { var i, key, l, node, foundOne = false, deferredList = [], missingKeyList = []; keyList = keyList || []; dfd = dfd || $.Deferred(); for( i=0, l=keyList.length; i<l; i++ ) { key = keyList[i]; node = tree.getNodeByKey(key); if( node ) { if( mode && node.isUndefined() ) { foundOne = true; tree.debug("_loadLazyNodes: " + node + " is lazy: loading..."); if( mode === "expand" ) { deferredList.push(node.setExpanded()); } else { deferredList.push(node.load()); } } else { tree.debug("_loadLazyNodes: " + node + " already loaded."); node.setExpanded(); } } else { missingKeyList.push(key); tree.debug("_loadLazyNodes: " + node + " was not yet found."); } } $.when.apply($, deferredList).always(function(){ // All lazy-expands have finished if( foundOne && missingKeyList.length > 0 ) { // If we read new nodes from server, try to resolve yet-missing keys _loadLazyNodes(tree, local, missingKeyList, mode, dfd); } else { if( missingKeyList.length ) { tree.warn("_loadLazyNodes: could not load those keys: ", missingKeyList); for( i=0, l=missingKeyList.length; i<l; i++ ) { key = keyList[i]; local._appendKey(EXPANDED, keyList[i], false); } } dfd.resolve(); } }); return dfd; } /** * [ext-persist] Remove persistence cookies of the given type(s). * Called like * $("#tree").fancytree("getTree").clearCookies("active expanded focus selected"); * * @alias Fancytree#clearCookies * @requires jquery.fancytree.persist.js */ $.ui.fancytree._FancytreeClass.prototype.clearCookies = function(types){ var local = this.ext.persist, prefix = local.cookiePrefix; types = types || "active expanded focus selected"; if(types.indexOf(ACTIVE) >= 0){ local._data(prefix + ACTIVE, null); } if(types.indexOf(EXPANDED) >= 0){ local._data(prefix + EXPANDED, null); } if(types.indexOf(FOCUS) >= 0){ local._data(prefix + FOCUS, null); } if(types.indexOf(SELECTED) >= 0){ local._data(prefix + SELECTED, null); } }; /** * [ext-persist] Return persistence information from cookies * * Called like * $("#tree").fancytree("getTree").getPersistData(); * * @alias Fancytree#getPersistData * @requires jquery.fancytree.persist.js */ $.ui.fancytree._FancytreeClass.prototype.getPersistData = function(){ var local = this.ext.persist, prefix = local.cookiePrefix, delim = local.cookieDelimiter, res = {}; res[ACTIVE] = local._data(prefix + ACTIVE); res[EXPANDED] = (local._data(prefix + EXPANDED) || "").split(delim); res[SELECTED] = (local._data(prefix + SELECTED) || "").split(delim); res[FOCUS] = local._data(prefix + FOCUS); return res; }; /* ***************************************************************************** * Extension code */ $.ui.fancytree.registerExtension({ name: "persist", version: "0.3.0", // Default options for this extension. options: { cookieDelimiter: "~", cookiePrefix: undefined, // 'fancytree-<treeId>-' by default cookie: { raw: false, expires: "", path: "", domain: "", secure: false }, expandLazy: false, // true: recursively expand and load lazy nodes overrideSource: true, // true: cookie takes precedence over `source` data attributes. store: "auto", // 'cookie': force cookie, 'local': force localStore, 'session': force sessionStore types: "active expanded focus selected" }, /* Generic read/write string data to cookie, sessionStorage or localStorage. */ _data: function(key, value){ var ls = this._local.localStorage; // null, sessionStorage, or localStorage if( value === undefined ) { return ls ? ls.getItem(key) : $.cookie(key); } else if ( value === null ) { if( ls ) { ls.removeItem(key); } else { $.removeCookie(key); } } else { if( ls ) { ls.setItem(key, value); } else { $.cookie(key, value, this.options.persist.cookie); } } }, /* Append `key` to a cookie. */ _appendKey: function(type, key, flag){ key = "" + key; // #90 var local = this._local, instOpts = this.options.persist, delim = instOpts.cookieDelimiter, cookieName = local.cookiePrefix + type, data = local._data(cookieName), keyList = data ? data.split(delim) : [], idx = $.inArray(key, keyList); // Remove, even if we add a key, so the key is always the last entry if(idx >= 0){ keyList.splice(idx, 1); } // Append key to cookie if(flag){ keyList.push(key); } local._data(cookieName, keyList.join(delim)); }, treeInit: function(ctx){ var tree = ctx.tree, opts = ctx.options, local = this._local, instOpts = this.options.persist; // For 'auto' or 'cookie' mode, the cookie plugin must be available _assert(instOpts.store === "localStore" || $.cookie, "Missing required plugin for 'persist' extension: jquery.cookie.js"); local.cookiePrefix = instOpts.cookiePrefix || ("fancytree-" + tree._id + "-"); local.storeActive = instOpts.types.indexOf(ACTIVE) >= 0; local.storeExpanded = instOpts.types.indexOf(EXPANDED) >= 0; local.storeSelected = instOpts.types.indexOf(SELECTED) >= 0; local.storeFocus = instOpts.types.indexOf(FOCUS) >= 0; if( instOpts.store === "cookie" || !window.localStorage ) { local.localStorage = null; } else { local.localStorage = (instOpts.store === "local") ? window.localStorage : window.sessionStorage; } // Bind init-handler to apply cookie state tree.$div.bind("fancytreeinit", function(event){ var cookie, dfd, i, keyList, node, prevFocus = $.cookie(local.cookiePrefix + FOCUS); // record this before node.setActive() overrides it; // tree.debug("document.cookie:", document.cookie); cookie = local._data(local.cookiePrefix + EXPANDED); keyList = cookie && cookie.split(instOpts.cookieDelimiter); if( local.storeExpanded ) { // Recursively load nested lazy nodes if expandLazy is 'expand' or 'load' // Also remove expand-cookies for unmatched nodes dfd = _loadLazyNodes(tree, local, keyList, instOpts.expandLazy ? "expand" : false , null); } else { // nothing to do dfd = new $.Deferred().resolve(); } dfd.done(function(){ if(local.storeSelected){ cookie = local._data(local.cookiePrefix + SELECTED); if(cookie){ keyList = cookie.split(instOpts.cookieDelimiter); for(i=0; i<keyList.length; i++){ node = tree.getNodeByKey(keyList[i]); if(node){ if(node.selected === undefined || instOpts.overrideSource && (node.selected === false)){ // node.setSelected(); node.selected = true; node.renderStatus(); } }else{ // node is no longer member of the tree: remove from cookie also local._appendKey(SELECTED, keyList[i], false); } } } // In selectMode 3 we have to fix the child nodes, since we // only stored the selected *top* nodes if( tree.options.selectMode === 3 ){ tree.visit(function(n){ if( n.selected ) { n.fixSelection3AfterClick(); return "skip"; } }); } } if(local.storeActive){ cookie = local._data(local.cookiePrefix + ACTIVE); if(cookie && (opts.persist.overrideSource || !tree.activeNode)){ node = tree.getNodeByKey(cookie); if(node){ node.setActive(); } } } if(local.storeFocus && prevFocus){ node = tree.getNodeByKey(prevFocus); if(node){ node.setFocus(); } } tree._triggerTreeEvent("restore", null, {}); }); }); // Init the tree return this._super(ctx); }, nodeSetActive: function(ctx, flag, opts) { var res, local = this._local; flag = (flag !== false); res = this._super(ctx, flag, opts); if(local.storeActive){ local._data(local.cookiePrefix + ACTIVE, this.activeNode ? this.activeNode.key : null); } return res; }, nodeSetExpanded: function(ctx, flag, opts) { var res, node = ctx.node, local = this._local; flag = (flag !== false); res = this._super(ctx, flag, opts); if(local.storeExpanded){ local._appendKey(EXPANDED, node.key, flag); } return res; }, nodeSetFocus: function(ctx, flag) { var res, local = this._local; flag = (flag !== false); res = this._super(ctx, flag); if(flag && local.storeFocus){ local._data(local.cookiePrefix + FOCUS, this.focusNode ? this.focusNode.key : null); } return res; }, nodeSetSelected: function(ctx, flag) { var res, selNodes, tree = ctx.tree, node = ctx.node, local = this._local; flag = (flag !== false); res = this._super(ctx, flag); if(local.storeSelected){ if( tree.options.selectMode === 3 ){ // In selectMode 3 we only store the the selected *top* nodes. // De-selecting a node may also de-select some parents, so we // calculate the current status again selNodes = $.map(tree.getSelectedNodes(true), function(n){ return n.key; }); selNodes = selNodes.join(ctx.options.persist.cookieDelimiter); local._data(local.cookiePrefix + SELECTED, selNodes); } else { local._appendKey(SELECTED, node.key, flag); } } return res; } }); }(jQuery, window, document)); /*! * jquery.fancytree.table.js * * Render tree as table (aka 'treegrid', 'tabletree'). * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/) * * Copyright (c) 2014, Martin Wendt (http://wwWendt.de) * * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.7.0 * @date 2014-12-21T15:57 */ ;(function($, window, document, undefined) { "use strict"; /* ***************************************************************************** * Private functions and variables */ function _assert(cond, msg){ msg = msg || ""; if(!cond){ $.error("Assertion failed " + msg); } } function insertSiblingAfter(referenceNode, newNode) { referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling); } /* Show/hide all rows that are structural descendants of `parent`. */ function setChildRowVisibility(parent, flag) { parent.visit(function(node){ var tr = node.tr; // currentFlag = node.hide ? false : flag; // fix for ext-filter if(tr){ tr.style.display = (node.hide || !flag) ? "none" : ""; } if(!node.expanded){ return "skip"; } }); } /* Find node that is rendered in previous row. */ function findPrevRowNode(node){ var i, last, prev, parent = node.parent, siblings = parent ? parent.children : null; if(siblings && siblings.length > 1 && siblings[0] !== node){ // use the lowest descendant of the preceeding sibling i = $.inArray(node, siblings); prev = siblings[i - 1]; _assert(prev.tr); // descend to lowest child (with a <tr> tag) while(prev.children){ last = prev.children[prev.children.length - 1]; if(!last.tr){ break; } prev = last; } }else{ // if there is no preceding sibling, use the direct parent prev = parent; } return prev; } $.ui.fancytree.registerExtension({ name: "table", version: "0.2.0", // Default options for this extension. options: { checkboxColumnIdx: null, // render the checkboxes into the this column index (default: nodeColumnIdx) customStatus: false, // true: generate renderColumns events for status nodes indentation: 16, // indent every node level by 16px nodeColumnIdx: 0 // render node expander, icon, and title to this column (default: #0) }, // Overide virtual methods for this extension. // `this` : is this extension object // `this._super`: the virtual function that was overriden (member of prev. extension or Fancytree) treeInit: function(ctx){ var i, $row, tdRole, tree = ctx.tree, $table = tree.widget.element; $table.addClass("fancytree-container fancytree-ext-table"); tree.tbody = $table.find("> tbody")[0]; tree.columnCount = $("thead >tr >th", $table).length; $(tree.tbody).empty(); tree.rowFragment = document.createDocumentFragment(); $row = $("<tr />"); tdRole = ""; if(ctx.options.aria){ $row.attr("role", "row"); tdRole = " role='gridcell'"; } for(i=0; i<tree.columnCount; i++) { if(ctx.options.table.nodeColumnIdx === i){ $row.append("<td" + tdRole + "><span class='fancytree-node' /></td>"); }else{ $row.append("<td" + tdRole + " />"); } } tree.rowFragment.appendChild($row.get(0)); // Make sure that status classes are set on the node's <tr> elements tree.statusClassPropName = "tr"; tree.ariaPropName = "tr"; this.nodeContainerAttrName = "tr"; this._super(ctx); // standard Fancytree created a root UL $(tree.rootNode.ul).remove(); tree.rootNode.ul = null; tree.$container = $table; // Add container to the TAB chain this.$container.attr("tabindex", this.options.tabbable ? "0" : "-1"); if(this.options.aria){ tree.$container .attr("role", "treegrid") .attr("aria-readonly", true); } }, /* Called by nodeRender to sync node order with tag order.*/ // nodeFixOrder: function(ctx) { // }, nodeRemoveChildMarkup: function(ctx) { var node = ctx.node; // node.debug("nodeRemoveChildMarkup()"); node.visit(function(n){ if(n.tr){ $(n.tr).remove(); n.tr = null; } }); }, nodeRemoveMarkup: function(ctx) { var node = ctx.node; // node.debug("nodeRemoveMarkup()"); if(node.tr){ $(node.tr).remove(); node.tr = null; } this.nodeRemoveChildMarkup(ctx); }, /* Override standard render. */ nodeRender: function(ctx, force, deep, collapsed, _recursive) { var children, firstTr, i, l, newRow, prevNode, prevTr, subCtx, tree = ctx.tree, node = ctx.node, opts = ctx.options, isRootNode = !node.parent; if( !_recursive ){ ctx.hasCollapsedParents = node.parent && !node.parent.expanded; } // $.ui.fancytree.debug("*** nodeRender " + node + ", isRoot=" + isRootNode, "tr=" + node.tr, "hcp=" + ctx.hasCollapsedParents, "parent.tr=" + (node.parent && node.parent.tr)); if( !isRootNode ){ if(!node.tr){ if( ctx.hasCollapsedParents /*&& !node.parent.tr*/ ) { // #166: we assume that the parent will be (recursively) rendered // later anyway. node.debug("nodeRender ignored due to unrendered parent"); return; } // Create new <tr> after previous row newRow = tree.rowFragment.firstChild.cloneNode(true); prevNode = findPrevRowNode(node); // $.ui.fancytree.debug("*** nodeRender " + node + ": prev: " + prevNode.key); _assert(prevNode); if(collapsed === true && _recursive){ // hide all child rows, so we can use an animation to show it later newRow.style.display = "none"; }else if(deep && ctx.hasCollapsedParents){ // also hide this row if deep === true but any parent is collapsed newRow.style.display = "none"; // newRow.style.color = "red"; } if(!prevNode.tr){ _assert(!prevNode.parent, "prev. row must have a tr, or is system root"); tree.tbody.appendChild(newRow); }else{ insertSiblingAfter(prevNode.tr, newRow); } node.tr = newRow; if( node.key && opts.generateIds ){ node.tr.id = opts.idPrefix + node.key; } node.tr.ftnode = node; if(opts.aria){ // TODO: why doesn't this work: // node.li.role = "treeitem"; $(node.tr).attr("aria-labelledby", "ftal_" + node.key); } node.span = $("span.fancytree-node", node.tr).get(0); // Set icon, link, and title (normally this is only required on initial render) this.nodeRenderTitle(ctx); // Allow tweaking, binding, after node was created for the first time // tree._triggerNodeEvent("createNode", ctx); if ( opts.createNode ){ opts.createNode.call(tree, {type: "createNode"}, ctx); } } else { if( force ) { // Set icon, link, and title (normally this is only required on initial render) this.nodeRenderTitle(ctx); // triggers renderColumns() } else { // Update element classes according to node state this.nodeRenderStatus(ctx); } } } // Allow tweaking after node state was rendered // tree._triggerNodeEvent("renderNode", ctx); if ( opts.renderNode ){ opts.renderNode.call(tree, {type: "renderNode"}, ctx); } // Visit child nodes // Add child markup children = node.children; if(children && (isRootNode || deep || node.expanded)){ for(i=0, l=children.length; i<l; i++) { subCtx = $.extend({}, ctx, {node: children[i]}); subCtx.hasCollapsedParents = subCtx.hasCollapsedParents || !node.expanded; this.nodeRender(subCtx, force, deep, collapsed, true); } } // Make sure, that <tr> order matches node.children order. if(children && !_recursive){ // we only have to do it once, for the root branch prevTr = node.tr || null; firstTr = tree.tbody.firstChild; // Iterate over all descendants node.visit(function(n){ if(n.tr){ if(!n.parent.expanded && n.tr.style.display !== "none"){ // fix after a node was dropped over a collapsed n.tr.style.display = "none"; setChildRowVisibility(n, false); } if(n.tr.previousSibling !== prevTr){ node.debug("_fixOrder: mismatch at node: " + n); var nextTr = prevTr ? prevTr.nextSibling : firstTr; tree.tbody.insertBefore(n.tr, nextTr); } prevTr = n.tr; } }); } // Update element classes according to node state // if(!isRootNode){ // this.nodeRenderStatus(ctx); // } }, nodeRenderTitle: function(ctx, title) { var $cb, node = ctx.node, opts = ctx.options; this._super(ctx); // Move checkbox to custom column if(opts.checkbox && opts.table.checkboxColumnIdx != null ){ $cb = $("span.fancytree-checkbox", node.span).detach(); $(node.tr).find("td:first").html($cb); } // Let user code write column content // ctx.tree._triggerNodeEvent("renderColumns", node); // Update element classes according to node state if( ! node.isRoot() ){ this.nodeRenderStatus(ctx); } if( !opts.table.customStatus && node.isStatusNode() ) { // default rendering for status node: leave other cells empty } else if ( opts.renderColumns ) { opts.renderColumns.call(ctx.tree, {type: "renderColumns"}, ctx); } }, nodeRenderStatus: function(ctx) { var indent, node = ctx.node, opts = ctx.options; this._super(ctx); $(node.tr).removeClass("fancytree-node"); // indent indent = (node.getLevel() - 1) * opts.table.indentation; $(node.span).css({marginLeft: indent + "px"}); }, /* Expand node, return Deferred.promise. */ nodeSetExpanded: function(ctx, flag, opts) { var dfd = new $.Deferred(), subOpts = $.extend({}, opts, {noEvents: true, noAnimation: true}); opts = opts || {}; function _afterExpand(ok) { flag = (flag !== false); setChildRowVisibility(ctx.node, flag); if( ok ) { if( flag && ctx.options.autoScroll && !opts.noAnimation && ctx.node.hasChildren() ) { // Scroll down to last child, but keep current node visible ctx.node.getLastChild().scrollIntoView(true, {topNode: ctx.node}).always(function(){ if( !opts.noEvents ) { ctx.tree._triggerNodeEvent(flag ? "expand" : "collapse", ctx); } dfd.resolveWith(ctx.node); }); } else { if( !opts.noEvents ) { ctx.tree._triggerNodeEvent(flag ? "expand" : "collapse", ctx); } dfd.resolveWith(ctx.node); } } else { if( !opts.noEvents ) { ctx.tree._triggerNodeEvent(flag ? "expand" : "collapse", ctx); } dfd.rejectWith(ctx.node); } } // Call base-expand with disabled events and animation this._super(ctx, flag, subOpts).done(function () { _afterExpand(true); }).fail(function () { _afterExpand(false); }); return dfd.promise(); }, nodeSetStatus: function(ctx, status, message, details) { if(status === "ok"){ var node = ctx.node, firstChild = ( node.children ? node.children[0] : null ); if ( firstChild && firstChild.isStatusNode() ) { $(firstChild.tr).remove(); } } this._super(ctx, status, message, details); }, treeClear: function(ctx) { this.nodeRemoveChildMarkup(this._makeHookContext(this.rootNode)); return this._super(ctx); } /*, treeSetFocus: function(ctx, flag) { // alert("treeSetFocus" + ctx.tree.$container); ctx.tree.$container.focus(); $.ui.fancytree.focusTree = ctx.tree; }*/ }); }(jQuery, window, document)); /*! * jquery.fancytree.themeroller.js * * Enable jQuery UI ThemeRoller styles. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/) * * @see http://jqueryui.com/themeroller/ * * Copyright (c) 2014, Martin Wendt (http://wwWendt.de) * * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.7.0 * @date 2014-12-21T15:57 */ ;(function($, window, document, undefined) { "use strict"; /******************************************************************************* * Extension code */ $.ui.fancytree.registerExtension({ name: "themeroller", version: "0.0.1", // Default options for this extension. options: { activeClass: "ui-state-active", foccusClass: "ui-state-focus", hoverClass: "ui-state-hover", selectedClass: "ui-state-highlight" }, treeInit: function(ctx){ this._super(ctx); var $el = ctx.widget.element; if($el[0].nodeName === "TABLE"){ $el.addClass("ui-widget ui-corner-all"); $el.find(">thead tr").addClass("ui-widget-header"); $el.find(">tbody").addClass("ui-widget-conent"); }else{ $el.addClass("ui-widget ui-widget-content ui-corner-all"); } $el.delegate(".fancytree-node", "mouseenter mouseleave", function(event){ var node = $.ui.fancytree.getNode(event.target), flag = (event.type === "mouseenter"); node.debug("hover: " + flag); $(node.span).toggleClass("ui-state-hover ui-corner-all", flag); }); }, treeDestroy: function(ctx){ this._super(ctx); ctx.widget.element.removeClass("ui-widget ui-widget-content ui-corner-all"); }, nodeRenderStatus: function(ctx){ var node = ctx.node, $el = $(node.span); this._super(ctx); /* .ui-state-highlight: Class to be applied to highlighted or selected elements. Applies "highlight" container styles to an element and its child text, links, and icons. .ui-state-error: Class to be applied to error messaging container elements. Applies "error" container styles to an element and its child text, links, and icons. .ui-state-error-text: An additional class that applies just the error text color without background. Can be used on form labels for instance. Also applies error icon color to child icons. .ui-state-default: Class to be applied to clickable button-like elements. Applies "clickable default" container styles to an element and its child text, links, and icons. .ui-state-hover: Class to be applied on mouseover to clickable button-like elements. Applies "clickable hover" container styles to an element and its child text, links, and icons. .ui-state-focus: Class to be applied on keyboard focus to clickable button-like elements. Applies "clickable hover" container styles to an element and its child text, links, and icons. .ui-state-active: Class to be applied on mousedown to clickable button-like elements. Applies "clickable active" container styles to an element and its child text, links, and icons. */ $el.toggleClass("ui-state-active", node.isActive()); $el.toggleClass("ui-state-focus", node.hasFocus()); $el.toggleClass("ui-state-highlight", node.isSelected()); // node.debug("ext-themeroller.nodeRenderStatus: ", node.span.className); } }); }(jQuery, window, document)); /*! * jquery.fancytree.wide.js * Support for 100% wide selection bars. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/) * * Copyright (c) 2014, Martin Wendt (http://wwWendt.de) * * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.7.0 * @date 2014-12-21T15:57 */ ;(function($, window, document, undefined) { "use strict"; var reNumUnit = /^([+-]?(?:\d+|\d*\.\d+))([a-z]*|%)$/; // split "1.5em" to ["1.5", "em"] /******************************************************************************* * Private functions and variables */ // var _assert = $.ui.fancytree.assert; /* Calculate inner width without scrollbar */ // function realInnerWidth($el) { // // http://blog.jquery.com/2012/08/16/jquery-1-8-box-sizing-width-csswidth-and-outerwidth/ // // inst.contWidth = parseFloat(this.$container.css("width"), 10); // // 'Client width without scrollbar' - 'padding' // return $el[0].clientWidth - ($el.innerWidth() - parseFloat($el.css("width"), 10)); // } /* Create a global embedded CSS style for the tree. */ function defineHeadStyleElement(id, cssText) { id = "fancytree-style-" + id; var $headStyle = $("#" + id); if( !cssText ) { $headStyle.remove(); return null; } if( !$headStyle.length ) { $headStyle = $("<style />") .attr("id", id) .addClass("fancytree-style") .prop("type", "text/css") .appendTo("head"); } try { $headStyle.html(cssText); } catch ( e ) { // fix for IE 6-8 $headStyle[0].styleSheet.cssText = cssText; } return $headStyle; } /* Calculate the CSS rules that indent title spans. */ function renderLevelCss(containerId, depth, levelOfs, lineOfs, measureUnit) { var i, prefix = "#" + containerId + " span.fancytree-level-", rules = []; for(i = 0; i < depth; i++) { rules.push(prefix + (i + 1) + " span.fancytree-title { padding-left: " + (i * levelOfs + lineOfs) + measureUnit + "; }"); } // Some UI animations wrap the UL inside a DIV and set position:relative on both. // This breaks the left:0 and padding-left:nn settings of the title rules.push("#" + containerId + " div.ui-effects-wrapper ul li span.fancytree-title " + "{ padding-left: 3px; position: static; width: auto; }"); return rules.join("\n"); } // /** // * [ext-wide] Recalculate the width of the selection bar after the tree container // * was resized.<br> // * May be called explicitly on container resize, since there is no resize event // * for DIV tags. // * // * @alias Fancytree#wideUpdate // * @requires jquery.fancytree.wide.js // */ // $.ui.fancytree._FancytreeClass.prototype.wideUpdate = function(){ // var inst = this.ext.wide, // prevCw = inst.contWidth, // prevLo = inst.lineOfs; // inst.contWidth = realInnerWidth(this.$container); // // Each title is precceeded by 2 or 3 icons (16px + 3 margin) // // + 1px title border and 3px title padding // // TODO: use code from treeInit() below // inst.lineOfs = (this.options.checkbox ? 3 : 2) * 19; // if( prevCw !== inst.contWidth || prevLo !== inst.lineOfs ) { // this.debug("wideUpdate: " + inst.contWidth); // this.visit(function(node){ // node.tree._callHook("nodeRenderTitle", node); // }); // } // }; /******************************************************************************* * Extension code */ $.ui.fancytree.registerExtension({ name: "wide", version: "0.0.3", // Default options for this extension. options: { iconWidth: null, // Adjust this if @fancy-icon-width != "16px" iconSpacing: null, // Adjust this if @fancy-icon-spacing != "3px" levelOfs: null // Adjust this if ul padding != "16px" }, treeCreate: function(ctx){ this._super(ctx); this.$container.addClass("fancytree-ext-wide"); var containerId, cssText, iconSpacingUnit, iconWidthUnit, levelOfsUnit, instOpts = ctx.options.wide, // css sniffing $dummyLI = $("<li id='fancytreeTemp'><span class='fancytree-node'><span class='fancytree-icon' /><span class='fancytree-title' /></span><ul />") .appendTo(ctx.tree.$container), $dummyIcon = $dummyLI.find(".fancytree-icon"), $dummyUL = $dummyLI.find("ul"), // $dummyTitle = $dummyLI.find(".fancytree-title"), iconSpacing = instOpts.iconSpacing || $dummyIcon.css("margin-left"), iconWidth = instOpts.iconWidth || $dummyIcon.css("width"), levelOfs = instOpts.levelOfs || $dummyUL.css("padding-left"); $dummyLI.remove(); iconSpacingUnit = iconSpacing.match(reNumUnit)[2]; iconSpacing = parseFloat(iconSpacing, 10); iconWidthUnit = iconWidth.match(reNumUnit)[2]; iconWidth = parseFloat(iconWidth, 10); levelOfsUnit = levelOfs.match(reNumUnit)[2]; if( iconSpacingUnit !== iconWidthUnit || levelOfsUnit !== iconWidthUnit ) { $.error("iconWidth, iconSpacing, and levelOfs must have the same css measure unit"); } this._local.measureUnit = iconWidthUnit; this._local.levelOfs = parseFloat(levelOfs); this._local.lineOfs = (ctx.options.checkbox ? 3 : 2) * (iconWidth + iconSpacing) + iconSpacing; this._local.maxDepth = 10; // Get/Set a unique Id on the container (if not already exists) containerId = this.$container.uniqueId().attr("id"); // Generated css rules for some levels (extended on demand) cssText = renderLevelCss(containerId, this._local.maxDepth, this._local.levelOfs, this._local.lineOfs, this._local.measureUnit); defineHeadStyleElement(containerId, cssText); }, treeDestroy: function(ctx){ // Remove generated css rules defineHeadStyleElement(this.$container.attr("id"), null); return this._super(ctx); }, nodeRenderStatus: function(ctx) { var containerId, cssText, res, node = ctx.node, level = node.getLevel(); res = this._super(ctx); // Generate some more level-n rules if required if( level > this._local.maxDepth ) { containerId = this.$container.attr("id"); this._local.maxDepth *= 2; node.debug("Define global ext-wide css up to level " + this._local.maxDepth); cssText = renderLevelCss(containerId, this._local.maxDepth, this._local.levelOfs, this._local.lineOfs, this._local.measureUnit); defineHeadStyleElement(containerId, cssText); } // Add level-n class to apply indentation padding. // (Setting element style would not work, since it cannot easily be // overriden while animations run) $(node.span).addClass("fancytree-level-" + level); return res; } }); }(jQuery, window, document));
examples/TopicsExample.js
ornl-sava/vis-react-components
import React from 'react' import { NavLink } from 'react-router-dom' import TopicsChart from '../src/premade/TopicsChart' import StoryViewerExample from './StoryViewerExample' // import {fakePrefixes, fakeData} from '../examples/data/for-hci/hciFakeData' // import {prefixes, topData, aList} from '../examples/data/for-hci/hciData' import { prefixes } from '../examples/data/for-hci/hciData' import topics from '../examples/data/topic-lane-sample/topics-sample_v01.json' import topics2 from './data/topic-lane-sample/topics-sample_v02.json' // import lanes from '../examples/data/topic-lane-sample/sets-sample.json' // console.log(topics) // console.log('TE-topics', topics.length) // console.log('TE-lanes', lanes.length) // const chartProps = { // tipFunction: toolTipFunction, // data: allData, // adjacencyList: aList, // colorDomain: prefixes, // numTData: nData // } class TopicsContainer extends React.Component { constructor (props) { super(props) this.state = { data: topics, initBins: topics2.data } this.chartProps = { // tipFunction: toolTipFunction, links: [], timeBins: [], colorDomain: prefixes, numTData: 5, onBarClick: this._onBarClick.bind(this) } this.timeBins = [] this.links = [] this.initStart = new Date(this.state.data[0]._source.bins[0].start) this.timeUnit = 1 * 1000 * 60 * 60 // this.refineData(this.chartProps) this.refineData2(this.chartProps) } _onBarClick (event, data) { console.log('GOTO', data) } refineData2 (props) { // console.log('rD-d', this.state.initBins) let timeBins = [] let topicMap = {} let links = [] // get time steps for (let i = 0; i < this.state.initBins.length - 1; i++) { if (this.state.initBins[i].start !== this.state.initBins[i + 1].start) { timeBins.push({ time: this.state.initBins[i].start, topics: [] }) } } // add last time step timeBins.push({ time: this.state.initBins[this.state.initBins.length - 1].end, topics: [] }) // sort in case out of order timeBins.sort((a, b) => { return a.time - b.time }) // console.log('timeBins', timeBins) this.state.initBins.map((data, index) => { let i = (new Date(data.start).getTime() - new Date(timeBins[0].time).getTime()) / this.timeUnit // console.log('i', i) data.events = data.common_events timeBins[i].topics.push(data) if (topicMap[data.topic] == null) { topicMap[data.topic] = [] } topicMap[data.topic].push(data) }) timeBins.map((da, ind) => { da.topics.map((data, index) => { // console.log('dMap', topicMap[data.topic], data.topic) let target = null data.story = topicMap[data.topic].filter((d, i) => { return d.start !== data.start }) topicMap[data.topic].map((d, i) => { if (data.end === d.start) { target = d // console.log('target', target) } }) if (target != null) { links.push({ source: data, target: target }) } }) }) // console.log('timeBinsAfter', timeBins, topicMap, links) props.timeBins = timeBins props.links = links } refineData (props) { this.story = [] let link = [] let story = [] let nodes = [] let timeBins = [] this.state.data.map((data, index) => { let bins = data._source.bins let tConnect = [] // console.log('TE-binLength', bins.length, '-numData', props.numTData) bins.map((d, i) => { // console.log('timeSTop', timeStop, '-dStart-', new Date(d.start).getTime()) if (index === 0) { timeBins.push({ startTime: d.start, topics: [] }) } // CHECKS NEXT TIME STEP FOR CONNECTION if (i < (bins.length - 1)) { let timeDiff = new Date(bins[i + 1].end) - new Date(d.end) if (timeDiff / 1000 / 60 / 60 === 1) { link.push({ source: nodes.length, target: nodes.length + 1 }) } } tConnect.push(nodes.length) story.push(tConnect) nodes.push(Object.assign({}, d, { topicID: data._id, events: data._source.common_events, story: [], fullStory: [] })) }) }) this.links = link.map((data, index) => { return { source: nodes[data.source], target: nodes[data.target] } }) // console.log('TE-props.links', this.links) // let topicSS = topics[0]._source // console.log('TE-nodes', nodes) nodes.map((data, index) => { let i = (new Date(data.start) - this.initStart) / this.timeUnit // let nStory = [] for (let j = 0; j < story[index].length; j++) { let d = story[index][j] if (d !== index) { data.story.push(nodes[d]) data.fullStory.push(nodes[d]) } } timeBins[i].topics.push(data) }) this.timeBins = timeBins // console.log('timeBins', this.timeBins) } getData (chartProps) { // CHECK TO SEE IF NUMBER OF TIMESTEPS EXCEEDS DATA if (chartProps.numTData > this.timeBins.length) { chartProps.numTData = this.timeBins.length } // REMOVES OUT OF RANGE BINS let timeStop = this.initStart.getTime() + (chartProps.numTData - 1) * this.timeUnit chartProps.timeBins = this.timeBins.filter((d, i) => { return i < chartProps.numTData }) // REMOVING THE STORY OF NODES THAT DO NOT FIT TIME STEP RANGE // MIGHT BE A BETTER WAY... chartProps.timeBins.map((d, i) => { d.topics.map((data, index) => { // console.log('tD', d) data.story = data.fullStory.filter((da) => { return new Date(da.start).getTime() <= timeStop }) }) }) console.log('chatime', chartProps.timeBins[0], '-', this.timeBins[0]) chartProps.links = this.links.filter((d, i) => { return (new Date(d.source.start).getTime() && new Date(d.target.start).getTime()) <= timeStop }) } render () { // this.getData(this.chartProps) return ( <div className={'col-md-12'}> <TopicsChart {...this.chartProps} /> <div className='row' > <StoryViewerExample colorDomain={prefixes} /> </div> <li><NavLink to='/id' activeClassName='active'>SingleTopic</NavLink></li> </div> ) } } // TopicsContainer.defaultProps = { // // } // // TopicsContainer.propTypes = { // tipFunction: PropTypes.function, // links: PropTypes.array, // timeBins: PropTypes.array, // colorDomain: PropTypes.array, // numTData: PropTypes.number // } export default TopicsContainer
app/components/DateRange/index.js
prudhvisays/newsb
import 'rc-calendar/assets/index.css'; import React from 'react'; import Calendar from 'rc-calendar'; import DatePicker from 'rc-calendar/lib/Picker'; import zhCN from 'rc-calendar/lib/locale/zh_CN'; import enUS from 'rc-calendar/lib/locale/en_US'; import RangeCalendar from 'rc-calendar/lib/RangeCalendar'; import moment from 'moment'; const formatStr = 'YYYY-MM-DD'; const cn = location.search.indexOf('cn') !== -1; const now = moment(); if (cn) { now.locale('zh-cn').utcOffset(8); } else { now.locale('en-gb').utcOffset(0); } const defaultCalendarValue = now.clone(); defaultCalendarValue.add(-1, 'month'); function newArray(start, end) { const result = []; for (let i = start; i < end; i++) { result.push(i); } return result; } function disabledDate(current) { const date = moment(); date.hour(0); date.minute(0); date.second(0); return current.isBefore(date); // can not select days before today } function format(v) { return v ? v.format(formatStr) : ''; } function isValidRange(v) { return v && v[0] && v[1]; } function onStandaloneChange(value) { console.log('onChange'); console.log(value[0] && format(value[0]), value[1] && format(value[1])); } function onStandaloneSelect(value) { console.log('onSelect'); console.log(format(value[0]), format(value[1])); } class DateRange extends React.Component { constructor(props) { super(props); this.state = { value: [], } this.onChange = this.onChange.bind(this); this.disabledDate = this.disabledDate.bind(this); } onChange(value) { this.setState({ value, }); if(this.props.merchantBlock) { this.props.merchantDateRange(value); this.props.getTeamCustomers() } else { this.props.pilotDateRange(value); } } disabledDate(current) { if (!current) { // allow empty select return false; } const date = moment(); date.hour(0); date.minute(0); date.second(0); return current.isBefore(date); // can not select days before today } value(value) { return isValidRange(value) && `${format(value[0])} ~ ${format(value[1])}` || '' } render() { const state = this.state; const { dateRangePilot, merchantBlock, dateRangeMerchant, Style } = this.props; const rangeValue = merchantBlock ? dateRangeMerchant : dateRangePilot; const calendar = ( <RangeCalendar showWeekNumber={false} dateInputPlaceholder={['start', 'end']} defaultValue={[now, now.clone().add(1, 'months')]} locale={cn ? zhCN : enUS} showClear={true} /> ); return ( <DatePicker value={rangeValue} onChange={this.onChange} animation="slide-up" calendar={calendar} style={{ zIndex: '99999999'}} > { ({ value }) => { return (<span> <input placeholder="Select Date" style={Style} disabled={state.disabled} readOnly className="ant-calendar-picker-input ant-input" value={this.value(value)} /> </span>); } } </DatePicker> ) } } export default DateRange;
react/features/mobile/external-api/functions.js
jitsi/jitsi-meet
// @flow import { NativeModules } from 'react-native'; import { getAppProp } from '../../base/app'; /** * Sends a specific event to the native counterpart of the External API. Native * apps may listen to such events via the mechanisms provided by the (native) * mobile Jitsi Meet SDK. * * @param {Object} store - The redux store. * @param {string} name - The name of the event to send. * @param {Object} data - The details/specifics of the event to send determined * by/associated with the specified {@code name}. * @returns {void} */ export function sendEvent(store: Object, name: string, data: Object) { // The JavaScript App needs to provide uniquely identifying information to // the native ExternalAPI module so that the latter may match the former to // the native view which hosts it. const externalAPIScope = getAppProp(store, 'externalAPIScope'); externalAPIScope && NativeModules.ExternalAPI.sendEvent(name, data, externalAPIScope); }
src/components/Accordion/Accordion-test.js
joshblack/carbon-components-react
/** * Copyright IBM Corp. 2016, 2018 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ import React from 'react'; import Accordion from '../Accordion'; import AccordionSkeleton from '../Accordion/Accordion.Skeleton'; import SkeletonText from '../SkeletonText'; import { shallow, mount } from 'enzyme'; describe('Accordion', () => { describe('Renders as expected', () => { const wrapper = shallow( <Accordion className="extra-class"> <div className="child">Test</div> </Accordion> ); it('renders children as expected', () => { expect(wrapper.find('.child').length).toBe(1); }); it('has the expected classes', () => { expect(wrapper.hasClass('bx--accordion')).toEqual(true); }); it('renders extra classes passed in via className', () => { expect(wrapper.hasClass('extra-class')).toEqual(true); }); }); }); describe('AccordionSkeleton', () => { describe('Renders as expected', () => { const wrapper = shallow(<AccordionSkeleton />); it('Has the expected classes', () => { expect(wrapper.hasClass('bx--skeleton')).toEqual(true); expect(wrapper.hasClass('bx--accordion')).toEqual(true); }); it('Renders first item as expected', () => { expect(wrapper.contains(<SkeletonText width="90%" />)).toEqual(true); }); it('Renders without opened item', () => { const noOpenedItem = shallow(<AccordionSkeleton open={false} />); expect(noOpenedItem.contains(<SkeletonText width="90%" />)).toEqual( false ); }); it('Renders number of items as expected', () => { const fullWrapper = mount(<AccordionSkeleton />); expect(fullWrapper.find('.bx--accordion__item')).toHaveLength(4); }); it('Renders custom number of items', () => { const fullWrapper = mount(<AccordionSkeleton count={8} />); expect(fullWrapper.find('.bx--accordion__item')).toHaveLength(8); }); }); });
ajax/libs/jquery/1.4.0/jquery.min.js
ZaValera/cdnjs
/*! * jQuery JavaScript Library v1.4 * http://jquery.com/ * * Copyright 2010, John Resig * Dual licensed under the MIT or GPL Version 2 licenses. * http://docs.jquery.com/License * * Includes Sizzle.js * http://sizzlejs.com/ * Copyright 2010, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * * Date: Wed Jan 13 15:23:05 2010 -0500 */ (function(A,w){function oa(){if(!c.isReady){try{s.documentElement.doScroll("left")}catch(a){setTimeout(oa,1);return}c.ready()}}function La(a,b){b.src?c.ajax({url:b.src,async:false,dataType:"script"}):c.globalEval(b.text||b.textContent||b.innerHTML||"");b.parentNode&&b.parentNode.removeChild(b)}function $(a,b,d,f,e,i){var j=a.length;if(typeof b==="object"){for(var o in b)$(a,o,b[o],f,e,d);return a}if(d!==w){f=!i&&f&&c.isFunction(d);for(o=0;o<j;o++)e(a[o],b,f?d.call(a[o],o,e(a[o],b)):d,i);return a}return j? e(a[0],b):null}function K(){return(new Date).getTime()}function aa(){return false}function ba(){return true}function pa(a,b,d){d[0].type=a;return c.event.handle.apply(b,d)}function qa(a){var b=true,d=[],f=[],e=arguments,i,j,o,p,n,t=c.extend({},c.data(this,"events").live);for(p in t){j=t[p];if(j.live===a.type||j.altLive&&c.inArray(a.type,j.altLive)>-1){i=j.data;i.beforeFilter&&i.beforeFilter[a.type]&&!i.beforeFilter[a.type](a)||f.push(j.selector)}else delete t[p]}i=c(a.target).closest(f,a.currentTarget); n=0;for(l=i.length;n<l;n++)for(p in t){j=t[p];o=i[n].elem;f=null;if(i[n].selector===j.selector){if(j.live==="mouseenter"||j.live==="mouseleave")f=c(a.relatedTarget).closest(j.selector)[0];if(!f||f!==o)d.push({elem:o,fn:j})}}n=0;for(l=d.length;n<l;n++){i=d[n];a.currentTarget=i.elem;a.data=i.fn.data;if(i.fn.apply(i.elem,e)===false){b=false;break}}return b}function ra(a,b){return["live",a,b.replace(/\./g,"`").replace(/ /g,"&")].join(".")}function sa(a){return!a||!a.parentNode||a.parentNode.nodeType=== 11}function ta(a,b){var d=0;b.each(function(){if(this.nodeName===(a[d]&&a[d].nodeName)){var f=c.data(a[d++]),e=c.data(this,f);if(f=f&&f.events){delete e.handle;e.events={};for(var i in f)for(var j in f[i])c.event.add(this,i,f[i][j],f[i][j].data)}}})}function ua(a,b,d){var f,e,i;if(a.length===1&&typeof a[0]==="string"&&a[0].length<512&&a[0].indexOf("<option")<0){e=true;if(i=c.fragments[a[0]])if(i!==1)f=i}if(!f){b=b&&b[0]?b[0].ownerDocument||b[0]:s;f=b.createDocumentFragment();c.clean(a,b,f,d)}if(e)c.fragments[a[0]]= i?f:1;return{fragment:f,cacheable:e}}function T(a){for(var b=0,d,f;(d=a[b])!=null;b++)if(!c.noData[d.nodeName.toLowerCase()]&&(f=d[H]))delete c.cache[f]}function L(a,b){var d={};c.each(va.concat.apply([],va.slice(0,b)),function(){d[this]=a});return d}function wa(a){return"scrollTo"in a&&a.document?a:a.nodeType===9?a.defaultView||a.parentWindow:false}var c=function(a,b){return new c.fn.init(a,b)},Ma=A.jQuery,Na=A.$,s=A.document,U,Oa=/^[^<]*(<[\w\W]+>)[^>]*$|^#([\w-]+)$/,Pa=/^.[^:#\[\.,]*$/,Qa=/\S/, Ra=/^(\s|\u00A0)+|(\s|\u00A0)+$/g,Sa=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,P=navigator.userAgent,xa=false,Q=[],M,ca=Object.prototype.toString,da=Object.prototype.hasOwnProperty,ea=Array.prototype.push,R=Array.prototype.slice,V=Array.prototype.indexOf;c.fn=c.prototype={init:function(a,b){var d,f;if(!a)return this;if(a.nodeType){this.context=this[0]=a;this.length=1;return this}if(typeof a==="string")if((d=Oa.exec(a))&&(d[1]||!b))if(d[1]){f=b?b.ownerDocument||b:s;if(a=Sa.exec(a))if(c.isPlainObject(b)){a=[s.createElement(a[1])]; c.fn.attr.call(a,b,true)}else a=[f.createElement(a[1])];else{a=ua([d[1]],[f]);a=(a.cacheable?a.fragment.cloneNode(true):a.fragment).childNodes}}else{if(b=s.getElementById(d[2])){if(b.id!==d[2])return U.find(a);this.length=1;this[0]=b}this.context=s;this.selector=a;return this}else if(!b&&/^\w+$/.test(a)){this.selector=a;this.context=s;a=s.getElementsByTagName(a)}else return!b||b.jquery?(b||U).find(a):c(b).find(a);else if(c.isFunction(a))return U.ready(a);if(a.selector!==w){this.selector=a.selector; this.context=a.context}return c.isArray(a)?this.setArray(a):c.makeArray(a,this)},selector:"",jquery:"1.4",length:0,size:function(){return this.length},toArray:function(){return R.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this.slice(a)[0]:this[a]},pushStack:function(a,b,d){a=c(a||null);a.prevObject=this;a.context=this.context;if(b==="find")a.selector=this.selector+(this.selector?" ":"")+d;else if(b)a.selector=this.selector+"."+b+"("+d+")";return a},setArray:function(a){this.length= 0;ea.apply(this,a);return this},each:function(a,b){return c.each(this,a,b)},ready:function(a){c.bindReady();if(c.isReady)a.call(s,c);else Q&&Q.push(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(R.apply(this,arguments),"slice",R.call(arguments).join(","))},map:function(a){return this.pushStack(c.map(this,function(b,d){return a.call(b,d,b)}))},end:function(){return this.prevObject|| c(null)},push:ea,sort:[].sort,splice:[].splice};c.fn.init.prototype=c.fn;c.extend=c.fn.extend=function(){var a=arguments[0]||{},b=1,d=arguments.length,f=false,e,i,j,o;if(typeof a==="boolean"){f=a;a=arguments[1]||{};b=2}if(typeof a!=="object"&&!c.isFunction(a))a={};if(d===b){a=this;--b}for(;b<d;b++)if((e=arguments[b])!=null)for(i in e){j=a[i];o=e[i];if(a!==o)if(f&&o&&(c.isPlainObject(o)||c.isArray(o))){j=j&&(c.isPlainObject(j)||c.isArray(j))?j:c.isArray(o)?[]:{};a[i]=c.extend(f,j,o)}else if(o!==w)a[i]= o}return a};c.extend({noConflict:function(a){A.$=Na;if(a)A.jQuery=Ma;return c},isReady:false,ready:function(){if(!c.isReady){if(!s.body)return setTimeout(c.ready,13);c.isReady=true;if(Q){for(var a,b=0;a=Q[b++];)a.call(s,c);Q=null}c.fn.triggerHandler&&c(s).triggerHandler("ready")}},bindReady:function(){if(!xa){xa=true;if(s.readyState==="complete")return c.ready();if(s.addEventListener){s.addEventListener("DOMContentLoaded",M,false);A.addEventListener("load",c.ready,false)}else if(s.attachEvent){s.attachEvent("onreadystatechange", M);A.attachEvent("onload",c.ready);var a=false;try{a=A.frameElement==null}catch(b){}s.documentElement.doScroll&&a&&oa()}}},isFunction:function(a){return ca.call(a)==="[object Function]"},isArray:function(a){return ca.call(a)==="[object Array]"},isPlainObject:function(a){if(!a||ca.call(a)!=="[object Object]"||a.nodeType||a.setInterval)return false;if(a.constructor&&!da.call(a,"constructor")&&!da.call(a.constructor.prototype,"isPrototypeOf"))return false;var b;for(b in a);return b===w||da.call(a,b)}, isEmptyObject:function(a){for(var b in a)return false;return true},noop:function(){},globalEval:function(a){if(a&&Qa.test(a)){var b=s.getElementsByTagName("head")[0]||s.documentElement,d=s.createElement("script");d.type="text/javascript";if(c.support.scriptEval)d.appendChild(s.createTextNode(a));else d.text=a;b.insertBefore(d,b.firstChild);b.removeChild(d)}},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,b,d){var f,e=0,i=a.length,j=i===w||c.isFunction(a); if(d)if(j)for(f in a){if(b.apply(a[f],d)===false)break}else for(;e<i;){if(b.apply(a[e++],d)===false)break}else if(j)for(f in a){if(b.call(a[f],f,a[f])===false)break}else for(d=a[0];e<i&&b.call(d,e,d)!==false;d=a[++e]);return a},trim:function(a){return(a||"").replace(Ra,"")},makeArray:function(a,b){b=b||[];if(a!=null)a.length==null||typeof a==="string"||c.isFunction(a)||typeof a!=="function"&&a.setInterval?ea.call(b,a):c.merge(b,a);return b},inArray:function(a,b){if(b.indexOf)return b.indexOf(a);for(var d= 0,f=b.length;d<f;d++)if(b[d]===a)return d;return-1},merge:function(a,b){var d=a.length,f=0;if(typeof b.length==="number")for(var e=b.length;f<e;f++)a[d++]=b[f];else for(;b[f]!==w;)a[d++]=b[f++];a.length=d;return a},grep:function(a,b,d){for(var f=[],e=0,i=a.length;e<i;e++)!d!==!b(a[e],e)&&f.push(a[e]);return f},map:function(a,b,d){for(var f=[],e,i=0,j=a.length;i<j;i++){e=b(a[i],i,d);if(e!=null)f[f.length]=e}return f.concat.apply([],f)},guid:1,proxy:function(a,b,d){if(arguments.length===2)if(typeof b=== "string"){d=a;a=d[b];b=w}else if(b&&!c.isFunction(b)){d=b;b=w}if(!b&&a)b=function(){return a.apply(d||this,arguments)};if(a)b.guid=a.guid=a.guid||b.guid||c.guid++;return b},uaMatch:function(a){var b={browser:""};a=a.toLowerCase();if(/webkit/.test(a))b={browser:"webkit",version:/webkit[\/ ]([\w.]+)/};else if(/opera/.test(a))b={browser:"opera",version:/version/.test(a)?/version[\/ ]([\w.]+)/:/opera[\/ ]([\w.]+)/};else if(/msie/.test(a))b={browser:"msie",version:/msie ([\w.]+)/};else if(/mozilla/.test(a)&& !/compatible/.test(a))b={browser:"mozilla",version:/rv:([\w.]+)/};b.version=(b.version&&b.version.exec(a)||[0,"0"])[1];return b},browser:{}});P=c.uaMatch(P);if(P.browser){c.browser[P.browser]=true;c.browser.version=P.version}if(c.browser.webkit)c.browser.safari=true;if(V)c.inArray=function(a,b){return V.call(b,a)};U=c(s);if(s.addEventListener)M=function(){s.removeEventListener("DOMContentLoaded",M,false);c.ready()};else if(s.attachEvent)M=function(){if(s.readyState==="complete"){s.detachEvent("onreadystatechange", M);c.ready()}};if(V)c.inArray=function(a,b){return V.call(b,a)};(function(){c.support={};var a=s.documentElement,b=s.createElement("script"),d=s.createElement("div"),f="script"+K();d.style.display="none";d.innerHTML=" <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>";var e=d.getElementsByTagName("*"),i=d.getElementsByTagName("a")[0];if(!(!e||!e.length||!i)){c.support={leadingWhitespace:d.firstChild.nodeType===3,tbody:!d.getElementsByTagName("tbody").length, htmlSerialize:!!d.getElementsByTagName("link").length,style:/red/.test(i.getAttribute("style")),hrefNormalized:i.getAttribute("href")==="/a",opacity:/^0.55$/.test(i.style.opacity),cssFloat:!!i.style.cssFloat,checkOn:d.getElementsByTagName("input")[0].value==="on",optSelected:s.createElement("select").appendChild(s.createElement("option")).selected,scriptEval:false,noCloneEvent:true,boxModel:null};b.type="text/javascript";try{b.appendChild(s.createTextNode("window."+f+"=1;"))}catch(j){}a.insertBefore(b, a.firstChild);if(A[f]){c.support.scriptEval=true;delete A[f]}a.removeChild(b);if(d.attachEvent&&d.fireEvent){d.attachEvent("onclick",function o(){c.support.noCloneEvent=false;d.detachEvent("onclick",o)});d.cloneNode(true).fireEvent("onclick")}c(function(){var o=s.createElement("div");o.style.width=o.style.paddingLeft="1px";s.body.appendChild(o);c.boxModel=c.support.boxModel=o.offsetWidth===2;s.body.removeChild(o).style.display="none"});a=function(o){var p=s.createElement("div");o="on"+o;var n=o in p;if(!n){p.setAttribute(o,"return;");n=typeof p[o]==="function"}return n};c.support.submitBubbles=a("submit");c.support.changeBubbles=a("change");a=b=d=e=i=null}})();c.props={"for":"htmlFor","class":"className",readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",colspan:"colSpan",tabindex:"tabIndex",usemap:"useMap",frameborder:"frameBorder"};var H="jQuery"+K(),Ta=0,ya={},Ua={};c.extend({cache:{},expando:H,noData:{embed:true,object:true,applet:true},data:function(a, b,d){if(!(a.nodeName&&c.noData[a.nodeName.toLowerCase()])){a=a==A?ya:a;var f=a[H],e=c.cache;if(!b&&!f)return null;f||(f=++Ta);if(typeof b==="object"){a[H]=f;e=e[f]=c.extend(true,{},b)}else e=e[f]?e[f]:typeof d==="undefined"?Ua:(e[f]={});if(d!==w){a[H]=f;e[b]=d}return typeof b==="string"?e[b]:e}},removeData:function(a,b){if(!(a.nodeName&&c.noData[a.nodeName.toLowerCase()])){a=a==A?ya:a;var d=a[H],f=c.cache,e=f[d];if(b){if(e){delete e[b];c.isEmptyObject(e)&&c.removeData(a)}}else{try{delete a[H]}catch(i){a.removeAttribute&& a.removeAttribute(H)}delete f[d]}}}});c.fn.extend({data:function(a,b){if(typeof a==="undefined"&&this.length)return c.data(this[0]);else if(typeof a==="object")return this.each(function(){c.data(this,a)});var d=a.split(".");d[1]=d[1]?"."+d[1]:"";if(b===w){var f=this.triggerHandler("getData"+d[1]+"!",[d[0]]);if(f===w&&this.length)f=c.data(this[0],a);return f===w&&d[1]?this.data(d[0]):f}else return this.trigger("setData"+d[1]+"!",[d[0],b]).each(function(){c.data(this,a,b)})},removeData:function(a){return this.each(function(){c.removeData(this, a)})}});c.extend({queue:function(a,b,d){if(a){b=(b||"fx")+"queue";var f=c.data(a,b);if(!d)return f||[];if(!f||c.isArray(d))f=c.data(a,b,c.makeArray(d));else f.push(d);return f}},dequeue:function(a,b){b=b||"fx";var d=c.queue(a,b),f=d.shift();if(f==="inprogress")f=d.shift();if(f){b==="fx"&&d.unshift("inprogress");f.call(a,function(){c.dequeue(a,b)})}}});c.fn.extend({queue:function(a,b){if(typeof a!=="string"){b=a;a="fx"}if(b===w)return c.queue(this[0],a);return this.each(function(){var d=c.queue(this, a,b);a==="fx"&&d[0]!=="inprogress"&&c.dequeue(this,a)})},dequeue:function(a){return this.each(function(){c.dequeue(this,a)})},delay:function(a,b){a=c.fx?c.fx.speeds[a]||a:a;b=b||"fx";return this.queue(b,function(){var d=this;setTimeout(function(){c.dequeue(d,b)},a)})},clearQueue:function(a){return this.queue(a||"fx",[])}});var za=/[\n\t]/g,fa=/\s+/,Va=/\r/g,Wa=/href|src|style/,Xa=/(button|input)/i,Ya=/(button|input|object|select|textarea)/i,Za=/^(a|area)$/i,Aa=/radio|checkbox/;c.fn.extend({attr:function(a, b){return $(this,a,b,true,c.attr)},removeAttr:function(a){return this.each(function(){c.attr(this,a,"");this.nodeType===1&&this.removeAttribute(a)})},addClass:function(a){if(c.isFunction(a))return this.each(function(p){var n=c(this);n.addClass(a.call(this,p,n.attr("class")))});if(a&&typeof a==="string")for(var b=(a||"").split(fa),d=0,f=this.length;d<f;d++){var e=this[d];if(e.nodeType===1)if(e.className)for(var i=" "+e.className+" ",j=0,o=b.length;j<o;j++){if(i.indexOf(" "+b[j]+" ")<0)e.className+= " "+b[j]}else e.className=a}return this},removeClass:function(a){if(c.isFunction(a))return this.each(function(p){var n=c(this);n.removeClass(a.call(this,p,n.attr("class")))});if(a&&typeof a==="string"||a===w)for(var b=(a||"").split(fa),d=0,f=this.length;d<f;d++){var e=this[d];if(e.nodeType===1&&e.className)if(a){for(var i=(" "+e.className+" ").replace(za," "),j=0,o=b.length;j<o;j++)i=i.replace(" "+b[j]+" "," ");e.className=i.substring(1,i.length-1)}else e.className=""}return this},toggleClass:function(a, b){var d=typeof a,f=typeof b==="boolean";if(c.isFunction(a))return this.each(function(e){var i=c(this);i.toggleClass(a.call(this,e,i.attr("class"),b),b)});return this.each(function(){if(d==="string")for(var e,i=0,j=c(this),o=b,p=a.split(fa);e=p[i++];){o=f?o:!j.hasClass(e);j[o?"addClass":"removeClass"](e)}else if(d==="undefined"||d==="boolean"){this.className&&c.data(this,"__className__",this.className);this.className=this.className||a===false?"":c.data(this,"__className__")||""}})},hasClass:function(a){a= " "+a+" ";for(var b=0,d=this.length;b<d;b++)if((" "+this[b].className+" ").replace(za," ").indexOf(a)>-1)return true;return false},val:function(a){if(a===w){var b=this[0];if(b){if(c.nodeName(b,"option"))return(b.attributes.value||{}).specified?b.value:b.text;if(c.nodeName(b,"select")){var d=b.selectedIndex,f=[],e=b.options;b=b.type==="select-one";if(d<0)return null;var i=b?d:0;for(d=b?d+1:e.length;i<d;i++){var j=e[i];if(j.selected){a=c(j).val();if(b)return a;f.push(a)}}return f}if(Aa.test(b.type)&& !c.support.checkOn)return b.getAttribute("value")===null?"on":b.value;return(b.value||"").replace(Va,"")}return w}var o=c.isFunction(a);return this.each(function(p){var n=c(this),t=a;if(this.nodeType===1){if(o)t=a.call(this,p,n.val());if(typeof t==="number")t+="";if(c.isArray(t)&&Aa.test(this.type))this.checked=c.inArray(n.val(),t)>=0;else if(c.nodeName(this,"select")){var z=c.makeArray(t);c("option",this).each(function(){this.selected=c.inArray(c(this).val(),z)>=0});if(!z.length)this.selectedIndex= -1}else this.value=t}})}});c.extend({attrFn:{val:true,css:true,html:true,text:true,data:true,width:true,height:true,offset:true},attr:function(a,b,d,f){if(!a||a.nodeType===3||a.nodeType===8)return w;if(f&&b in c.attrFn)return c(a)[b](d);f=a.nodeType!==1||!c.isXMLDoc(a);var e=d!==w;b=f&&c.props[b]||b;if(a.nodeType===1){var i=Wa.test(b);if(b in a&&f&&!i){if(e){if(b==="type"&&Xa.test(a.nodeName)&&a.parentNode)throw"type property can't be changed";a[b]=d}if(c.nodeName(a,"form")&&a.getAttributeNode(b))return a.getAttributeNode(b).nodeValue; if(b==="tabIndex")return(b=a.getAttributeNode("tabIndex"))&&b.specified?b.value:Ya.test(a.nodeName)||Za.test(a.nodeName)&&a.href?0:w;return a[b]}if(!c.support.style&&f&&b==="style"){if(e)a.style.cssText=""+d;return a.style.cssText}e&&a.setAttribute(b,""+d);a=!c.support.hrefNormalized&&f&&i?a.getAttribute(b,2):a.getAttribute(b);return a===null?w:a}return c.style(a,b,d)}});var $a=function(a){return a.replace(/[^\w\s\.\|`]/g,function(b){return"\\"+b})};c.event={add:function(a,b,d,f){if(!(a.nodeType=== 3||a.nodeType===8)){if(a.setInterval&&a!==A&&!a.frameElement)a=A;if(!d.guid)d.guid=c.guid++;if(f!==w){d=c.proxy(d);d.data=f}var e=c.data(a,"events")||c.data(a,"events",{}),i=c.data(a,"handle"),j;if(!i){j=function(){return typeof c!=="undefined"&&!c.event.triggered?c.event.handle.apply(j.elem,arguments):w};i=c.data(a,"handle",j)}if(i){i.elem=a;b=b.split(/\s+/);for(var o,p=0;o=b[p++];){var n=o.split(".");o=n.shift();d.type=n.slice(0).sort().join(".");var t=e[o],z=this.special[o]||{};if(!t){t=e[o]={}; if(!z.setup||z.setup.call(a,f,n,d)===false)if(a.addEventListener)a.addEventListener(o,i,false);else a.attachEvent&&a.attachEvent("on"+o,i)}if(z.add)if((n=z.add.call(a,d,f,n,t))&&c.isFunction(n)){n.guid=n.guid||d.guid;d=n}t[d.guid]=d;this.global[o]=true}a=null}}},global:{},remove:function(a,b,d){if(!(a.nodeType===3||a.nodeType===8)){var f=c.data(a,"events"),e,i,j;if(f){if(b===w||typeof b==="string"&&b.charAt(0)===".")for(i in f)this.remove(a,i+(b||""));else{if(b.type){d=b.handler;b=b.type}b=b.split(/\s+/); for(var o=0;i=b[o++];){var p=i.split(".");i=p.shift();var n=!p.length,t=c.map(p.slice(0).sort(),$a);t=new RegExp("(^|\\.)"+t.join("\\.(?:.*\\.)?")+"(\\.|$)");var z=this.special[i]||{};if(f[i]){if(d){j=f[i][d.guid];delete f[i][d.guid]}else for(var B in f[i])if(n||t.test(f[i][B].type))delete f[i][B];z.remove&&z.remove.call(a,p,j);for(e in f[i])break;if(!e){if(!z.teardown||z.teardown.call(a,p)===false)if(a.removeEventListener)a.removeEventListener(i,c.data(a,"handle"),false);else a.detachEvent&&a.detachEvent("on"+ i,c.data(a,"handle"));e=null;delete f[i]}}}}for(e in f)break;if(!e){if(B=c.data(a,"handle"))B.elem=null;c.removeData(a,"events");c.removeData(a,"handle")}}}},trigger:function(a,b,d,f){var e=a.type||a;if(!f){a=typeof a==="object"?a[H]?a:c.extend(c.Event(e),a):c.Event(e);if(e.indexOf("!")>=0){a.type=e=e.slice(0,-1);a.exclusive=true}if(!d){a.stopPropagation();this.global[e]&&c.each(c.cache,function(){this.events&&this.events[e]&&c.event.trigger(a,b,this.handle.elem)})}if(!d||d.nodeType===3||d.nodeType=== 8)return w;a.result=w;a.target=d;b=c.makeArray(b);b.unshift(a)}a.currentTarget=d;var i=c.data(d,"handle");i&&i.apply(d,b);var j,o;try{if(!(d&&d.nodeName&&c.noData[d.nodeName.toLowerCase()])){j=d[e];o=d["on"+e]}}catch(p){}i=c.nodeName(d,"a")&&e==="click";if(!f&&j&&!a.isDefaultPrevented()&&!i){this.triggered=true;try{d[e]()}catch(n){}}else if(o&&d["on"+e].apply(d,b)===false)a.result=false;this.triggered=false;if(!a.isPropagationStopped())(d=d.parentNode||d.ownerDocument)&&c.event.trigger(a,b,d,true)}, handle:function(a){var b,d;a=arguments[0]=c.event.fix(a||A.event);a.currentTarget=this;d=a.type.split(".");a.type=d.shift();b=!d.length&&!a.exclusive;var f=new RegExp("(^|\\.)"+d.slice(0).sort().join("\\.(?:.*\\.)?")+"(\\.|$)");d=(c.data(this,"events")||{})[a.type];for(var e in d){var i=d[e];if(b||f.test(i.type)){a.handler=i;a.data=i.data;i=i.apply(this,arguments);if(i!==w){a.result=i;if(i===false){a.preventDefault();a.stopPropagation()}}if(a.isImmediatePropagationStopped())break}}return a.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 originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),fix:function(a){if(a[H])return a;var b=a;a=c.Event(b);for(var d=this.props.length,f;d;){f=this.props[--d];a[f]=b[f]}if(!a.target)a.target=a.srcElement|| s;if(a.target.nodeType===3)a.target=a.target.parentNode;if(!a.relatedTarget&&a.fromElement)a.relatedTarget=a.fromElement===a.target?a.toElement:a.fromElement;if(a.pageX==null&&a.clientX!=null){b=s.documentElement;d=s.body;a.pageX=a.clientX+(b&&b.scrollLeft||d&&d.scrollLeft||0)-(b&&b.clientLeft||d&&d.clientLeft||0);a.pageY=a.clientY+(b&&b.scrollTop||d&&d.scrollTop||0)-(b&&b.clientTop||d&&d.clientTop||0)}if(!a.which&&(a.charCode||a.charCode===0?a.charCode:a.keyCode))a.which=a.charCode||a.keyCode;if(!a.metaKey&& a.ctrlKey)a.metaKey=a.ctrlKey;if(!a.which&&a.button!==w)a.which=a.button&1?1:a.button&2?3:a.button&4?2:0;return a},guid:1E8,proxy:c.proxy,special:{ready:{setup:c.bindReady,teardown:c.noop},live:{add:function(a,b){c.extend(a,b||{});a.guid+=b.selector+b.live;c.event.add(this,b.live,qa,b)},remove:function(a){if(a.length){var b=0,d=new RegExp("(^|\\.)"+a[0]+"(\\.|$)");c.each(c.data(this,"events").live||{},function(){d.test(this.type)&&b++});b<1&&c.event.remove(this,a[0],qa)}},special:{}},beforeunload:{setup:function(a, b,d){if(this.setInterval)this.onbeforeunload=d;return false},teardown:function(a,b){if(this.onbeforeunload===b)this.onbeforeunload=null}}}};c.Event=function(a){if(!this.preventDefault)return new c.Event(a);if(a&&a.type){this.originalEvent=a;this.type=a.type}else this.type=a;this.timeStamp=K();this[H]=true};c.Event.prototype={preventDefault:function(){this.isDefaultPrevented=ba;var a=this.originalEvent;if(a){a.preventDefault&&a.preventDefault();a.returnValue=false}},stopPropagation:function(){this.isPropagationStopped= ba;var a=this.originalEvent;if(a){a.stopPropagation&&a.stopPropagation();a.cancelBubble=true}},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=ba;this.stopPropagation()},isDefaultPrevented:aa,isPropagationStopped:aa,isImmediatePropagationStopped:aa};var Ba=function(a){for(var b=a.relatedTarget;b&&b!==this;)try{b=b.parentNode}catch(d){break}if(b!==this){a.type=a.data;c.event.handle.apply(this,arguments)}},Ca=function(a){a.type=a.data;c.event.handle.apply(this,arguments)};c.each({mouseenter:"mouseover", mouseleave:"mouseout"},function(a,b){c.event.special[a]={setup:function(d){c.event.add(this,b,d&&d.selector?Ca:Ba,a)},teardown:function(d){c.event.remove(this,b,d&&d.selector?Ca:Ba)}}});if(!c.support.submitBubbles)c.event.special.submit={setup:function(a,b,d){if(this.nodeName.toLowerCase()!=="form"){c.event.add(this,"click.specialSubmit."+d.guid,function(f){var e=f.target,i=e.type;if((i==="submit"||i==="image")&&c(e).closest("form").length)return pa("submit",this,arguments)});c.event.add(this,"keypress.specialSubmit."+ d.guid,function(f){var e=f.target,i=e.type;if((i==="text"||i==="password")&&c(e).closest("form").length&&f.keyCode===13)return pa("submit",this,arguments)})}else return false},remove:function(a,b){c.event.remove(this,"click.specialSubmit"+(b?"."+b.guid:""));c.event.remove(this,"keypress.specialSubmit"+(b?"."+b.guid:""))}};if(!c.support.changeBubbles){var ga=/textarea|input|select/i;function Da(a){var b=a.type,d=a.value;if(b==="radio"||b==="checkbox")d=a.checked;else if(b==="select-multiple")d=a.selectedIndex> -1?c.map(a.options,function(f){return f.selected}).join("-"):"";else if(a.nodeName.toLowerCase()==="select")d=a.selectedIndex;return d}function ha(a,b){var d=a.target,f,e;if(!(!ga.test(d.nodeName)||d.readOnly)){f=c.data(d,"_change_data");e=Da(d);if(e!==f){if(a.type!=="focusout"||d.type!=="radio")c.data(d,"_change_data",e);if(d.type!=="select"&&(f!=null||e)){a.type="change";return c.event.trigger(a,b,this)}}}}c.event.special.change={filters:{focusout:ha,click:function(a){var b=a.target,d=b.type;if(d=== "radio"||d==="checkbox"||b.nodeName.toLowerCase()==="select")return ha.call(this,a)},keydown:function(a){var b=a.target,d=b.type;if(a.keyCode===13&&b.nodeName.toLowerCase()!=="textarea"||a.keyCode===32&&(d==="checkbox"||d==="radio")||d==="select-multiple")return ha.call(this,a)},beforeactivate:function(a){a=a.target;a.nodeName.toLowerCase()==="input"&&a.type==="radio"&&c.data(a,"_change_data",Da(a))}},setup:function(a,b,d){for(var f in W)c.event.add(this,f+".specialChange."+d.guid,W[f]);return ga.test(this.nodeName)}, remove:function(a,b){for(var d in W)c.event.remove(this,d+".specialChange"+(b?"."+b.guid:""),W[d]);return ga.test(this.nodeName)}};var W=c.event.special.change.filters}s.addEventListener&&c.each({focus:"focusin",blur:"focusout"},function(a,b){function d(f){f=c.event.fix(f);f.type=b;return c.event.handle.call(this,f)}c.event.special[b]={setup:function(){this.addEventListener(a,d,true)},teardown:function(){this.removeEventListener(a,d,true)}}});c.each(["bind","one"],function(a,b){c.fn[b]=function(d, f,e){if(typeof d==="object"){for(var i in d)this[b](i,f,d[i],e);return this}if(c.isFunction(f)){thisObject=e;e=f;f=w}var j=b==="one"?c.proxy(e,function(o){c(this).unbind(o,j);return e.apply(this,arguments)}):e;return d==="unload"&&b!=="one"?this.one(d,f,e,thisObject):this.each(function(){c.event.add(this,d,j,f)})}});c.fn.extend({unbind:function(a,b){if(typeof a==="object"&&!a.preventDefault){for(var d in a)this.unbind(d,a[d]);return this}return this.each(function(){c.event.remove(this,a,b)})},trigger:function(a, b){return this.each(function(){c.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0]){a=c.Event(a);a.preventDefault();a.stopPropagation();c.event.trigger(a,b,this[0]);return a.result}},toggle:function(a){for(var b=arguments,d=1;d<b.length;)c.proxy(a,b[d++]);return this.click(c.proxy(a,function(f){var e=(c.data(this,"lastToggle"+a.guid)||0)%d;c.data(this,"lastToggle"+a.guid,e+1);f.preventDefault();return b[e].apply(this,arguments)||false}))},hover:function(a,b){return this.mouseenter(a).mouseleave(b|| a)},live:function(a,b,d){if(c.isFunction(b)){d=b;b=w}c(this.context).bind(ra(a,this.selector),{data:b,selector:this.selector,live:a},d);return this},die:function(a,b){c(this.context).unbind(ra(a,this.selector),b?{guid:b.guid+this.selector+a}:null);return this}});c.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){c.fn[b]=function(d){return d? this.bind(b,d):this.trigger(b)};if(c.attrFn)c.attrFn[b]=true});A.attachEvent&&!A.addEventListener&&A.attachEvent("onunload",function(){for(var a in c.cache)if(c.cache[a].handle)try{c.event.remove(c.cache[a].handle.elem)}catch(b){}});(function(){function a(g){for(var h="",k,m=0;g[m];m++){k=g[m];if(k.nodeType===3||k.nodeType===4)h+=k.nodeValue;else if(k.nodeType!==8)h+=a(k.childNodes)}return h}function b(g,h,k,m,r,q){r=0;for(var v=m.length;r<v;r++){var u=m[r];if(u){u=u[g];for(var y=false;u;){if(u.sizcache=== k){y=m[u.sizset];break}if(u.nodeType===1&&!q){u.sizcache=k;u.sizset=r}if(u.nodeName.toLowerCase()===h){y=u;break}u=u[g]}m[r]=y}}}function d(g,h,k,m,r,q){r=0;for(var v=m.length;r<v;r++){var u=m[r];if(u){u=u[g];for(var y=false;u;){if(u.sizcache===k){y=m[u.sizset];break}if(u.nodeType===1){if(!q){u.sizcache=k;u.sizset=r}if(typeof h!=="string"){if(u===h){y=true;break}}else if(p.filter(h,[u]).length>0){y=u;break}}u=u[g]}m[r]=y}}}var f=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, e=0,i=Object.prototype.toString,j=false,o=true;[0,0].sort(function(){o=false;return 0});var p=function(g,h,k,m){k=k||[];var r=h=h||s;if(h.nodeType!==1&&h.nodeType!==9)return[];if(!g||typeof g!=="string")return k;for(var q=[],v,u,y,S,I=true,N=x(h),J=g;(f.exec(""),v=f.exec(J))!==null;){J=v[3];q.push(v[1]);if(v[2]){S=v[3];break}}if(q.length>1&&t.exec(g))if(q.length===2&&n.relative[q[0]])u=ia(q[0]+q[1],h);else for(u=n.relative[q[0]]?[h]:p(q.shift(),h);q.length;){g=q.shift();if(n.relative[g])g+=q.shift(); u=ia(g,u)}else{if(!m&&q.length>1&&h.nodeType===9&&!N&&n.match.ID.test(q[0])&&!n.match.ID.test(q[q.length-1])){v=p.find(q.shift(),h,N);h=v.expr?p.filter(v.expr,v.set)[0]:v.set[0]}if(h){v=m?{expr:q.pop(),set:B(m)}:p.find(q.pop(),q.length===1&&(q[0]==="~"||q[0]==="+")&&h.parentNode?h.parentNode:h,N);u=v.expr?p.filter(v.expr,v.set):v.set;if(q.length>0)y=B(u);else I=false;for(;q.length;){var E=q.pop();v=E;if(n.relative[E])v=q.pop();else E="";if(v==null)v=h;n.relative[E](y,v,N)}}else y=[]}y||(y=u);if(!y)throw"Syntax error, unrecognized expression: "+ (E||g);if(i.call(y)==="[object Array]")if(I)if(h&&h.nodeType===1)for(g=0;y[g]!=null;g++){if(y[g]&&(y[g]===true||y[g].nodeType===1&&F(h,y[g])))k.push(u[g])}else for(g=0;y[g]!=null;g++)y[g]&&y[g].nodeType===1&&k.push(u[g]);else k.push.apply(k,y);else B(y,k);if(S){p(S,r,k,m);p.uniqueSort(k)}return k};p.uniqueSort=function(g){if(D){j=o;g.sort(D);if(j)for(var h=1;h<g.length;h++)g[h]===g[h-1]&&g.splice(h--,1)}return g};p.matches=function(g,h){return p(g,null,null,h)};p.find=function(g,h,k){var m,r;if(!g)return[]; for(var q=0,v=n.order.length;q<v;q++){var u=n.order[q];if(r=n.leftMatch[u].exec(g)){var y=r[1];r.splice(1,1);if(y.substr(y.length-1)!=="\\"){r[1]=(r[1]||"").replace(/\\/g,"");m=n.find[u](r,h,k);if(m!=null){g=g.replace(n.match[u],"");break}}}}m||(m=h.getElementsByTagName("*"));return{set:m,expr:g}};p.filter=function(g,h,k,m){for(var r=g,q=[],v=h,u,y,S=h&&h[0]&&x(h[0]);g&&h.length;){for(var I in n.filter)if((u=n.leftMatch[I].exec(g))!=null&&u[2]){var N=n.filter[I],J,E;E=u[1];y=false;u.splice(1,1);if(E.substr(E.length- 1)!=="\\"){if(v===q)q=[];if(n.preFilter[I])if(u=n.preFilter[I](u,v,k,q,m,S)){if(u===true)continue}else y=J=true;if(u)for(var X=0;(E=v[X])!=null;X++)if(E){J=N(E,u,X,v);var Ea=m^!!J;if(k&&J!=null)if(Ea)y=true;else v[X]=false;else if(Ea){q.push(E);y=true}}if(J!==w){k||(v=q);g=g.replace(n.match[I],"");if(!y)return[];break}}}if(g===r)if(y==null)throw"Syntax error, unrecognized expression: "+g;else break;r=g}return v};var n=p.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(g){return g.getAttribute("href")}}, relative:{"+":function(g,h){var k=typeof h==="string",m=k&&!/\W/.test(h);k=k&&!m;if(m)h=h.toLowerCase();m=0;for(var r=g.length,q;m<r;m++)if(q=g[m]){for(;(q=q.previousSibling)&&q.nodeType!==1;);g[m]=k||q&&q.nodeName.toLowerCase()===h?q||false:q===h}k&&p.filter(h,g,true)},">":function(g,h){var k=typeof h==="string";if(k&&!/\W/.test(h)){h=h.toLowerCase();for(var m=0,r=g.length;m<r;m++){var q=g[m];if(q){k=q.parentNode;g[m]=k.nodeName.toLowerCase()===h?k:false}}}else{m=0;for(r=g.length;m<r;m++)if(q=g[m])g[m]= k?q.parentNode:q.parentNode===h;k&&p.filter(h,g,true)}},"":function(g,h,k){var m=e++,r=d;if(typeof h==="string"&&!/\W/.test(h)){var q=h=h.toLowerCase();r=b}r("parentNode",h,m,g,q,k)},"~":function(g,h,k){var m=e++,r=d;if(typeof h==="string"&&!/\W/.test(h)){var q=h=h.toLowerCase();r=b}r("previousSibling",h,m,g,q,k)}},find:{ID:function(g,h,k){if(typeof h.getElementById!=="undefined"&&!k)return(g=h.getElementById(g[1]))?[g]:[]},NAME:function(g,h){if(typeof h.getElementsByName!=="undefined"){var k=[]; h=h.getElementsByName(g[1]);for(var m=0,r=h.length;m<r;m++)h[m].getAttribute("name")===g[1]&&k.push(h[m]);return k.length===0?null:k}},TAG:function(g,h){return h.getElementsByTagName(g[1])}},preFilter:{CLASS:function(g,h,k,m,r,q){g=" "+g[1].replace(/\\/g,"")+" ";if(q)return g;q=0;for(var v;(v=h[q])!=null;q++)if(v)if(r^(v.className&&(" "+v.className+" ").replace(/[\t\n]/g," ").indexOf(g)>=0))k||m.push(v);else if(k)h[q]=false;return false},ID:function(g){return g[1].replace(/\\/g,"")},TAG:function(g){return g[1].toLowerCase()}, CHILD:function(g){if(g[1]==="nth"){var h=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(g[2]==="even"&&"2n"||g[2]==="odd"&&"2n+1"||!/\D/.test(g[2])&&"0n+"+g[2]||g[2]);g[2]=h[1]+(h[2]||1)-0;g[3]=h[3]-0}g[0]=e++;return g},ATTR:function(g,h,k,m,r,q){h=g[1].replace(/\\/g,"");if(!q&&n.attrMap[h])g[1]=n.attrMap[h];if(g[2]==="~=")g[4]=" "+g[4]+" ";return g},PSEUDO:function(g,h,k,m,r){if(g[1]==="not")if((f.exec(g[3])||"").length>1||/^\w/.test(g[3]))g[3]=p(g[3],null,null,h);else{g=p.filter(g[3],h,k,true^r);k||m.push.apply(m, g);return false}else if(n.match.POS.test(g[0])||n.match.CHILD.test(g[0]))return true;return g},POS:function(g){g.unshift(true);return g}},filters:{enabled:function(g){return g.disabled===false&&g.type!=="hidden"},disabled:function(g){return g.disabled===true},checked:function(g){return g.checked===true},selected:function(g){return g.selected===true},parent:function(g){return!!g.firstChild},empty:function(g){return!g.firstChild},has:function(g,h,k){return!!p(k[3],g).length},header:function(g){return/h\d/i.test(g.nodeName)}, text:function(g){return"text"===g.type},radio:function(g){return"radio"===g.type},checkbox:function(g){return"checkbox"===g.type},file:function(g){return"file"===g.type},password:function(g){return"password"===g.type},submit:function(g){return"submit"===g.type},image:function(g){return"image"===g.type},reset:function(g){return"reset"===g.type},button:function(g){return"button"===g.type||g.nodeName.toLowerCase()==="button"},input:function(g){return/input|select|textarea|button/i.test(g.nodeName)}}, setFilters:{first:function(g,h){return h===0},last:function(g,h,k,m){return h===m.length-1},even:function(g,h){return h%2===0},odd:function(g,h){return h%2===1},lt:function(g,h,k){return h<k[3]-0},gt:function(g,h,k){return h>k[3]-0},nth:function(g,h,k){return k[3]-0===h},eq:function(g,h,k){return k[3]-0===h}},filter:{PSEUDO:function(g,h,k,m){var r=h[1],q=n.filters[r];if(q)return q(g,k,h,m);else if(r==="contains")return(g.textContent||g.innerText||a([g])||"").indexOf(h[3])>=0;else if(r==="not"){h= h[3];k=0;for(m=h.length;k<m;k++)if(h[k]===g)return false;return true}else throw"Syntax error, unrecognized expression: "+r;},CHILD:function(g,h){var k=h[1],m=g;switch(k){case "only":case "first":for(;m=m.previousSibling;)if(m.nodeType===1)return false;if(k==="first")return true;m=g;case "last":for(;m=m.nextSibling;)if(m.nodeType===1)return false;return true;case "nth":k=h[2];var r=h[3];if(k===1&&r===0)return true;h=h[0];var q=g.parentNode;if(q&&(q.sizcache!==h||!g.nodeIndex)){var v=0;for(m=q.firstChild;m;m= m.nextSibling)if(m.nodeType===1)m.nodeIndex=++v;q.sizcache=h}g=g.nodeIndex-r;return k===0?g===0:g%k===0&&g/k>=0}},ID:function(g,h){return g.nodeType===1&&g.getAttribute("id")===h},TAG:function(g,h){return h==="*"&&g.nodeType===1||g.nodeName.toLowerCase()===h},CLASS:function(g,h){return(" "+(g.className||g.getAttribute("class"))+" ").indexOf(h)>-1},ATTR:function(g,h){var k=h[1];g=n.attrHandle[k]?n.attrHandle[k](g):g[k]!=null?g[k]:g.getAttribute(k);k=g+"";var m=h[2];h=h[4];return g==null?m==="!=":m=== "="?k===h:m==="*="?k.indexOf(h)>=0:m==="~="?(" "+k+" ").indexOf(h)>=0:!h?k&&g!==false:m==="!="?k!==h:m==="^="?k.indexOf(h)===0:m==="$="?k.substr(k.length-h.length)===h:m==="|="?k===h||k.substr(0,h.length+1)===h+"-":false},POS:function(g,h,k,m){var r=n.setFilters[h[2]];if(r)return r(g,k,h,m)}}},t=n.match.POS;for(var z in n.match){n.match[z]=new RegExp(n.match[z].source+/(?![^\[]*\])(?![^\(]*\))/.source);n.leftMatch[z]=new RegExp(/(^(?:.|\r|\n)*?)/.source+n.match[z].source.replace(/\\(\d+)/g,function(g, h){return"\\"+(h-0+1)}))}var B=function(g,h){g=Array.prototype.slice.call(g,0);if(h){h.push.apply(h,g);return h}return g};try{Array.prototype.slice.call(s.documentElement.childNodes,0)}catch(C){B=function(g,h){h=h||[];if(i.call(g)==="[object Array]")Array.prototype.push.apply(h,g);else if(typeof g.length==="number")for(var k=0,m=g.length;k<m;k++)h.push(g[k]);else for(k=0;g[k];k++)h.push(g[k]);return h}}var D;if(s.documentElement.compareDocumentPosition)D=function(g,h){if(!g.compareDocumentPosition|| !h.compareDocumentPosition){if(g==h)j=true;return g.compareDocumentPosition?-1:1}g=g.compareDocumentPosition(h)&4?-1:g===h?0:1;if(g===0)j=true;return g};else if("sourceIndex"in s.documentElement)D=function(g,h){if(!g.sourceIndex||!h.sourceIndex){if(g==h)j=true;return g.sourceIndex?-1:1}g=g.sourceIndex-h.sourceIndex;if(g===0)j=true;return g};else if(s.createRange)D=function(g,h){if(!g.ownerDocument||!h.ownerDocument){if(g==h)j=true;return g.ownerDocument?-1:1}var k=g.ownerDocument.createRange(),m= h.ownerDocument.createRange();k.setStart(g,0);k.setEnd(g,0);m.setStart(h,0);m.setEnd(h,0);g=k.compareBoundaryPoints(Range.START_TO_END,m);if(g===0)j=true;return g};(function(){var g=s.createElement("div"),h="script"+(new Date).getTime();g.innerHTML="<a name='"+h+"'/>";var k=s.documentElement;k.insertBefore(g,k.firstChild);if(s.getElementById(h)){n.find.ID=function(m,r,q){if(typeof r.getElementById!=="undefined"&&!q)return(r=r.getElementById(m[1]))?r.id===m[1]||typeof r.getAttributeNode!=="undefined"&& r.getAttributeNode("id").nodeValue===m[1]?[r]:w:[]};n.filter.ID=function(m,r){var q=typeof m.getAttributeNode!=="undefined"&&m.getAttributeNode("id");return m.nodeType===1&&q&&q.nodeValue===r}}k.removeChild(g);k=g=null})();(function(){var g=s.createElement("div");g.appendChild(s.createComment(""));if(g.getElementsByTagName("*").length>0)n.find.TAG=function(h,k){k=k.getElementsByTagName(h[1]);if(h[1]==="*"){h=[];for(var m=0;k[m];m++)k[m].nodeType===1&&h.push(k[m]);k=h}return k};g.innerHTML="<a href='#'></a>"; if(g.firstChild&&typeof g.firstChild.getAttribute!=="undefined"&&g.firstChild.getAttribute("href")!=="#")n.attrHandle.href=function(h){return h.getAttribute("href",2)};g=null})();s.querySelectorAll&&function(){var g=p,h=s.createElement("div");h.innerHTML="<p class='TEST'></p>";if(!(h.querySelectorAll&&h.querySelectorAll(".TEST").length===0)){p=function(m,r,q,v){r=r||s;if(!v&&r.nodeType===9&&!x(r))try{return B(r.querySelectorAll(m),q)}catch(u){}return g(m,r,q,v)};for(var k in g)p[k]=g[k];h=null}}(); (function(){var g=s.createElement("div");g.innerHTML="<div class='test e'></div><div class='test'></div>";if(!(!g.getElementsByClassName||g.getElementsByClassName("e").length===0)){g.lastChild.className="e";if(g.getElementsByClassName("e").length!==1){n.order.splice(1,0,"CLASS");n.find.CLASS=function(h,k,m){if(typeof k.getElementsByClassName!=="undefined"&&!m)return k.getElementsByClassName(h[1])};g=null}}})();var F=s.compareDocumentPosition?function(g,h){return g.compareDocumentPosition(h)&16}:function(g, h){return g!==h&&(g.contains?g.contains(h):true)},x=function(g){return(g=(g?g.ownerDocument||g:0).documentElement)?g.nodeName!=="HTML":false},ia=function(g,h){var k=[],m="",r;for(h=h.nodeType?[h]:h;r=n.match.PSEUDO.exec(g);){m+=r[0];g=g.replace(n.match.PSEUDO,"")}g=n.relative[g]?g+"*":g;r=0;for(var q=h.length;r<q;r++)p(g,h[r],k);return p.filter(m,k)};c.find=p;c.expr=p.selectors;c.expr[":"]=c.expr.filters;c.unique=p.uniqueSort;c.getText=a;c.isXMLDoc=x;c.contains=F})();var ab=/Until$/,bb=/^(?:parents|prevUntil|prevAll)/, cb=/,/;R=Array.prototype.slice;var Fa=function(a,b,d){if(c.isFunction(b))return c.grep(a,function(e,i){return!!b.call(e,i,e)===d});else if(b.nodeType)return c.grep(a,function(e){return e===b===d});else if(typeof b==="string"){var f=c.grep(a,function(e){return e.nodeType===1});if(Pa.test(b))return c.filter(b,f,!d);else b=c.filter(b,a)}return c.grep(a,function(e){return c.inArray(e,b)>=0===d})};c.fn.extend({find:function(a){for(var b=this.pushStack("","find",a),d=0,f=0,e=this.length;f<e;f++){d=b.length; c.find(a,this[f],b);if(f>0)for(var i=d;i<b.length;i++)for(var j=0;j<d;j++)if(b[j]===b[i]){b.splice(i--,1);break}}return b},has:function(a){var b=c(a);return this.filter(function(){for(var d=0,f=b.length;d<f;d++)if(c.contains(this,b[d]))return true})},not:function(a){return this.pushStack(Fa(this,a,false),"not",a)},filter:function(a){return this.pushStack(Fa(this,a,true),"filter",a)},is:function(a){return!!a&&c.filter(a,this).length>0},closest:function(a,b){if(c.isArray(a)){var d=[],f=this[0],e,i= {},j;if(f&&a.length){e=0;for(var o=a.length;e<o;e++){j=a[e];i[j]||(i[j]=c.expr.match.POS.test(j)?c(j,b||this.context):j)}for(;f&&f.ownerDocument&&f!==b;){for(j in i){e=i[j];if(e.jquery?e.index(f)>-1:c(f).is(e)){d.push({selector:j,elem:f});delete i[j]}}f=f.parentNode}}return d}var p=c.expr.match.POS.test(a)?c(a,b||this.context):null;return this.map(function(n,t){for(;t&&t.ownerDocument&&t!==b;){if(p?p.index(t)>-1:c(t).is(a))return t;t=t.parentNode}return null})},index:function(a){if(!a||typeof a=== "string")return c.inArray(this[0],a?c(a):this.parent().children());return c.inArray(a.jquery?a[0]:a,this)},add:function(a,b){a=typeof a==="string"?c(a,b||this.context):c.makeArray(a);b=c.merge(this.get(),a);return this.pushStack(sa(a[0])||sa(b[0])?b:c.unique(b))},andSelf:function(){return this.add(this.prevObject)}});c.each({parent:function(a){return(a=a.parentNode)&&a.nodeType!==11?a:null},parents:function(a){return c.dir(a,"parentNode")},parentsUntil:function(a,b,d){return c.dir(a,"parentNode", d)},next:function(a){return c.nth(a,2,"nextSibling")},prev:function(a){return c.nth(a,2,"previousSibling")},nextAll:function(a){return c.dir(a,"nextSibling")},prevAll:function(a){return c.dir(a,"previousSibling")},nextUntil:function(a,b,d){return c.dir(a,"nextSibling",d)},prevUntil:function(a,b,d){return c.dir(a,"previousSibling",d)},siblings:function(a){return c.sibling(a.parentNode.firstChild,a)},children:function(a){return c.sibling(a.firstChild)},contents:function(a){return c.nodeName(a,"iframe")? a.contentDocument||a.contentWindow.document:c.makeArray(a.childNodes)}},function(a,b){c.fn[a]=function(d,f){var e=c.map(this,b,d);ab.test(a)||(f=d);if(f&&typeof f==="string")e=c.filter(f,e);e=this.length>1?c.unique(e):e;if((this.length>1||cb.test(f))&&bb.test(a))e=e.reverse();return this.pushStack(e,a,R.call(arguments).join(","))}});c.extend({filter:function(a,b,d){if(d)a=":not("+a+")";return c.find.matches(a,b)},dir:function(a,b,d){var f=[];for(a=a[b];a&&a.nodeType!==9&&(d===w||!c(a).is(d));){a.nodeType=== 1&&f.push(a);a=a[b]}return f},nth:function(a,b,d){b=b||1;for(var f=0;a;a=a[d])if(a.nodeType===1&&++f===b)break;return a},sibling:function(a,b){for(var d=[];a;a=a.nextSibling)a.nodeType===1&&a!==b&&d.push(a);return d}});var Ga=/ jQuery\d+="(?:\d+|null)"/g,Y=/^\s+/,db=/(<([\w:]+)[^>]*?)\/>/g,eb=/^(?:area|br|col|embed|hr|img|input|link|meta|param)$/i,Ha=/<([\w:]+)/,fb=/<tbody/i,gb=/<|&\w+;/,hb=function(a,b,d){return eb.test(d)?a:b+"></"+d+">"},G={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,"",""]};G.optgroup=G.option;G.tbody=G.tfoot=G.colgroup=G.caption=G.thead;G.th=G.td;if(!c.support.htmlSerialize)G._default=[1,"div<div>","</div>"];c.fn.extend({text:function(a){if(c.isFunction(a))return this.each(function(b){var d=c(this); return d.text(a.call(this,b,d.text()))});if(typeof a!=="object"&&a!==w)return this.empty().append((this[0]&&this[0].ownerDocument||s).createTextNode(a));return c.getText(this)},wrapAll:function(a){if(c.isFunction(a))return this.each(function(d){c(this).wrapAll(a.call(this,d))});if(this[0]){var b=c(a,this[0].ownerDocument).eq(0).clone(true);this[0].parentNode&&b.insertBefore(this[0]);b.map(function(){for(var d=this;d.firstChild&&d.firstChild.nodeType===1;)d=d.firstChild;return d}).append(this)}return this}, wrapInner:function(a){return this.each(function(){var b=c(this),d=b.contents();d.length?d.wrapAll(a):b.append(a)})},wrap:function(a){return this.each(function(){c(this).wrapAll(a)})},unwrap:function(){return this.parent().each(function(){c.nodeName(this,"body")||c(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&& this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b,this)});else if(arguments.length){var a=c(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,false,function(b){this.parentNode.insertBefore(b,this.nextSibling)});else if(arguments.length){var a=this.pushStack(this, "after",arguments);a.push.apply(a,c(arguments[0]).toArray());return a}},clone:function(a){var b=this.map(function(){if(!c.support.noCloneEvent&&!c.isXMLDoc(this)){var d=this.outerHTML,f=this.ownerDocument;if(!d){d=f.createElement("div");d.appendChild(this.cloneNode(true));d=d.innerHTML}return c.clean([d.replace(Ga,"").replace(Y,"")],f)[0]}else return this.cloneNode(true)});if(a===true){ta(this,b);ta(this.find("*"),b.find("*"))}return b},html:function(a){if(a===w)return this[0]&&this[0].nodeType=== 1?this[0].innerHTML.replace(Ga,""):null;else if(typeof a==="string"&&!/<script/i.test(a)&&(c.support.leadingWhitespace||!Y.test(a))&&!G[(Ha.exec(a)||["",""])[1].toLowerCase()])try{for(var b=0,d=this.length;b<d;b++)if(this[b].nodeType===1){T(this[b].getElementsByTagName("*"));this[b].innerHTML=a}}catch(f){this.empty().append(a)}else c.isFunction(a)?this.each(function(e){var i=c(this),j=i.html();i.empty().append(function(){return a.call(this,e,j)})}):this.empty().append(a);return this},replaceWith:function(a){if(this[0]&& this[0].parentNode){c.isFunction(a)||(a=c(a).detach());return this.each(function(){var b=this.nextSibling,d=this.parentNode;c(this).remove();b?c(b).before(a):c(d).append(a)})}else return this.pushStack(c(c.isFunction(a)?a():a),"replaceWith",a)},detach:function(a){return this.remove(a,true)},domManip:function(a,b,d){function f(t){return c.nodeName(t,"table")?t.getElementsByTagName("tbody")[0]||t.appendChild(t.ownerDocument.createElement("tbody")):t}var e,i,j=a[0],o=[];if(c.isFunction(j))return this.each(function(t){var z= c(this);a[0]=j.call(this,t,b?z.html():w);return z.domManip(a,b,d)});if(this[0]){e=a[0]&&a[0].parentNode&&a[0].parentNode.nodeType===11?{fragment:a[0].parentNode}:ua(a,this,o);if(i=e.fragment.firstChild){b=b&&c.nodeName(i,"tr");for(var p=0,n=this.length;p<n;p++)d.call(b?f(this[p],i):this[p],e.cacheable||this.length>1||p>0?e.fragment.cloneNode(true):e.fragment)}o&&c.each(o,La)}return this}});c.fragments={};c.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"}, function(a,b){c.fn[a]=function(d){var f=[];d=c(d);for(var e=0,i=d.length;e<i;e++){var j=(e>0?this.clone(true):this).get();c.fn[b].apply(c(d[e]),j);f=f.concat(j)}return this.pushStack(f,a,d.selector)}});c.each({remove:function(a,b){if(!a||c.filter(a,[this]).length){if(!b&&this.nodeType===1){T(this.getElementsByTagName("*"));T([this])}this.parentNode&&this.parentNode.removeChild(this)}},empty:function(){for(this.nodeType===1&&T(this.getElementsByTagName("*"));this.firstChild;)this.removeChild(this.firstChild)}}, function(a,b){c.fn[a]=function(){return this.each(b,arguments)}});c.extend({clean:function(a,b,d,f){b=b||s;if(typeof b.createElement==="undefined")b=b.ownerDocument||b[0]&&b[0].ownerDocument||s;var e=[];c.each(a,function(i,j){if(typeof j==="number")j+="";if(j){if(typeof j==="string"&&!gb.test(j))j=b.createTextNode(j);else if(typeof j==="string"){j=j.replace(db,hb);var o=(Ha.exec(j)||["",""])[1].toLowerCase(),p=G[o]||G._default,n=p[0];i=b.createElement("div");for(i.innerHTML=p[1]+j+p[2];n--;)i=i.lastChild; if(!c.support.tbody){n=fb.test(j);o=o==="table"&&!n?i.firstChild&&i.firstChild.childNodes:p[1]==="<table>"&&!n?i.childNodes:[];for(p=o.length-1;p>=0;--p)c.nodeName(o[p],"tbody")&&!o[p].childNodes.length&&o[p].parentNode.removeChild(o[p])}!c.support.leadingWhitespace&&Y.test(j)&&i.insertBefore(b.createTextNode(Y.exec(j)[0]),i.firstChild);j=c.makeArray(i.childNodes)}if(j.nodeType)e.push(j);else e=c.merge(e,j)}});if(d)for(a=0;e[a];a++)if(f&&c.nodeName(e[a],"script")&&(!e[a].type||e[a].type.toLowerCase()=== "text/javascript"))f.push(e[a].parentNode?e[a].parentNode.removeChild(e[a]):e[a]);else{e[a].nodeType===1&&e.splice.apply(e,[a+1,0].concat(c.makeArray(e[a].getElementsByTagName("script"))));d.appendChild(e[a])}return e}});var ib=/z-?index|font-?weight|opacity|zoom|line-?height/i,Ia=/alpha\([^)]*\)/,Ja=/opacity=([^)]*)/,ja=/float/i,ka=/-([a-z])/ig,jb=/([A-Z])/g,kb=/^-?\d+(?:px)?$/i,lb=/^-?\d/,mb={position:"absolute",visibility:"hidden",display:"block"},nb=["Left","Right"],ob=["Top","Bottom"],pb=s.defaultView&& s.defaultView.getComputedStyle,Ka=c.support.cssFloat?"cssFloat":"styleFloat",la=function(a,b){return b.toUpperCase()};c.fn.css=function(a,b){return $(this,a,b,true,function(d,f,e){if(e===w)return c.curCSS(d,f);if(typeof e==="number"&&!ib.test(f))e+="px";c.style(d,f,e)})};c.extend({style:function(a,b,d){if(!a||a.nodeType===3||a.nodeType===8)return w;if((b==="width"||b==="height")&&parseFloat(d)<0)d=w;var f=a.style||a,e=d!==w;if(!c.support.opacity&&b==="opacity"){if(e){f.zoom=1;b=parseInt(d,10)+""=== "NaN"?"":"alpha(opacity="+d*100+")";a=f.filter||c.curCSS(a,"filter")||"";f.filter=Ia.test(a)?a.replace(Ia,b):b}return f.filter&&f.filter.indexOf("opacity=")>=0?parseFloat(Ja.exec(f.filter)[1])/100+"":""}if(ja.test(b))b=Ka;b=b.replace(ka,la);if(e)f[b]=d;return f[b]},css:function(a,b,d,f){if(b==="width"||b==="height"){var e,i=b==="width"?nb:ob;function j(){e=b==="width"?a.offsetWidth:a.offsetHeight;f!=="border"&&c.each(i,function(){f||(e-=parseFloat(c.curCSS(a,"padding"+this,true))||0);if(f==="margin")e+= parseFloat(c.curCSS(a,"margin"+this,true))||0;else e-=parseFloat(c.curCSS(a,"border"+this+"Width",true))||0})}a.offsetWidth!==0?j():c.swap(a,mb,j);return Math.max(0,Math.round(e))}return c.curCSS(a,b,d)},curCSS:function(a,b,d){var f,e=a.style;if(!c.support.opacity&&b==="opacity"&&a.currentStyle){f=Ja.test(a.currentStyle.filter||"")?parseFloat(RegExp.$1)/100+"":"";return f===""?"1":f}if(ja.test(b))b=Ka;if(!d&&e&&e[b])f=e[b];else if(pb){if(ja.test(b))b="float";b=b.replace(jb,"-$1").toLowerCase();e= a.ownerDocument.defaultView;if(!e)return null;if(a=e.getComputedStyle(a,null))f=a.getPropertyValue(b);if(b==="opacity"&&f==="")f="1"}else if(a.currentStyle){d=b.replace(ka,la);f=a.currentStyle[b]||a.currentStyle[d];if(!kb.test(f)&&lb.test(f)){b=e.left;var i=a.runtimeStyle.left;a.runtimeStyle.left=a.currentStyle.left;e.left=d==="fontSize"?"1em":f||0;f=e.pixelLeft+"px";e.left=b;a.runtimeStyle.left=i}}return f},swap:function(a,b,d){var f={};for(var e in b){f[e]=a.style[e];a.style[e]=b[e]}d.call(a);for(e in b)a.style[e]= f[e]}});if(c.expr&&c.expr.filters){c.expr.filters.hidden=function(a){var b=a.offsetWidth,d=a.offsetHeight,f=a.nodeName.toLowerCase()==="tr";return b===0&&d===0&&!f?true:b>0&&d>0&&!f?false:c.curCSS(a,"display")==="none"};c.expr.filters.visible=function(a){return!c.expr.filters.hidden(a)}}var qb=K(),rb=/<script(.|\s)*?\/script>/gi,sb=/select|textarea/i,tb=/color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week/i,O=/=\?(&|$)/,ma=/\?/,ub=/(\?|&)_=.*?(&|$)/,vb=/^(\w+:)?\/\/([^\/?#]+)/, wb=/%20/g;c.fn.extend({_load:c.fn.load,load:function(a,b,d){if(typeof a!=="string")return this._load(a);else if(!this.length)return this;var f=a.indexOf(" ");if(f>=0){var e=a.slice(f,a.length);a=a.slice(0,f)}f="GET";if(b)if(c.isFunction(b)){d=b;b=null}else if(typeof b==="object"){b=c.param(b,c.ajaxSettings.traditional);f="POST"}c.ajax({url:a,type:f,dataType:"html",data:b,context:this,complete:function(i,j){if(j==="success"||j==="notmodified")this.html(e?c("<div />").append(i.responseText.replace(rb, "")).find(e):i.responseText);d&&this.each(d,[i.responseText,j,i])}});return this},serialize:function(){return c.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?c.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||sb.test(this.nodeName)||tb.test(this.type))}).map(function(a,b){a=c(this).val();return a==null?null:c.isArray(a)?c.map(a,function(d){return{name:b.name,value:d}}):{name:b.name,value:a}}).get()}}); c.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){c.fn[b]=function(d){return this.bind(b,d)}});c.extend({get:function(a,b,d,f){if(c.isFunction(b)){f=f||d;d=b;b=null}return c.ajax({type:"GET",url:a,data:b,success:d,dataType:f})},getScript:function(a,b){return c.get(a,null,b,"script")},getJSON:function(a,b,d){return c.get(a,b,d,"json")},post:function(a,b,d,f){if(c.isFunction(b)){f=f||d;d=b;b={}}return c.ajax({type:"POST",url:a,data:b,success:d,dataType:f})}, ajaxSetup:function(a){c.extend(c.ajaxSettings,a)},ajaxSettings:{url:location.href,global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:A.XMLHttpRequest&&(A.location.protocol!=="file:"||!A.ActiveXObject)?function(){return new A.XMLHttpRequest}:function(){try{return new A.ActiveXObject("Microsoft.XMLHTTP")}catch(a){}},accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript", text:"text/plain",_default:"*/*"}},lastModified:{},etag:{},ajax:function(a){function b(){e.success&&e.success.call(p,o,j,x);e.global&&f("ajaxSuccess",[x,e])}function d(){e.complete&&e.complete.call(p,x,j);e.global&&f("ajaxComplete",[x,e]);e.global&&!--c.active&&c.event.trigger("ajaxStop")}function f(r,q){(e.context?c(e.context):c.event).trigger(r,q)}var e=c.extend(true,{},c.ajaxSettings,a),i,j,o,p=e.context||e,n=e.type.toUpperCase();if(e.data&&e.processData&&typeof e.data!=="string")e.data=c.param(e.data, e.traditional);if(e.dataType==="jsonp"){if(n==="GET")O.test(e.url)||(e.url+=(ma.test(e.url)?"&":"?")+(e.jsonp||"callback")+"=?");else if(!e.data||!O.test(e.data))e.data=(e.data?e.data+"&":"")+(e.jsonp||"callback")+"=?";e.dataType="json"}if(e.dataType==="json"&&(e.data&&O.test(e.data)||O.test(e.url))){i=e.jsonpCallback||"jsonp"+qb++;if(e.data)e.data=(e.data+"").replace(O,"="+i+"$1");e.url=e.url.replace(O,"="+i+"$1");e.dataType="script";A[i]=A[i]||function(r){o=r;b();d();A[i]=w;try{delete A[i]}catch(q){}B&& B.removeChild(C)}}if(e.dataType==="script"&&e.cache===null)e.cache=false;if(e.cache===false&&n==="GET"){var t=K(),z=e.url.replace(ub,"$1_="+t+"$2");e.url=z+(z===e.url?(ma.test(e.url)?"&":"?")+"_="+t:"")}if(e.data&&n==="GET")e.url+=(ma.test(e.url)?"&":"?")+e.data;e.global&&!c.active++&&c.event.trigger("ajaxStart");t=(t=vb.exec(e.url))&&(t[1]&&t[1]!==location.protocol||t[2]!==location.host);if(e.dataType==="script"&&n==="GET"&&t){var B=s.getElementsByTagName("head")[0]||s.documentElement,C=s.createElement("script"); C.src=e.url;if(e.scriptCharset)C.charset=e.scriptCharset;if(!i){var D=false;C.onload=C.onreadystatechange=function(){if(!D&&(!this.readyState||this.readyState==="loaded"||this.readyState==="complete")){D=true;b();d();C.onload=C.onreadystatechange=null;B&&C.parentNode&&B.removeChild(C)}}}B.insertBefore(C,B.firstChild);return w}var F=false,x=e.xhr();if(x){e.username?x.open(n,e.url,e.async,e.username,e.password):x.open(n,e.url,e.async);try{if(e.data||a&&a.contentType)x.setRequestHeader("Content-Type", e.contentType);if(e.ifModified){c.lastModified[e.url]&&x.setRequestHeader("If-Modified-Since",c.lastModified[e.url]);c.etag[e.url]&&x.setRequestHeader("If-None-Match",c.etag[e.url])}t||x.setRequestHeader("X-Requested-With","XMLHttpRequest");x.setRequestHeader("Accept",e.dataType&&e.accepts[e.dataType]?e.accepts[e.dataType]+", */*":e.accepts._default)}catch(ia){}if(e.beforeSend&&e.beforeSend.call(p,x,e)===false){e.global&&!--c.active&&c.event.trigger("ajaxStop");x.abort();return false}e.global&&f("ajaxSend", [x,e]);var g=x.onreadystatechange=function(r){if(!x||x.readyState===0){F||d();F=true;if(x)x.onreadystatechange=c.noop}else if(!F&&x&&(x.readyState===4||r==="timeout")){F=true;x.onreadystatechange=c.noop;j=r==="timeout"?"timeout":!c.httpSuccess(x)?"error":e.ifModified&&c.httpNotModified(x,e.url)?"notmodified":"success";if(j==="success")try{o=c.httpData(x,e.dataType,e)}catch(q){j="parsererror"}if(j==="success"||j==="notmodified")i||b();else c.handleError(e,x,j);d();r==="timeout"&&x.abort();if(e.async)x= null}};try{var h=x.abort;x.abort=function(){if(x){h.call(x);if(x)x.readyState=0}g()}}catch(k){}e.async&&e.timeout>0&&setTimeout(function(){x&&!F&&g("timeout")},e.timeout);try{x.send(n==="POST"||n==="PUT"||n==="DELETE"?e.data:null)}catch(m){c.handleError(e,x,null,m);d()}e.async||g();return x}},handleError:function(a,b,d,f){if(a.error)a.error.call(a.context||A,b,d,f);if(a.global)(a.context?c(a.context):c.event).trigger("ajaxError",[b,a,f])},active:0,httpSuccess:function(a){try{return!a.status&&location.protocol=== "file:"||a.status>=200&&a.status<300||a.status===304||a.status===1223||a.status===0}catch(b){}return false},httpNotModified:function(a,b){var d=a.getResponseHeader("Last-Modified"),f=a.getResponseHeader("Etag");if(d)c.lastModified[b]=d;if(f)c.etag[b]=f;return a.status===304||a.status===0},httpData:function(a,b,d){var f=a.getResponseHeader("content-type")||"",e=b==="xml"||!b&&f.indexOf("xml")>=0;a=e?a.responseXML:a.responseText;if(e&&a.documentElement.nodeName==="parsererror")throw"parsererror";if(d&& d.dataFilter)a=d.dataFilter(a,b);if(typeof a==="string")if(b==="json"||!b&&f.indexOf("json")>=0)if(/^[\],:{}\s]*$/.test(a.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,"")))a=A.JSON&&A.JSON.parse?A.JSON.parse(a):(new Function("return "+a))();else throw"Invalid JSON: "+a;else if(b==="script"||!b&&f.indexOf("javascript")>=0)c.globalEval(a);return a},param:function(a,b){function d(e,i){i= c.isFunction(i)?i():i;f[f.length]=encodeURIComponent(e)+"="+encodeURIComponent(i)}var f=[];if(b===w)b=c.ajaxSettings.traditional;c.isArray(a)||a.jquery?c.each(a,function(){d(this.name,this.value)}):c.each(a,function e(i,j){if(c.isArray(j))c.each(j,function(o,p){b?d(i,p):e(i+"["+(typeof p==="object"||c.isArray(p)?o:"")+"]",p)});else!b&&j!=null&&typeof j==="object"?c.each(j,function(o,p){e(i+"["+o+"]",p)}):d(i,j)});return f.join("&").replace(wb,"+")}});var na={},xb=/toggle|show|hide/,yb=/^([+-]=)?([\d+-.]+)(.*)$/, Z,va=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];c.fn.extend({show:function(a,b){if(a!=null)return this.animate(L("show",3),a,b);else{a=0;for(b=this.length;a<b;a++){var d=c.data(this[a],"olddisplay");this[a].style.display=d||"";if(c.css(this[a],"display")==="none"){d=this[a].nodeName;var f;if(na[d])f=na[d];else{var e=c("<"+d+" />").appendTo("body");f=e.css("display");if(f==="none")f="block";e.remove(); na[d]=f}c.data(this[a],"olddisplay",f)}}a=0;for(b=this.length;a<b;a++)this[a].style.display=c.data(this[a],"olddisplay")||"";return this}},hide:function(a,b){if(a!=null)return this.animate(L("hide",3),a,b);else{a=0;for(b=this.length;a<b;a++){var d=c.data(this[a],"olddisplay");!d&&d!=="none"&&c.data(this[a],"olddisplay",c.css(this[a],"display"))}a=0;for(b=this.length;a<b;a++)this[a].style.display="none";return this}},_toggle:c.fn.toggle,toggle:function(a,b){var d=typeof a==="boolean";if(c.isFunction(a)&& c.isFunction(b))this._toggle.apply(this,arguments);else a==null||d?this.each(function(){var f=d?a:c(this).is(":hidden");c(this)[f?"show":"hide"]()}):this.animate(L("toggle",3),a,b);return this},fadeTo:function(a,b,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,d)},animate:function(a,b,d,f){var e=c.speed(b,d,f);if(c.isEmptyObject(a))return this.each(e.complete);return this[e.queue===false?"each":"queue"](function(){var i=c.extend({},e),j,o=this.nodeType===1&&c(this).is(":hidden"), p=this;for(j in a){var n=j.replace(ka,la);if(j!==n){a[n]=a[j];delete a[j];j=n}if(a[j]==="hide"&&o||a[j]==="show"&&!o)return i.complete.call(this);if((j==="height"||j==="width")&&this.style){i.display=c.css(this,"display");i.overflow=this.style.overflow}if(c.isArray(a[j])){(i.specialEasing=i.specialEasing||{})[j]=a[j][1];a[j]=a[j][0]}}if(i.overflow!=null)this.style.overflow="hidden";i.curAnim=c.extend({},a);c.each(a,function(t,z){var B=new c.fx(p,i,t);if(xb.test(z))B[z==="toggle"?o?"show":"hide":z](a); else{var C=yb.exec(z),D=B.cur(true)||0;if(C){z=parseFloat(C[2]);var F=C[3]||"px";if(F!=="px"){p.style[t]=(z||1)+F;D=(z||1)/B.cur(true)*D;p.style[t]=D+F}if(C[1])z=(C[1]==="-="?-1:1)*z+D;B.custom(D,z,F)}else B.custom(D,z,"")}});return true})},stop:function(a,b){var d=c.timers;a&&this.queue([]);this.each(function(){for(var f=d.length-1;f>=0;f--)if(d[f].elem===this){b&&d[f](true);d.splice(f,1)}});b||this.dequeue();return this}});c.each({slideDown:L("show",1),slideUp:L("hide",1),slideToggle:L("toggle", 1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}},function(a,b){c.fn[a]=function(d,f){return this.animate(b,d,f)}});c.extend({speed:function(a,b,d){var f=a&&typeof a==="object"?a:{complete:d||!d&&b||c.isFunction(a)&&a,duration:a,easing:d&&b||b&&!c.isFunction(b)&&b};f.duration=c.fx.off?0:typeof f.duration==="number"?f.duration:c.fx.speeds[f.duration]||c.fx.speeds._default;f.old=f.complete;f.complete=function(){f.queue!==false&&c(this).dequeue();c.isFunction(f.old)&&f.old.call(this)};return f},easing:{linear:function(a, b,d,f){return d+f*a},swing:function(a,b,d,f){return(-Math.cos(a*Math.PI)/2+0.5)*f+d}},timers:[],fx:function(a,b,d){this.options=b;this.elem=a;this.prop=d;if(!b.orig)b.orig={}}});c.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this);(c.fx.step[this.prop]||c.fx.step._default)(this);if((this.prop==="height"||this.prop==="width")&&this.elem.style)this.elem.style.display="block"},cur:function(a){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]== null))return this.elem[this.prop];return(a=parseFloat(c.css(this.elem,this.prop,a)))&&a>-10000?a:parseFloat(c.curCSS(this.elem,this.prop))||0},custom:function(a,b,d){function f(i){return e.step(i)}this.startTime=K();this.start=a;this.end=b;this.unit=d||this.unit||"px";this.now=this.start;this.pos=this.state=0;var e=this;f.elem=this.elem;if(f()&&c.timers.push(f)&&!Z)Z=setInterval(c.fx.tick,13)},show:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.show=true;this.custom(this.prop=== "width"||this.prop==="height"?1:0,this.cur());c(this.elem).show()},hide:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.hide=true;this.custom(this.cur(),0)},step:function(a){var b=K(),d=true;if(a||b>=this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;for(var f in this.options.curAnim)if(this.options.curAnim[f]!==true)d=false;if(d){if(this.options.display!=null){this.elem.style.overflow= this.options.overflow;a=c.data(this.elem,"olddisplay");this.elem.style.display=a?a:this.options.display;if(c.css(this.elem,"display")==="none")this.elem.style.display="block"}this.options.hide&&c(this.elem).hide();if(this.options.hide||this.options.show)for(var e in this.options.curAnim)c.style(this.elem,e,this.options.orig[e]);this.options.complete.call(this.elem)}return false}else{e=b-this.startTime;this.state=e/this.options.duration;a=this.options.easing||(c.easing.swing?"swing":"linear");this.pos= c.easing[this.options.specialEasing&&this.options.specialEasing[this.prop]||a](this.state,e,0,1,this.options.duration);this.now=this.start+(this.end-this.start)*this.pos;this.update()}return true}};c.extend(c.fx,{tick:function(){for(var a=c.timers,b=0;b<a.length;b++)a[b]()||a.splice(b--,1);a.length||c.fx.stop()},stop:function(){clearInterval(Z);Z=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){c.style(a.elem,"opacity",a.now)},_default:function(a){if(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;else a.elem[a.prop]=a.now}}});if(c.expr&&c.expr.filters)c.expr.filters.animated=function(a){return c.grep(c.timers,function(b){return a===b.elem}).length};c.fn.offset="getBoundingClientRect"in s.documentElement?function(a){var b=this[0];if(!b||!b.ownerDocument)return null;if(a)return this.each(function(e){c.offset.setOffset(this,a,e)});if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);var d=b.getBoundingClientRect(), f=b.ownerDocument;b=f.body;f=f.documentElement;return{top:d.top+(self.pageYOffset||c.support.boxModel&&f.scrollTop||b.scrollTop)-(f.clientTop||b.clientTop||0),left:d.left+(self.pageXOffset||c.support.boxModel&&f.scrollLeft||b.scrollLeft)-(f.clientLeft||b.clientLeft||0)}}:function(a){var b=this[0];if(!b||!b.ownerDocument)return null;if(a)return this.each(function(t){c.offset.setOffset(this,a,t)});if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);c.offset.initialize();var d=b.offsetParent,f= b,e=b.ownerDocument,i,j=e.documentElement,o=e.body;f=(e=e.defaultView)?e.getComputedStyle(b,null):b.currentStyle;for(var p=b.offsetTop,n=b.offsetLeft;(b=b.parentNode)&&b!==o&&b!==j;){if(c.offset.supportsFixedPosition&&f.position==="fixed")break;i=e?e.getComputedStyle(b,null):b.currentStyle;p-=b.scrollTop;n-=b.scrollLeft;if(b===d){p+=b.offsetTop;n+=b.offsetLeft;if(c.offset.doesNotAddBorder&&!(c.offset.doesAddBorderForTableAndCells&&/^t(able|d|h)$/i.test(b.nodeName))){p+=parseFloat(i.borderTopWidth)|| 0;n+=parseFloat(i.borderLeftWidth)||0}f=d;d=b.offsetParent}if(c.offset.subtractsBorderForOverflowNotVisible&&i.overflow!=="visible"){p+=parseFloat(i.borderTopWidth)||0;n+=parseFloat(i.borderLeftWidth)||0}f=i}if(f.position==="relative"||f.position==="static"){p+=o.offsetTop;n+=o.offsetLeft}if(c.offset.supportsFixedPosition&&f.position==="fixed"){p+=Math.max(j.scrollTop,o.scrollTop);n+=Math.max(j.scrollLeft,o.scrollLeft)}return{top:p,left:n}};c.offset={initialize:function(){var a=s.body,b=s.createElement("div"), d,f,e,i=parseFloat(c.curCSS(a,"marginTop",true))||0;c.extend(b.style,{position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"});b.innerHTML="<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>";a.insertBefore(b,a.firstChild); d=b.firstChild;f=d.firstChild;e=d.nextSibling.firstChild.firstChild;this.doesNotAddBorder=f.offsetTop!==5;this.doesAddBorderForTableAndCells=e.offsetTop===5;f.style.position="fixed";f.style.top="20px";this.supportsFixedPosition=f.offsetTop===20||f.offsetTop===15;f.style.position=f.style.top="";d.style.overflow="hidden";d.style.position="relative";this.subtractsBorderForOverflowNotVisible=f.offsetTop===-5;this.doesNotIncludeMarginInBodyOffset=a.offsetTop!==i;a.removeChild(b);c.offset.initialize=c.noop}, bodyOffset:function(a){var b=a.offsetTop,d=a.offsetLeft;c.offset.initialize();if(c.offset.doesNotIncludeMarginInBodyOffset){b+=parseFloat(c.curCSS(a,"marginTop",true))||0;d+=parseFloat(c.curCSS(a,"marginLeft",true))||0}return{top:b,left:d}},setOffset:function(a,b,d){if(/static/.test(c.curCSS(a,"position")))a.style.position="relative";var f=c(a),e=f.offset(),i=parseInt(c.curCSS(a,"top",true),10)||0,j=parseInt(c.curCSS(a,"left",true),10)||0;if(c.isFunction(b))b=b.call(a,d,e);d={top:b.top-e.top+i,left:b.left- e.left+j};"using"in b?b.using.call(a,d):f.css(d)}};c.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),d=this.offset(),f=/^body|html$/i.test(b[0].nodeName)?{top:0,left:0}:b.offset();d.top-=parseFloat(c.curCSS(a,"marginTop",true))||0;d.left-=parseFloat(c.curCSS(a,"marginLeft",true))||0;f.top+=parseFloat(c.curCSS(b[0],"borderTopWidth",true))||0;f.left+=parseFloat(c.curCSS(b[0],"borderLeftWidth",true))||0;return{top:d.top-f.top,left:d.left-f.left}},offsetParent:function(){return this.map(function(){for(var a= this.offsetParent||s.body;a&&!/^body|html$/i.test(a.nodeName)&&c.css(a,"position")==="static";)a=a.offsetParent;return a})}});c.each(["Left","Top"],function(a,b){var d="scroll"+b;c.fn[d]=function(f){var e=this[0],i;if(!e)return null;if(f!==w)return this.each(function(){if(i=wa(this))i.scrollTo(!a?f:c(i).scrollLeft(),a?f:c(i).scrollTop());else this[d]=f});else return(i=wa(e))?"pageXOffset"in i?i[a?"pageYOffset":"pageXOffset"]:c.support.boxModel&&i.document.documentElement[d]||i.document.body[d]:e[d]}}); c.each(["Height","Width"],function(a,b){var d=b.toLowerCase();c.fn["inner"+b]=function(){return this[0]?c.css(this[0],d,false,"padding"):null};c.fn["outer"+b]=function(f){return this[0]?c.css(this[0],d,false,f?"margin":"border"):null};c.fn[d]=function(f){var e=this[0];if(!e)return f==null?null:this;return"scrollTo"in e&&e.document?e.document.compatMode==="CSS1Compat"&&e.document.documentElement["client"+b]||e.document.body["client"+b]:e.nodeType===9?Math.max(e.documentElement["client"+b],e.body["scroll"+ b],e.documentElement["scroll"+b],e.body["offset"+b],e.documentElement["offset"+b]):f===w?c.css(e,d):this.css(d,typeof f==="string"?f:f+"px")}});A.jQuery=A.$=c})(window);
Examples/UIExplorer/UIExplorerApp.android.js
eliagrady/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. * * @providesModule UIExplorerApp * @flow */ 'use strict'; var React = require('react-native'); var { AppRegistry, BackAndroid, Dimensions, DrawerLayoutAndroid, StyleSheet, ToolbarAndroid, View, } = React; var UIExplorerList = require('./UIExplorerList.android'); var DRAWER_WIDTH_LEFT = 56; var UIExplorerApp = React.createClass({ getInitialState: function() { return { example: this._getUIExplorerHome(), }; }, _getUIExplorerHome: function() { return { title: 'UIExplorer', component: this._renderHome(), }; }, componentWillMount: function() { BackAndroid.addEventListener('hardwareBackPress', this._handleBackButtonPress); }, render: function() { return ( <DrawerLayoutAndroid drawerPosition={DrawerLayoutAndroid.positions.Left} drawerWidth={Dimensions.get('window').width - DRAWER_WIDTH_LEFT} keyboardDismissMode="on-drag" ref={(drawer) => { this.drawer = drawer; }} renderNavigationView={this._renderNavigationView}> {this._renderNavigation()} </DrawerLayoutAndroid> ); }, _renderNavigationView: function() { return ( <UIExplorerList onSelectExample={this.onSelectExample} isInDrawer={true} /> ); }, onSelectExample: function(example) { this.drawer.closeDrawer(); if (example.title === this._getUIExplorerHome().title) { example = this._getUIExplorerHome(); } this.setState({ example: example, }); }, _renderHome: function() { var onSelectExample = this.onSelectExample; return React.createClass({ render: function() { return ( <UIExplorerList onSelectExample={onSelectExample} isInDrawer={false} /> ); } }); }, _renderNavigation: function() { var Component = this.state.example.component; return ( <View style={styles.container}> <ToolbarAndroid logo={require('image!launcher_icon')} navIcon={require('image!ic_menu_black_24dp')} onIconClicked={() => this.drawer.openDrawer()} style={styles.toolbar} title={this.state.example.title} /> <Component /> </View> ); }, _handleBackButtonPress: function() { if (this.state.example.title !== this._getUIExplorerHome().title) { this.onSelectExample(this._getUIExplorerHome()); return true; } return false; }, }); var styles = StyleSheet.create({ container: { flex: 1, }, toolbar: { backgroundColor: '#E9EAED', height: 56, }, }); AppRegistry.registerComponent('UIExplorerApp', () => UIExplorerApp); module.exports = UIExplorerApp;
test/example2/node_modules/browserify/node_modules/insert-module-globals/node_modules/lexical-scope/node_modules/astw/node_modules/esprima-six/test/3rdparty/jquery-1.7.1.js
pepoviola/cartero
/*! * jQuery JavaScript Library v1.7.1 * 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: Mon Nov 21 21:11:03 2011 -0500 */ (function( window, undefined ) { // Use the correct document accordingly with window argument (sandbox) var document = window.document, navigator = window.navigator, location = window.location; var jQuery = (function() { // Define a local copy of jQuery var jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // A central reference to the root jQuery(document) rootjQuery, // A simple way to check for HTML strings or ID strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) quickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/, // Check if a string has a non-whitespace character in it rnotwhite = /\S/, // Used for trimming whitespace trimLeft = /^\s+/, trimRight = /\s+$/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/, // JSON RegExp rvalidchars = /^[\],:{}\s]*$/, rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, // Useragent RegExp rwebkit = /(webkit)[ \/]([\w.]+)/, ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/, rmsie = /(msie) ([\w.]+)/, rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/, // Matches dashed string for camelizing rdashAlpha = /-([a-z]|[0-9])/ig, rmsPrefix = /^-ms-/, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return ( letter + "" ).toUpperCase(); }, // Keep a UserAgent string for use with jQuery.browser userAgent = navigator.userAgent, // For matching the engine and version of the browser browserMatch, // The deferred used on DOM ready readyList, // The ready event handler DOMContentLoaded, // Save a reference to some core methods toString = Object.prototype.toString, hasOwn = Object.prototype.hasOwnProperty, push = Array.prototype.push, slice = Array.prototype.slice, trim = String.prototype.trim, indexOf = Array.prototype.indexOf, // [[Class]] -> type pairs class2type = {}; jQuery.fn = jQuery.prototype = { constructor: jQuery, init: function( selector, context, rootjQuery ) { var match, elem, ret, doc; // Handle $(""), $(null), or $(undefined) if ( !selector ) { return this; } // Handle $(DOMElement) if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; } // The body element only exists once, optimize finding it if ( selector === "body" && !context && document.body ) { this.context = document; this[0] = document.body; this.selector = selector; this.length = 1; return this; } // Handle HTML strings if ( typeof selector === "string" ) { // Are we dealing with HTML string or an ID? if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = quickExpr.exec( selector ); } // Verify a match, and that no context was specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; doc = ( context ? context.ownerDocument || context : document ); // If a single string is passed in and it's a single tag // just do a createElement and skip the rest ret = rsingleTag.exec( selector ); if ( ret ) { if ( jQuery.isPlainObject( context ) ) { selector = [ document.createElement( ret[1] ) ]; jQuery.fn.attr.call( selector, context, true ); } else { selector = [ doc.createElement( ret[1] ) ]; } } else { ret = jQuery.buildFragment( [ match[1] ], [ doc ] ); selector = ( ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment ).childNodes; } return jQuery.merge( this, selector ); // HANDLE: $("#id") } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id !== match[2] ) { return rootjQuery.find( selector ); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }, // Start with an empty selector selector: "", // The current version of jQuery being used jquery: "1.7.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 slice.call( this, 0 ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this[ this.length + num ] : this[ num ] ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems, name, selector ) { // Build a new jQuery matched element set var ret = this.constructor(); if ( jQuery.isArray( elems ) ) { push.apply( ret, elems ); } else { jQuery.merge( ret, elems ); } // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; if ( name === "find" ) { ret.selector = this.selector + ( this.selector ? " " : "" ) + selector; } else if ( name ) { ret.selector = this.selector + "." + name + "(" + selector + ")"; } // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, ready: function( fn ) { // Attach the listeners jQuery.bindReady(); // Add the callback readyList.add( fn ); return this; }, eq: function( i ) { i = +i; return i === -1 ? this.slice( i ) : this.slice( i, i + 1 ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, slice: function() { return this.pushStack( slice.apply( this, arguments ), "slice", slice.call(arguments).join(",") ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { target = this; --i; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ noConflict: function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }, // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Either a released hold or an DOMready/load event and not yet ready if ( (wait === true && !--jQuery.readyWait) || (wait !== true && !jQuery.isReady) ) { // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready, 1 ); } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.fireWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger( "ready" ).off( "ready" ); } } }, bindReady: function() { if ( readyList ) { return; } readyList = jQuery.Callbacks( "once memory" ); // Catch cases where $(document).ready() is called after the // browser event has already occurred. if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready return setTimeout( jQuery.ready, 1 ); } // Mozilla, Opera and webkit nightlies currently support this event if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", jQuery.ready, false ); // If IE event model is used } else if ( document.attachEvent ) { // ensure firing before onload, // maybe late but safe also for iframes document.attachEvent( "onreadystatechange", DOMContentLoaded ); // A fallback to window.onload, that will always work window.attachEvent( "onload", jQuery.ready ); // If IE and not a frame // continually check to see if the document is ready var toplevel = false; try { toplevel = window.frameElement == null; } catch(e) {} if ( document.documentElement.doScroll && toplevel ) { doScrollCheck(); } } }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray || function( obj ) { return jQuery.type(obj) === "array"; }, // A crude way of determining if an object is a window isWindow: function( obj ) { return obj && typeof obj === "object" && "setInterval" in obj; }, isNumeric: function( obj ) { return !isNaN( parseFloat(obj) ) && isFinite( obj ); }, type: function( obj ) { return obj == null ? String( obj ) : class2type[ toString.call(obj) ] || "object"; }, isPlainObject: function( obj ) { // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } try { // Not own constructor property must be Object if ( obj.constructor && !hasOwn.call(obj, "constructor") && !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } } catch ( e ) { // IE8,9 Will throw exceptions on certain host objects #9897 return false; } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. var key; for ( key in obj ) {} return key === undefined || hasOwn.call( obj, key ); }, isEmptyObject: function( obj ) { for ( var name in obj ) { return false; } return true; }, error: function( msg ) { throw new Error( msg ); }, parseJSON: function( data ) { if ( typeof data !== "string" || !data ) { return null; } // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); // Attempt to parse using the native JSON parser first if ( window.JSON && window.JSON.parse ) { return window.JSON.parse( data ); } // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if ( rvalidchars.test( data.replace( rvalidescape, "@" ) .replace( rvalidtokens, "]" ) .replace( rvalidbraces, "")) ) { return ( new Function( "return " + data ) )(); } jQuery.error( "Invalid JSON: " + data ); }, // Cross-browser xml parsing parseXML: function( data ) { var xml, tmp; try { if ( window.DOMParser ) { // Standard tmp = new DOMParser(); xml = tmp.parseFromString( data , "text/xml" ); } else { // IE xml = new ActiveXObject( "Microsoft.XMLDOM" ); xml.async = "false"; xml.loadXML( data ); } } catch( e ) { xml = undefined; } if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }, noop: function() {}, // Evaluates a script in a global context // Workarounds based on findings by Jim Driscoll // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context globalEval: function( data ) { if ( data && rnotwhite.test( data ) ) { // We use execScript on Internet Explorer // We use an anonymous function so that context is window // rather than jQuery in Firefox ( window.execScript || function( data ) { window[ "eval" ].call( window, data ); } )( data ); } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase(); }, // args is for internal usage only each: function( object, callback, args ) { var name, i = 0, length = object.length, isObj = length === undefined || jQuery.isFunction( object ); if ( args ) { if ( isObj ) { for ( name in object ) { if ( callback.apply( object[ name ], args ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.apply( object[ i++ ], args ) === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isObj ) { for ( name in object ) { if ( callback.call( object[ name ], name, object[ name ] ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) { break; } } } } return object; }, // Use native String.trim function wherever possible trim: trim ? function( text ) { return text == null ? "" : trim.call( text ); } : // Otherwise use our own trimming functionality function( text ) { return text == null ? "" : text.toString().replace( trimLeft, "" ).replace( trimRight, "" ); }, // results is for internal usage only makeArray: function( array, results ) { var ret = results || []; if ( array != null ) { // The window, strings (and functions) also have 'length' // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930 var type = jQuery.type( array ); if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) { push.call( ret, array ); } else { jQuery.merge( ret, array ); } } return ret; }, inArray: function( elem, array, i ) { var len; if ( array ) { if ( indexOf ) { return indexOf.call( array, elem, i ); } len = array.length; i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; for ( ; i < len; i++ ) { // Skip accessing in sparse arrays if ( i in array && array[ i ] === elem ) { return i; } } } return -1; }, merge: function( first, second ) { var i = first.length, j = 0; if ( typeof second.length === "number" ) { for ( var l = second.length; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, inv ) { var ret = [], retVal; inv = !!inv; // Go through the array, only saving the items // that pass the validator function for ( var i = 0, length = elems.length; i < length; i++ ) { retVal = !!callback( elems[ i ], i ); if ( inv !== retVal ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, key, ret = [], i = 0, length = elems.length, // jquery objects are treated as arrays isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ; // Go through the array, translating each of the items to their if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } // Go through every key on the object, } else { for ( key in elems ) { value = callback( elems[ key ], key, arg ); if ( value != null ) { ret[ ret.length ] = value; } } } // Flatten any nested arrays return ret.concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { if ( typeof context === "string" ) { var tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind var args = slice.call( arguments, 2 ), proxy = function() { return fn.apply( context, args.concat( slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++; return proxy; }, // Mutifunctional method to get and set values to a collection // The value/s can optionally be executed if it's a function access: function( elems, 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" }; }, sub: function() { function jQuerySub( selector, context ) { return new jQuerySub.fn.init( selector, context ); } jQuery.extend( true, jQuerySub, this ); jQuerySub.superclass = this; jQuerySub.fn = jQuerySub.prototype = this(); jQuerySub.fn.constructor = jQuerySub; jQuerySub.sub = this.sub; jQuerySub.fn.init = function init( selector, context ) { if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) { context = jQuerySub( context ); } return jQuery.fn.init.call( this, selector, context, rootjQuerySub ); }; jQuerySub.fn.init.prototype = jQuerySub.fn; var rootjQuerySub = jQuerySub(document); return jQuerySub; }, browser: {} }); // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); browserMatch = jQuery.uaMatch( userAgent ); if ( browserMatch.browser ) { jQuery.browser[ browserMatch.browser ] = true; jQuery.browser.version = browserMatch.version; } // Deprecated, use jQuery.browser.webkit instead if ( jQuery.browser.webkit ) { jQuery.browser.safari = true; } // IE doesn't match non-breaking spaces with \s if ( rnotwhite.test( "\xA0" ) ) { trimLeft = /^[\s\xA0]+/; trimRight = /[\s\xA0]+$/; } // All jQuery objects should point back to these rootjQuery = jQuery(document); // Cleanup functions for the document ready method if ( document.addEventListener ) { DOMContentLoaded = function() { document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); jQuery.ready(); }; } else if ( document.attachEvent ) { DOMContentLoaded = function() { // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( document.readyState === "complete" ) { document.detachEvent( "onreadystatechange", DOMContentLoaded ); jQuery.ready(); } }; } // The DOM ready check for Internet Explorer function doScrollCheck() { if ( jQuery.isReady ) { return; } try { // If IE is used, use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ document.documentElement.doScroll("left"); } catch(e) { setTimeout( doScrollCheck, 1 ); return; } // and execute any waiting functions jQuery.ready(); } return jQuery; })(); // String to Object flags format cache var flagsCache = {}; // Convert String-formatted flags into Object-formatted ones and store in cache function createFlags( flags ) { var object = flagsCache[ flags ] = {}, i, length; flags = flags.split( /\s+/ ); for ( i = 0, length = flags.length; i < length; i++ ) { object[ flags[i] ] = true; } return object; } /* * Create a callback list using the following parameters: * * flags: an optional list of space-separated flags that will change how * the callback list behaves * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible flags: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( flags ) { // Convert flags from String-formatted to Object-formatted // (we check in cache first) flags = flags ? ( flagsCache[ flags ] || createFlags( flags ) ) : {}; var // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = [], // Last fire value (for non-forgettable lists) memory, // Flag to know if list is currently firing firing, // First callback to fire (used internally by add and fireWith) firingStart, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // Add one or several callbacks to the list add = function( args ) { var i, length, elem, type, actual; for ( i = 0, length = args.length; i < length; i++ ) { elem = args[ i ]; type = jQuery.type( elem ); if ( type === "array" ) { // Inspect recursively add( elem ); } else if ( type === "function" ) { // Add if not in unique mode and callback is not in if ( !flags.unique || !self.has( elem ) ) { list.push( elem ); } } } }, // Fire callbacks fire = function( context, args ) { args = args || []; memory = !flags.memory || [ context, args ]; firing = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( context, args ) === false && flags.stopOnFalse ) { memory = true; // Mark as halted break; } } firing = false; if ( list ) { if ( !flags.once ) { if ( stack && stack.length ) { memory = stack.shift(); self.fireWith( memory[ 0 ], memory[ 1 ] ); } } else if ( memory === true ) { self.disable(); } else { list = []; } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { var length = list.length; add( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away, unless previous // firing was halted (stopOnFalse) } else if ( memory && memory !== true ) { firingStart = length; fire( memory[ 0 ], memory[ 1 ] ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { var args = arguments, argIndex = 0, argLength = args.length; for ( ; argIndex < argLength ; argIndex++ ) { for ( var i = 0; i < list.length; i++ ) { if ( args[ argIndex ] === list[ i ] ) { // Handle firingIndex and firingLength if ( firing ) { if ( i <= firingLength ) { firingLength--; if ( i <= firingIndex ) { firingIndex--; } } } // Remove the element list.splice( i--, 1 ); // If we have some unicity property then // we only need to do this once if ( flags.unique ) { break; } } } } } return this; }, // Control if a given callback is in the list has: function( fn ) { if ( list ) { var i = 0, length = list.length; for ( ; i < length; i++ ) { if ( fn === list[ i ] ) { return true; } } } return false; }, // Remove all callbacks from the list empty: function() { list = []; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory || memory === true ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { if ( stack ) { if ( firing ) { if ( !flags.once ) { stack.push( [ context, args ] ); } } else if ( !( flags.once && memory ) ) { fire( context, args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!memory; } }; return self; }; var // Static reference to slice sliceDeferred = [].slice; jQuery.extend({ Deferred: function( func ) { var doneList = jQuery.Callbacks( "once memory" ), failList = jQuery.Callbacks( "once memory" ), progressList = jQuery.Callbacks( "memory" ), state = "pending", lists = { resolve: doneList, reject: failList, notify: progressList }, promise = { done: doneList.add, fail: failList.add, progress: progressList.add, state: function() { return state; }, // Deprecated isResolved: doneList.fired, isRejected: failList.fired, then: function( doneCallbacks, failCallbacks, progressCallbacks ) { deferred.done( doneCallbacks ).fail( failCallbacks ).progress( progressCallbacks ); return this; }, always: function() { deferred.done.apply( deferred, arguments ).fail.apply( deferred, arguments ); return this; }, pipe: function( fnDone, fnFail, fnProgress ) { return jQuery.Deferred(function( newDefer ) { jQuery.each( { done: [ fnDone, "resolve" ], fail: [ fnFail, "reject" ], progress: [ fnProgress, "notify" ] }, function( handler, data ) { var fn = data[ 0 ], action = data[ 1 ], returned; if ( jQuery.isFunction( fn ) ) { deferred[ handler ](function() { returned = fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise().then( newDefer.resolve, newDefer.reject, newDefer.notify ); } else { newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] ); } }); } else { deferred[ handler ]( newDefer[ action ] ); } }); }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { if ( obj == null ) { obj = promise; } else { for ( var key in promise ) { obj[ key ] = promise[ key ]; } } return obj; } }, deferred = promise.promise({}), key; for ( key in lists ) { deferred[ key ] = lists[ key ].fire; deferred[ key + "With" ] = lists[ key ].fireWith; } // Handle state deferred.done( function() { state = "resolved"; }, failList.disable, progressList.lock ).fail( function() { state = "rejected"; }, doneList.disable, progressList.lock ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( firstParam ) { var args = sliceDeferred.call( arguments, 0 ), i = 0, length = args.length, pValues = new Array( length ), count = length, pCount = length, deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise ) ? firstParam : jQuery.Deferred(), promise = deferred.promise(); function resolveFunc( i ) { return function( value ) { args[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; if ( !( --count ) ) { deferred.resolveWith( deferred, args ); } }; } function progressFunc( i ) { return function( value ) { pValues[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; deferred.notifyWith( promise, pValues ); }; } if ( length > 1 ) { for ( ; i < length; i++ ) { if ( args[ i ] && args[ i ].promise && jQuery.isFunction( args[ i ].promise ) ) { args[ i ].promise().then( resolveFunc(i), deferred.reject, progressFunc(i) ); } else { --count; } } if ( !count ) { deferred.resolveWith( deferred, args ); } } else if ( deferred !== firstParam ) { deferred.resolveWith( deferred, length ? [ firstParam ] : [] ); } return promise; } }); jQuery.support = (function() { var support, all, a, select, opt, input, marginDiv, fragment, tds, events, eventName, i, isSupported, div = document.createElement( "div" ), documentElement = document.documentElement; // Preliminary tests div.setAttribute("className", "t"); div.innerHTML = " <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>"; all = div.getElementsByTagName( "*" ); a = div.getElementsByTagName( "a" )[ 0 ]; // Can't get basic test support if ( !all || !all.length || !a ) { return {}; } // First batch of supports tests select = document.createElement( "select" ); opt = select.appendChild( document.createElement("option") ); input = div.getElementsByTagName( "input" )[ 0 ]; support = { // IE strips leading whitespace when .innerHTML is used leadingWhitespace: ( div.firstChild.nodeType === 3 ), // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables tbody: !div.getElementsByTagName("tbody").length, // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE htmlSerialize: !!div.getElementsByTagName("link").length, // Get the style information from getAttribute // (IE uses .cssText instead) style: /top/.test( a.getAttribute("style") ), // Make sure that URLs aren't manipulated // (IE normalizes it by default) hrefNormalized: ( a.getAttribute("href") === "/a" ), // Make sure that element opacity exists // (IE uses filter instead) // Use a regex to work around a WebKit issue. See #5145 opacity: /^0.55/.test( a.style.opacity ), // Verify style float existence // (IE uses styleFloat instead of cssFloat) cssFloat: !!a.style.cssFloat, // Make sure that if no value is specified for a checkbox // that it defaults to "on". // (WebKit defaults to "" instead) checkOn: ( input.value === "on" ), // Make sure that a selected-by-default option has a working selected property. // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) optSelected: opt.selected, // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) getSetAttribute: div.className !== "t", // Tests for enctype support on a form(#6743) enctype: !!document.createElement("form").enctype, // Makes sure cloning an html5 element does not cause problems // Where outerHTML is undefined, this still works html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>", // Will be defined later submitBubbles: true, changeBubbles: true, focusinBubbles: false, deleteExpando: true, noCloneEvent: true, inlineBlockNeedsLayout: false, shrinkWrapBlocks: false, reliableMarginRight: true }; // Make sure checked status is properly cloned input.checked = true; support.noCloneChecked = input.cloneNode( true ).checked; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Test to see if it's possible to delete an expando from an element // Fails in Internet Explorer try { delete div.test; } catch( e ) { support.deleteExpando = false; } if ( !div.addEventListener && div.attachEvent && div.fireEvent ) { div.attachEvent( "onclick", function() { // Cloning a node shouldn't copy over any // bound event handlers (IE does this) support.noCloneEvent = false; }); div.cloneNode( true ).fireEvent( "onclick" ); } // Check if a radio maintains its value // after being appended to the DOM input = document.createElement("input"); input.value = "t"; input.setAttribute("type", "radio"); support.radioValue = input.value === "t"; input.setAttribute("checked", "checked"); 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 ); div.innerHTML = ""; // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. For more // info see bug #3333 // Fails in WebKit before Feb 2011 nightlies // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right if ( window.getComputedStyle ) { marginDiv = document.createElement( "div" ); marginDiv.style.width = "0"; marginDiv.style.marginRight = "0"; div.style.width = "2px"; div.appendChild( marginDiv ); support.reliableMarginRight = ( parseInt( ( window.getComputedStyle( marginDiv, null ) || { marginRight: 0 } ).marginRight, 10 ) || 0 ) === 0; } // Technique from Juriy Zaytsev // http://perfectionkills.com/detecting-event-support-without-browser-sniffing/ // We only care about the case where non-standard event systems // are used, namely in IE. Short-circuiting here helps us to // avoid an eval call (in setAttribute) which can cause CSP // to go haywire. See: https://developer.mozilla.org/en/Security/CSP if ( div.attachEvent ) { for( i in { submit: 1, change: 1, focusin: 1 }) { eventName = "on" + i; isSupported = ( eventName in div ); if ( !isSupported ) { div.setAttribute( eventName, "return;" ); isSupported = ( typeof div[ eventName ] === "function" ); } support[ i + "Bubbles" ] = isSupported; } } fragment.removeChild( div ); // Null elements to avoid leaks in IE fragment = select = opt = marginDiv = div = input = null; // Run tests that need a body at doc ready jQuery(function() { var container, outer, inner, table, td, offsetSupport, conMarginTop, ptlm, vb, style, html, body = document.getElementsByTagName("body")[0]; if ( !body ) { // Return for frameset docs that don't have a body return; } conMarginTop = 1; ptlm = "position:absolute;top:0;left:0;width:1px;height:1px;margin:0;"; vb = "visibility:hidden;border:0;"; style = "style='" + ptlm + "border:5px solid #000;padding:0;'"; html = "<div " + style + "><div></div></div>" + "<table " + style + " cellpadding='0' cellspacing='0'>" + "<tr><td></td></tr></table>"; container = document.createElement("div"); container.style.cssText = vb + "width:0;height:0;position:static;top:0;margin-top:" + conMarginTop + "px"; body.insertBefore( container, body.firstChild ); // Construct the test element div = document.createElement("div"); container.appendChild( div ); // Check if table cells still have offsetWidth/Height when they are set // to display:none and there are still other visible table cells in a // table row; if so, offsetWidth/Height are not reliable for use when // determining if an element has been hidden directly using // display:none (it is still safe to use offsets if a parent element is // hidden; don safety goggles and see bug #4512 for more information). // (only IE 8 fails this test) div.innerHTML = "<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>"; tds = div.getElementsByTagName( "td" ); isSupported = ( tds[ 0 ].offsetHeight === 0 ); tds[ 0 ].style.display = ""; tds[ 1 ].style.display = "none"; // Check if empty table cells still have offsetWidth/Height // (IE <= 8 fail this test) support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); // Figure out if the W3C box model works as expected div.innerHTML = ""; div.style.width = div.style.paddingLeft = "1px"; jQuery.boxModel = support.boxModel = div.offsetWidth === 2; 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.style.display = "inline"; div.style.zoom = 1; 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>"; support.shrinkWrapBlocks = ( div.offsetWidth !== 2 ); } div.style.cssText = ptlm + vb; div.innerHTML = html; outer = div.firstChild; inner = outer.firstChild; td = outer.nextSibling.firstChild.firstChild; offsetSupport = { doesNotAddBorder: ( inner.offsetTop !== 5 ), doesAddBorderForTableAndCells: ( td.offsetTop === 5 ) }; inner.style.position = "fixed"; inner.style.top = "20px"; // safari subtracts parent border width here which is 5px offsetSupport.fixedPosition = ( inner.offsetTop === 20 || inner.offsetTop === 15 ); inner.style.position = inner.style.top = ""; outer.style.overflow = "hidden"; outer.style.position = "relative"; offsetSupport.subtractsBorderForOverflowNotVisible = ( inner.offsetTop === -5 ); offsetSupport.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== conMarginTop ); body.removeChild( container ); div = container = null; jQuery.extend( support, offsetSupport ); }); return support; })(); var rbrace = /^(?:\{.*\}|\[.*\])$/, rmultiDash = /([A-Z])/g; jQuery.extend({ cache: {}, // Please use with caution uuid: 0, // Unique for each copy of jQuery on the page // Non-digits removed to match rinlinejQuery expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ), // The following elements throw uncatchable exceptions if you // attempt to add expando properties to them. noData: { "embed": true, // Ban all objects except for Flash (which handle expandos) "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", "applet": true }, hasData: function( elem ) { elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; return !!elem && !isEmptyDataObject( elem ); }, data: function( elem, name, data, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var privateCache, thisCache, ret, internalKey = jQuery.expando, getByName = typeof name === "string", // We have to handle DOM nodes and JS objects differently because IE6-7 // can't GC object references properly across the DOM-JS boundary isNode = elem.nodeType, // Only DOM nodes need the global jQuery cache; JS object data is // attached directly to the object so GC can occur automatically cache = isNode ? jQuery.cache : elem, // Only defining an ID for JS objects if its cache already exists allows // the code to shortcut on the same path as a DOM node with no cache id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey, isEvents = name === "events"; // Avoid doing any more work than we need to when trying to get data on an // object that has no data at all if ( (!id || !cache[id] || (!isEvents && !pvt && !cache[id].data)) && getByName && data === undefined ) { return; } if ( !id ) { // Only DOM nodes need a new unique ID for each element since their data // ends up in the global cache if ( isNode ) { elem[ internalKey ] = id = ++jQuery.uuid; } else { id = internalKey; } } if ( !cache[ id ] ) { cache[ id ] = {}; // Avoids exposing jQuery metadata on plain JS objects when the object // is serialized using JSON.stringify if ( !isNode ) { cache[ id ].toJSON = jQuery.noop; } } // An object can be passed to jQuery.data instead of a key/value pair; this gets // shallow copied over onto the existing cache if ( typeof name === "object" || typeof name === "function" ) { if ( pvt ) { cache[ id ] = jQuery.extend( cache[ id ], name ); } else { cache[ id ].data = jQuery.extend( cache[ id ].data, name ); } } privateCache = thisCache = cache[ id ]; // jQuery data() is stored in a separate object inside the object's internal data // cache in order to avoid key collisions between internal data and user-defined // data. if ( !pvt ) { if ( !thisCache.data ) { thisCache.data = {}; } thisCache = thisCache.data; } if ( data !== undefined ) { thisCache[ jQuery.camelCase( name ) ] = data; } // Users should not attempt to inspect the internal events object using jQuery.data, // it is undocumented and subject to change. But does anyone listen? No. if ( isEvents && !thisCache[ name ] ) { return privateCache.events; } // Check for both converted-to-camel and non-converted data property names // If a data property was specified if ( getByName ) { // First Try to find as-is property data ret = thisCache[ name ]; // Test for null|undefined property data if ( ret == null ) { // Try to find the camelCased property ret = thisCache[ jQuery.camelCase( name ) ]; } } else { ret = thisCache; } return ret; }, removeData: function( elem, name, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, i, l, // Reference to internal data cache key internalKey = jQuery.expando, isNode = elem.nodeType, // See jQuery.data for more information cache = isNode ? jQuery.cache : elem, // See jQuery.data for more information id = isNode ? elem[ internalKey ] : internalKey; // If there is already no cache entry for this object, there is no // purpose in continuing if ( !cache[ id ] ) { return; } if ( name ) { thisCache = pvt ? cache[ id ] : cache[ id ].data; if ( thisCache ) { // Support array or space separated string names for data keys if ( !jQuery.isArray( name ) ) { // try the string as a key before any manipulation if ( name in thisCache ) { name = [ name ]; } else { // split the camel cased version by spaces unless a key with the spaces exists name = jQuery.camelCase( name ); if ( name in thisCache ) { name = [ name ]; } else { name = name.split( " " ); } } } for ( i = 0, l = name.length; i < l; i++ ) { delete thisCache[ name[i] ]; } // If there is no data left in the cache, we want to continue // and let the cache object itself get destroyed if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) { return; } } } // See jQuery.data for more information if ( !pvt ) { delete cache[ id ].data; // Don't destroy the parent cache unless the internal data object // had been the only thing left in it if ( !isEmptyDataObject(cache[ id ]) ) { return; } } // Browsers that fail expando deletion also refuse to delete expandos on // the window, but it will allow it on all other JS objects; other browsers // don't care // Ensure that `cache` is not a window object #10080 if ( jQuery.support.deleteExpando || !cache.setInterval ) { delete cache[ id ]; } else { cache[ id ] = null; } // We destroyed the cache and need to eliminate the expando on the node to avoid // false lookups in the cache for entries that no longer exist if ( isNode ) { // IE does not allow us to delete expando properties from nodes, // nor does it have a removeAttribute function on Document nodes; // we must handle all of these cases if ( jQuery.support.deleteExpando ) { delete elem[ internalKey ]; } else if ( elem.removeAttribute ) { elem.removeAttribute( internalKey ); } else { elem[ internalKey ] = null; } } }, // For internal use only. _data: function( elem, name, data ) { return jQuery.data( elem, name, data, true ); }, // A method for determining if a DOM node can handle the data expando acceptData: function( elem ) { if ( elem.nodeName ) { var match = jQuery.noData[ elem.nodeName.toLowerCase() ]; if ( match ) { return !(match === true || elem.getAttribute("classid") !== match); } } return true; } }); jQuery.fn.extend({ data: function( key, value ) { var parts, attr, name, data = null; if ( typeof key === "undefined" ) { if ( this.length ) { data = jQuery.data( this[0] ); if ( this[0].nodeType === 1 && !jQuery._data( this[0], "parsedAttrs" ) ) { attr = this[0].attributes; for ( var i = 0, l = attr.length; i < l; i++ ) { name = attr[i].name; if ( name.indexOf( "data-" ) === 0 ) { name = jQuery.camelCase( name.substring(5) ); dataAttr( this[0], name, data[ name ] ); } } jQuery._data( this[0], "parsedAttrs", true ); } } return data; } else if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } 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 self = jQuery( this ), args = [ parts[0], value ]; self.triggerHandler( "setData" + parts[1] + "!", args ); jQuery.data( this, key, value ); self.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 ) { var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : jQuery.isNumeric( data ) ? 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; } // checks a cache object for emptiness function isEmptyDataObject( obj ) { for ( var name in obj ) { // if the public data object is empty, the private is still empty if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { continue; } if ( name !== "toJSON" ) { return false; } } return true; } function handleQueueMarkDefer( elem, type, src ) { var deferDataKey = type + "defer", queueDataKey = type + "queue", markDataKey = type + "mark", defer = jQuery._data( elem, deferDataKey ); if ( defer && ( src === "queue" || !jQuery._data(elem, queueDataKey) ) && ( src === "mark" || !jQuery._data(elem, markDataKey) ) ) { // Give room for hard-coded callbacks to fire first // and eventually mark/queue something else on the element setTimeout( function() { if ( !jQuery._data( elem, queueDataKey ) && !jQuery._data( elem, markDataKey ) ) { jQuery.removeData( elem, deferDataKey, true ); defer.fire(); } }, 0 ); } } jQuery.extend({ _mark: function( elem, type ) { if ( elem ) { type = ( type || "fx" ) + "mark"; jQuery._data( elem, type, (jQuery._data( elem, type ) || 0) + 1 ); } }, _unmark: function( force, elem, type ) { if ( force !== true ) { type = elem; elem = force; force = false; } if ( elem ) { type = type || "fx"; var key = type + "mark", count = force ? 0 : ( (jQuery._data( elem, key ) || 1) - 1 ); if ( count ) { jQuery._data( elem, key, count ); } else { jQuery.removeData( elem, key, true ); handleQueueMarkDefer( elem, type, "mark" ); } } }, queue: function( elem, type, data ) { var q; if ( elem ) { type = ( type || "fx" ) + "queue"; q = jQuery._data( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !q || jQuery.isArray(data) ) { q = jQuery._data( elem, type, jQuery.makeArray(data) ); } else { q.push( data ); } } return q || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), fn = queue.shift(), hooks = {}; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } jQuery._data( elem, type + ".run", hooks ); fn.call( elem, function() { jQuery.dequeue( elem, type ); }, hooks ); } if ( !queue.length ) { jQuery.removeData( elem, type + "queue " + type + ".run", true ); handleQueueMarkDefer( elem, type, "queue" ); } } }); jQuery.fn.extend({ queue: function( type, data ) { if ( typeof type !== "string" ) { data = type; type = "fx"; } if ( data === undefined ) { return jQuery.queue( this[0], type ); } return this.each(function() { var queue = jQuery.queue( this, type, data ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ delay: function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = setTimeout( next, time ); hooks.stop = function() { clearTimeout( timeout ); }; }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, object ) { if ( typeof type !== "string" ) { object = type; type = undefined; } type = type || "fx"; var defer = jQuery.Deferred(), elements = this, i = elements.length, count = 1, deferDataKey = type + "defer", queueDataKey = type + "queue", markDataKey = type + "mark", tmp; function resolve() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } } while( i-- ) { if (( tmp = jQuery.data( elements[ i ], deferDataKey, undefined, true ) || ( jQuery.data( elements[ i ], queueDataKey, undefined, true ) || jQuery.data( elements[ i ], markDataKey, undefined, true ) ) && jQuery.data( elements[ i ], deferDataKey, jQuery.Callbacks( "once memory" ), true ) )) { count++; tmp.add( resolve ); } } resolve(); return defer.promise(); } }); var rclass = /[\n\t\r]/g, rspace = /\s+/, rreturn = /\r/g, rtype = /^(?:button|input)$/i, rfocusable = /^(?:button|input|object|select|textarea)$/i, rclickable = /^a(?:rea)?$/i, rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i, getSetAttribute = jQuery.support.getSetAttribute, nodeHook, boolHook, fixSpecified; jQuery.fn.extend({ attr: function( name, value ) { return jQuery.access( this, name, value, true, jQuery.attr ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); }, prop: function( name, value ) { return jQuery.access( this, name, value, true, jQuery.prop ); }, removeProp: function( name ) { name = jQuery.propFix[ name ] || name; return this.each(function() { // try/catch handles cases where IE balks (such as removing a property on window) try { this[ name ] = undefined; delete this[ name ]; } catch( e ) {} }); }, addClass: function( value ) { var classNames, i, l, elem, setClass, c, cl; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call(this, j, this.className) ); }); } if ( value && typeof value === "string" ) { classNames = value.split( rspace ); for ( i = 0, l = this.length; i < l; i++ ) { elem = this[ i ]; if ( elem.nodeType === 1 ) { if ( !elem.className && classNames.length === 1 ) { elem.className = value; } else { setClass = " " + elem.className + " "; for ( c = 0, cl = classNames.length; c < cl; c++ ) { if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) { setClass += classNames[ c ] + " "; } } elem.className = jQuery.trim( setClass ); } } } } return this; }, removeClass: function( value ) { var classNames, i, l, elem, className, c, cl; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call(this, j, this.className) ); }); } if ( (value && typeof value === "string") || value === undefined ) { classNames = ( value || "" ).split( rspace ); for ( i = 0, l = this.length; i < l; i++ ) { elem = this[ i ]; if ( elem.nodeType === 1 && elem.className ) { if ( value ) { className = (" " + elem.className + " ").replace( rclass, " " ); for ( c = 0, cl = classNames.length; c < cl; c++ ) { className = className.replace(" " + classNames[ c ] + " ", " "); } elem.className = jQuery.trim( className ); } else { elem.className = ""; } } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value, isBool = typeof stateVal === "boolean"; if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), state = stateVal, classNames = value.split( rspace ); while ( (className = classNames[ i++ ]) ) { // check each className given, space seperated list state = isBool ? state : !self.hasClass( className ); self[ state ? "addClass" : "removeClass" ]( className ); } } else if ( type === "undefined" || type === "boolean" ) { if ( this.className ) { // store className if set jQuery._data( this, "__className__", this.className ); } // toggle whole className this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) { return true; } } return false; }, val: function( value ) { var hooks, ret, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.nodeName.toLowerCase() ] || jQuery.valHooks[ elem.type ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var self = jQuery(this), val; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, self.val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map(val, function ( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.nodeName.toLowerCase() ] || jQuery.valHooks[ this.type ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { // attributes.value is undefined in Blackberry 4.7 but // uses .value. See #6932 var val = elem.attributes.value; return !val || val.specified ? elem.value : elem.text; } }, select: { get: function( elem ) { var value, i, max, option, index = elem.selectedIndex, values = [], options = elem.options, one = elem.type === "select-one"; // Nothing was selected if ( index < 0 ) { return null; } // Loop through all the selected options i = one ? index : 0; max = one ? index + 1 : options.length; for ( ; i < max; i++ ) { option = options[ i ]; // Don't return options that are disabled or in a disabled optgroup if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) && (!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } // Fixes Bug #2551 -- select.val() broken in IE after form.reset() if ( one && !values.length && options.length ) { return jQuery( options[ index ] ).val(); } return values; }, set: function( elem, value ) { var values = jQuery.makeArray( value ); jQuery(elem).find("option").each(function() { this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; }); if ( !values.length ) { elem.selectedIndex = -1; } return values; } } }, attrFn: { val: true, css: true, html: true, text: true, data: true, width: true, height: true, offset: true }, attr: function( elem, name, value, pass ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } if ( pass && name in jQuery.attrFn ) { return jQuery( elem )[ name ]( value ); } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === "undefined" ) { return jQuery.prop( elem, name, value ); } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); // All attributes are lowercase // Grab necessary hook if one is defined if ( notxml ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); return; } else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, "" + value ); return value; } } else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = elem.getAttribute( name ); // Non-existent attributes return null, we normalize to undefined return ret === null ? undefined : ret; } }, removeAttr: function( elem, value ) { var propName, attrNames, name, l, i = 0; if ( value && elem.nodeType === 1 ) { attrNames = value.toLowerCase().split( rspace ); l = attrNames.length; for ( ; i < l; i++ ) { name = attrNames[ i ]; if ( name ) { propName = jQuery.propFix[ name ] || name; // See #9699 for explanation of this approach (setting first, then removal) jQuery.attr( elem, name, "" ); elem.removeAttribute( getSetAttribute ? name : propName ); // Set corresponding property to false for boolean attributes if ( rboolean.test( name ) && propName in elem ) { elem[ propName ] = false; } } } } }, attrHooks: { type: { set: function( elem, value ) { // We can't allow the type property to be changed (since it causes problems in IE) if ( rtype.test( elem.nodeName ) && elem.parentNode ) { jQuery.error( "type property can't be changed" ); } else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to it's default in case type is set after value // This is for element creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } }, // Use the value property for back compat // Use the nodeHook for button elements in IE6/7 (#1954) value: { get: function( elem, name ) { if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { return nodeHook.get( elem, name ); } return name in elem ? elem.value : null; }, set: function( elem, value, name ) { if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { return nodeHook.set( elem, value, name ); } // Does not return so that setAttribute is also used elem.value = value; } } }, propFix: { tabindex: "tabIndex", readonly: "readOnly", "for": "htmlFor", "class": "className", maxlength: "maxLength", cellspacing: "cellSpacing", cellpadding: "cellPadding", rowspan: "rowSpan", colspan: "colSpan", usemap: "useMap", frameborder: "frameBorder", contenteditable: "contentEditable" }, prop: function( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { return ( elem[ name ] = value ); } } else { if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { return elem[ name ]; } } }, propHooks: { tabIndex: { get: function( elem ) { // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ var attributeNode = elem.getAttributeNode("tabindex"); return attributeNode && attributeNode.specified ? parseInt( attributeNode.value, 10 ) : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : undefined; } } } }); // Add the tabIndex propHook to attrHooks for back-compat (different case is intentional) jQuery.attrHooks.tabindex = jQuery.propHooks.tabIndex; // Hook for boolean attributes boolHook = { get: function( elem, name ) { // Align boolean attributes with corresponding properties // Fall back to attribute presence where some booleans are not supported var attrNode, property = jQuery.prop( elem, name ); return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ? name.toLowerCase() : undefined; }, set: function( elem, value, name ) { var propName; if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else { // value is true since we know at this point it's type boolean and not false // Set boolean attributes to the same name and set the DOM property propName = jQuery.propFix[ name ] || name; if ( propName in elem ) { // Only set the IDL specifically if it already exists on the element elem[ propName ] = true; } elem.setAttribute( name, name.toLowerCase() ); } return name; } }; // IE6/7 do not support getting/setting some attributes with get/setAttribute if ( !getSetAttribute ) { fixSpecified = { name: true, id: true }; // Use this for any attribute in IE6/7 // This fixes almost every IE6/7 issue nodeHook = jQuery.valHooks.button = { get: function( elem, name ) { var ret; ret = elem.getAttributeNode( name ); return ret && ( fixSpecified[ name ] ? ret.nodeValue !== "" : ret.specified ) ? ret.nodeValue : undefined; }, set: function( elem, value, name ) { // Set the existing or create a new attribute node var ret = elem.getAttributeNode( name ); if ( !ret ) { ret = document.createAttribute( name ); elem.setAttributeNode( ret ); } return ( ret.nodeValue = value + "" ); } }; // Apply the nodeHook to tabindex jQuery.attrHooks.tabindex.set = nodeHook.set; // Set width and height to auto instead of 0 on empty string( Bug #8150 ) // This is for removals jQuery.each([ "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { set: function( elem, value ) { if ( value === "" ) { elem.setAttribute( name, "auto" ); return value; } } }); }); // Set contenteditable to false on removals(#10429) // Setting to empty string throws an error as an invalid value jQuery.attrHooks.contenteditable = { get: nodeHook.get, set: function( elem, value, name ) { if ( value === "" ) { value = "false"; } nodeHook.set( elem, value, name ); } }; } // Some attributes require a special call on IE if ( !jQuery.support.hrefNormalized ) { jQuery.each([ "href", "src", "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { get: function( elem ) { var ret = elem.getAttribute( name, 2 ); return ret === null ? undefined : ret; } }); }); } if ( !jQuery.support.style ) { jQuery.attrHooks.style = { get: function( elem ) { // Return undefined in the case of empty string // Normalize to lowercase since IE uppercases css property names return elem.style.cssText.toLowerCase() || undefined; }, set: function( elem, value ) { return ( elem.style.cssText = "" + value ); } }; } // Safari mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( !jQuery.support.optSelected ) { jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, { get: function( elem ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; // Make sure that it also works with optgroups, see #5701 if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } return null; } }); } // IE6/7 call enctype encoding if ( !jQuery.support.enctype ) { jQuery.propFix.enctype = "encoding"; } // Radios and checkboxes getter/setter if ( !jQuery.support.checkOn ) { jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { get: function( elem ) { // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; } }; }); } jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }); }); var rformElems = /^(?:textarea|input|select)$/i, rtypenamespace = /^([^\.]*)?(?:\.(.+))?$/, rhoverHack = /\bhover(\.\S+)?\b/, rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rquickIs = /^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/, quickParse = function( selector ) { var quick = rquickIs.exec( selector ); if ( quick ) { // 0 1 2 3 // [ _, tag, id, class ] quick[1] = ( quick[1] || "" ).toLowerCase(); quick[3] = quick[3] && new RegExp( "(?:^|\\s)" + quick[3] + "(?:\\s|$)" ); } return quick; }, quickIs = function( elem, m ) { var attrs = elem.attributes || {}; return ( (!m[1] || elem.nodeName.toLowerCase() === m[1]) && (!m[2] || (attrs.id || {}).value === m[2]) && (!m[3] || m[3].test( (attrs[ "class" ] || {}).value )) ); }, hoverHack = function( events ) { return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" ); }; /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { add: function( elem, types, handler, data, selector ) { var elemData, eventHandle, events, t, tns, type, namespaces, handleObj, handleObjIn, quick, handlers, special; // Don't attach events to noData or text/comment nodes (allow plain objects tho) if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first events = elemData.events; if ( !events ) { elemData.events = events = {}; } eventHandle = elemData.handle; if ( !eventHandle ) { elemData.handle = eventHandle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : undefined; }; // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events eventHandle.elem = elem; } // Handle multiple events separated by a space // jQuery(...).bind("mouseover mouseout", fn); types = jQuery.trim( hoverHack(types) ).split( " " ); for ( t = 0; t < types.length; t++ ) { tns = rtypenamespace.exec( types[t] ) || []; type = tns[1]; namespaces = ( tns[2] || "" ).split( "." ).sort(); // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: tns[1], data: data, handler: handler, guid: handler.guid, selector: selector, quick: quickParse( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first handlers = events[ type ]; if ( !handlers ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener/attachEvent if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { // Bind the global event handler to the element if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, global: {}, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var elemData = jQuery.hasData( elem ) && jQuery._data( elem ), t, tns, type, origType, namespaces, origCount, j, events, special, handle, eventType, handleObj; if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = jQuery.trim( hoverHack( types || "" ) ).split(" "); for ( t = 0; t < types.length; t++ ) { tns = rtypenamespace.exec( types[t] ) || []; type = origType = tns[1]; namespaces = tns[2]; // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector? special.delegateType : special.bindType ) || type; eventType = events[ type ] || []; origCount = eventType.length; namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.)?") + "(\\.|$)") : null; // Remove matching events for ( j = 0; j < eventType.length; j++ ) { handleObj = eventType[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !namespaces || namespaces.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { eventType.splice( j--, 1 ); if ( handleObj.selector ) { eventType.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( eventType.length === 0 && origCount !== eventType.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { handle = elemData.handle; if ( handle ) { handle.elem = null; } // removeData also checks for emptiness and clears the expando if empty // so use it instead of delete jQuery.removeData( elem, [ "events", "handle" ], true ); } }, // Events that are safe to short-circuit if no handlers are attached. // Native DOM events should not be added, they may have inline handlers. customEvent: { "getData": true, "setData": true, "changeData": true }, trigger: function( event, data, elem, onlyHandlers ) { // Don't do events on text and comment nodes if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) { return; } // Event object or event type var type = event.type || event, namespaces = [], cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType; // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf( "!" ) >= 0 ) { // Exclusive events trigger only for the exact event (no namespaces) type = type.slice(0, -1); exclusive = true; } if ( type.indexOf( "." ) >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) { // No jQuery handlers for this event type, and it can't have inline handlers return; } // Caller can pass in an Event, Object, or just an event type string event = typeof event === "object" ? // jQuery.Event object event[ jQuery.expando ] ? event : // Object literal new jQuery.Event( type, event ) : // Just the event type (string) new jQuery.Event( type ); event.type = type; event.isTrigger = true; event.exclusive = exclusive; event.namespace = namespaces.join( "." ); event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.)?") + "(\\.|$)") : null; ontype = type.indexOf( ":" ) < 0 ? "on" + type : ""; // Handle a global trigger if ( !elem ) { // TODO: Stop taunting the data cache; remove global events and always attach to document cache = jQuery.cache; for ( i in cache ) { if ( cache[ i ].events && cache[ i ].events[ type ] ) { jQuery.event.trigger( event, data, cache[ i ].handle.elem, true ); } } return; } // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data != null ? jQuery.makeArray( data ) : []; data.unshift( event ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) eventPath = [[ elem, special.bindType || type ]]; if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode; old = null; for ( ; cur; cur = cur.parentNode ) { eventPath.push([ cur, bubbleType ]); old = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( old && old === elem.ownerDocument ) { eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]); } } // Fire handlers on the event path for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) { cur = eventPath[i][0]; event.type = eventPath[i][1]; handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Note that this is a bare JS function and not a jQuery handler handle = ontype && cur[ ontype ]; if ( handle && jQuery.acceptData( cur ) && handle.apply( cur, data ) === false ) { event.preventDefault(); } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) && !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Can't use an .isFunction() check here because IE6/7 fails that test. // Don't do default actions on window, that's where global variables be (#6170) // IE<9 dies on focus/blur to hidden element (#1486) if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method old = elem[ ontype ]; if ( old ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; elem[ type ](); jQuery.event.triggered = undefined; if ( old ) { elem[ ontype ] = old; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event || window.event ); var handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []), delegateCount = handlers.delegateCount, args = [].slice.call( arguments, 0 ), run_all = !event.exclusive && !event.namespace, handlerQueue = [], i, j, cur, jqcur, ret, selMatch, matched, matches, handleObj, sel, related; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Determine handlers that should run if there are delegated events // Avoid disabled elements in IE (#6911) and non-left-click bubbling in Firefox (#3861) if ( delegateCount && !event.target.disabled && !(event.button && event.type === "click") ) { // Pregenerate a single jQuery object for reuse with .is() jqcur = jQuery(this); jqcur.context = this.ownerDocument || this; for ( cur = event.target; cur != this; cur = cur.parentNode || this ) { selMatch = {}; matches = []; jqcur[0] = cur; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; sel = handleObj.selector; if ( selMatch[ sel ] === undefined ) { selMatch[ sel ] = ( handleObj.quick ? quickIs( cur, handleObj.quick ) : jqcur.is( sel ) ); } if ( selMatch[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, matches: matches }); } } } // Add the remaining (directly-bound) handlers if ( handlers.length > delegateCount ) { handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) }); } // Run delegates first; they may want to stop propagation beneath us for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) { matched = handlerQueue[ i ]; event.currentTarget = matched.elem; for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) { handleObj = matched.matches[ j ]; // Triggered event must either 1) be non-exclusive and have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) { event.data = handleObj.data; event.handleObj = handleObj; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { event.result = ret; if ( ret === false ) { event.preventDefault(); event.stopPropagation(); } } } } } return event.result; }, // Includes some event props shared by KeyEvent and MouseEvent // *** attrChange attrName relatedNode srcElement are not normalized, non-W3C, deprecated, will be removed in 1.8 *** props: "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split(" "), filter: function( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var eventDoc, doc, body, button = original.button, fromElement = original.fromElement; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add relatedTarget, if necessary if ( !event.relatedTarget && fromElement ) { event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, originalEvent = event, fixHook = jQuery.event.fixHooks[ event.type ] || {}, copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = jQuery.Event( originalEvent ); for ( i = copy.length; i; ) { prop = copy[ --i ]; event[ prop ] = originalEvent[ prop ]; } // Fix target property, if necessary (#1925, IE 6/7/8 & Safari2) if ( !event.target ) { event.target = originalEvent.srcElement || document; } // Target should not be a text node (#504, Safari) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // For mouse/key events; add metaKey if it's not there (#3368, IE6/7/8) if ( event.metaKey === undefined ) { event.metaKey = event.ctrlKey; } return fixHook.filter? fixHook.filter( event, originalEvent ) : event; }, special: { ready: { // Make sure the ready event is setup setup: jQuery.bindReady }, load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { delegateType: "focusin" }, blur: { delegateType: "focusout" }, beforeunload: { setup: function( data, namespaces, eventHandle ) { // We only want to do this special case on windows if ( jQuery.isWindow( this ) ) { this.onbeforeunload = eventHandle; } }, teardown: function( namespaces, eventHandle ) { if ( this.onbeforeunload === eventHandle ) { this.onbeforeunload = null; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; // Some plugins are using, but it's undocumented/deprecated and will be removed. // The 1.7 special event interface should provide all the hooks needed now. jQuery.event.handle = jQuery.event.dispatch; jQuery.removeEvent = document.removeEventListener ? function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } } : function( elem, type, handle ) { if ( elem.detachEvent ) { elem.detachEvent( "on" + type, handle ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !(this instanceof jQuery.Event) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false || src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; function returnFalse() { return false; } function returnTrue() { return true; } // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { preventDefault: function() { this.isDefaultPrevented = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if preventDefault exists run it on the original event if ( e.preventDefault ) { e.preventDefault(); // otherwise set the returnValue property of the original event to false (IE) } else { e.returnValue = false; } }, stopPropagation: function() { this.isPropagationStopped = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if stopPropagation exists run it on the original event if ( e.stopPropagation ) { e.stopPropagation(); } // otherwise set the cancelBubble property of the original event to true (IE) e.cancelBubble = true; }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); }, isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse }; // Create mouseenter/leave events using mouseover/out and event-time checks jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var target = this, related = event.relatedTarget, handleObj = event.handleObj, selector = handleObj.selector, ret; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !jQuery.contains( target, related )) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; }); // IE submit delegation if ( !jQuery.support.submitBubbles ) { jQuery.event.special.submit = { setup: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Lazy-add a submit handler when a descendant form may potentially be submitted jQuery.event.add( this, "click._submit keypress._submit", function( e ) { // Node name check avoids a VML-related crash in IE (#9807) var elem = e.target, form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; if ( form && !form._submit_attached ) { jQuery.event.add( form, "submit._submit", function( event ) { // If form was submitted by the user, bubble the event up the tree if ( this.parentNode && !event.isTrigger ) { jQuery.event.simulate( "submit", this.parentNode, event, true ); } }); form._submit_attached = true; } }); // return undefined since we don't need an event listener }, teardown: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Remove delegated handlers; cleanData eventually reaps submit handlers attached above jQuery.event.remove( this, "._submit" ); } }; } // IE change delegation and checkbox/radio fix if ( !jQuery.support.changeBubbles ) { jQuery.event.special.change = { setup: function() { if ( rformElems.test( this.nodeName ) ) { // IE doesn't fire change on a check/radio until blur; trigger it on click // after a propertychange. Eat the blur-change in special.change.handle. // This still fires onchange a second time for check/radio after blur. if ( this.type === "checkbox" || this.type === "radio" ) { jQuery.event.add( this, "propertychange._change", function( event ) { if ( event.originalEvent.propertyName === "checked" ) { this._just_changed = true; } }); jQuery.event.add( this, "click._change", function( event ) { if ( this._just_changed && !event.isTrigger ) { this._just_changed = false; jQuery.event.simulate( "change", this, event, true ); } }); } return false; } // Delegated event; lazy-add a change handler on descendant inputs jQuery.event.add( this, "beforeactivate._change", function( e ) { var elem = e.target; if ( rformElems.test( elem.nodeName ) && !elem._change_attached ) { jQuery.event.add( elem, "change._change", function( event ) { if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { jQuery.event.simulate( "change", this.parentNode, event, true ); } }); elem._change_attached = true; } }); }, handle: function( event ) { var elem = event.target; // Swallow native change events from checkbox/radio, we already triggered them above if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { return event.handleObj.handler.apply( this, arguments ); } }, teardown: function() { jQuery.event.remove( this, "._change" ); return rformElems.test( this.nodeName ); } }; } // Create "bubbling" focus and blur events if ( !jQuery.support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler while someone wants focusin/focusout var attaches = 0, handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { if ( attaches++ === 0 ) { document.addEventListener( orig, handler, true ); } }, teardown: function() { if ( --attaches === 0 ) { document.removeEventListener( orig, handler, true ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var origFn, type; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, 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.call( this, types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event var handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace? handleObj.type + "." + handleObj.namespace : handleObj.type, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( var type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, live: function( types, data, fn ) { jQuery( this.context ).on( types, this.selector, data, fn ); return this; }, die: function( types, fn ) { jQuery( this.context ).off( types, this.selector || "**", fn ); return this; }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length == 1? this.off( selector, "**" ) : this.off( types, selector, fn ); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { if ( this[0] ) { return jQuery.event.trigger( type, data, this[0], true ); } }, toggle: function( fn ) { // Save reference to arguments for access in closure var args = arguments, guid = fn.guid || jQuery.guid++, i = 0, toggler = function( event ) { // Figure out which function to execute var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i; jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 ); // Make sure that clicks stop event.preventDefault(); // and execute the function return args[ lastToggle ].apply( this, arguments ) || false; }; // link all the functions, so any of them can unbind this click handler toggler.guid = guid; while ( i < args.length ) { args[ i++ ].guid = guid; } return this.click( toggler ); }, hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); } }); jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { if ( fn == null ) { fn = data; data = null; } return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; if ( jQuery.attrFn ) { jQuery.attrFn[ name ] = true; } if ( rkeyEvent.test( name ) ) { jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks; } if ( rmouseEvent.test( name ) ) { jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks; } }); /*! * Sizzle CSS Selector Engine * Copyright 2011, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * More information: http://sizzlejs.com/ */ (function(){ var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, expando = "sizcache" + (Math.random() + '').replace('.', ''), done = 0, toString = Object.prototype.toString, hasDuplicate = false, baseHasDuplicate = true, rBackslash = /\\/g, rReturn = /\r\n/g, rNonWord = /\W/; // Here we check if the JavaScript engine is using some sort of // optimization where it does not always call our comparision // function. If that is the case, discard the hasDuplicate value. // Thus far that includes Google Chrome. [0, 0].sort(function() { baseHasDuplicate = false; return 0; }); var Sizzle = function( selector, context, results, seed ) { results = results || []; context = context || document; var origContext = context; if ( context.nodeType !== 1 && context.nodeType !== 9 ) { return []; } if ( !selector || typeof selector !== "string" ) { return results; } var m, set, checkSet, extra, ret, cur, pop, i, prune = true, contextXML = Sizzle.isXML( context ), parts = [], soFar = selector; // Reset the position of the chunker regexp (start from head) do { chunker.exec( "" ); m = chunker.exec( soFar ); if ( m ) { soFar = m[3]; parts.push( m[1] ); if ( m[2] ) { extra = m[3]; break; } } } while ( m ); if ( parts.length > 1 && origPOS.exec( selector ) ) { if ( parts.length === 2 && Expr.relative[ parts[0] ] ) { set = posProcess( parts[0] + parts[1], context, seed ); } else { set = Expr.relative[ parts[0] ] ? [ context ] : Sizzle( parts.shift(), context ); while ( parts.length ) { selector = parts.shift(); if ( Expr.relative[ selector ] ) { selector += parts.shift(); } set = posProcess( selector, set, seed ); } } } else { // Take a shortcut and set the context if the root selector is an ID // (but not if it'll be faster if the inner selector is an ID) if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML && Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) { ret = Sizzle.find( parts.shift(), context, contextXML ); context = ret.expr ? Sizzle.filter( ret.expr, ret.set )[0] : ret.set[0]; } if ( context ) { ret = seed ? { expr: parts.pop(), set: makeArray(seed) } : Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML ); set = ret.expr ? Sizzle.filter( ret.expr, ret.set ) : ret.set; if ( parts.length > 0 ) { checkSet = makeArray( set ); } else { prune = false; } while ( parts.length ) { cur = parts.pop(); pop = cur; if ( !Expr.relative[ cur ] ) { cur = ""; } else { pop = parts.pop(); } if ( pop == null ) { pop = context; } Expr.relative[ cur ]( checkSet, pop, contextXML ); } } else { checkSet = parts = []; } } if ( !checkSet ) { checkSet = set; } if ( !checkSet ) { Sizzle.error( cur || selector ); } if ( toString.call(checkSet) === "[object Array]" ) { if ( !prune ) { results.push.apply( results, checkSet ); } else if ( context && context.nodeType === 1 ) { for ( i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) { results.push( set[i] ); } } } else { for ( i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && checkSet[i].nodeType === 1 ) { results.push( set[i] ); } } } } else { makeArray( checkSet, results ); } if ( extra ) { Sizzle( extra, origContext, results, seed ); Sizzle.uniqueSort( results ); } return results; }; Sizzle.uniqueSort = function( results ) { if ( sortOrder ) { hasDuplicate = baseHasDuplicate; results.sort( sortOrder ); if ( hasDuplicate ) { for ( var i = 1; i < results.length; i++ ) { if ( results[i] === results[ i - 1 ] ) { results.splice( i--, 1 ); } } } } return results; }; Sizzle.matches = function( expr, set ) { return Sizzle( expr, null, null, set ); }; Sizzle.matchesSelector = function( node, expr ) { return Sizzle( expr, null, null, [node] ).length > 0; }; Sizzle.find = function( expr, context, isXML ) { var set, i, len, match, type, left; if ( !expr ) { return []; } for ( i = 0, len = Expr.order.length; i < len; i++ ) { type = Expr.order[i]; if ( (match = Expr.leftMatch[ type ].exec( expr )) ) { left = match[1]; match.splice( 1, 1 ); if ( left.substr( left.length - 1 ) !== "\\" ) { match[1] = (match[1] || "").replace( rBackslash, "" ); set = Expr.find[ type ]( match, context, isXML ); if ( set != null ) { expr = expr.replace( Expr.match[ type ], "" ); break; } } } } if ( !set ) { set = typeof context.getElementsByTagName !== "undefined" ? context.getElementsByTagName( "*" ) : []; } return { set: set, expr: expr }; }; Sizzle.filter = function( expr, set, inplace, not ) { var match, anyFound, type, found, item, filter, left, i, pass, old = expr, result = [], curLoop = set, isXMLFilter = set && set[0] && Sizzle.isXML( set[0] ); while ( expr && set.length ) { for ( type in Expr.filter ) { if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) { filter = Expr.filter[ type ]; left = match[1]; anyFound = false; match.splice(1,1); if ( left.substr( left.length - 1 ) === "\\" ) { continue; } if ( curLoop === result ) { result = []; } if ( Expr.preFilter[ type ] ) { match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter ); if ( !match ) { anyFound = found = true; } else if ( match === true ) { continue; } } if ( match ) { for ( i = 0; (item = curLoop[i]) != null; i++ ) { if ( item ) { found = filter( item, match, i, curLoop ); pass = not ^ found; if ( inplace && found != null ) { if ( pass ) { anyFound = true; } else { curLoop[i] = false; } } else if ( pass ) { result.push( item ); anyFound = true; } } } } if ( found !== undefined ) { if ( !inplace ) { curLoop = result; } expr = expr.replace( Expr.match[ type ], "" ); if ( !anyFound ) { return []; } break; } } } // Improper expression if ( expr === old ) { if ( anyFound == null ) { Sizzle.error( expr ); } else { break; } } old = expr; } return curLoop; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Utility function for retreiving the text value of an array of DOM nodes * @param {Array|Element} elem */ var getText = Sizzle.getText = function( elem ) { var i, node, nodeType = elem.nodeType, ret = ""; if ( nodeType ) { if ( nodeType === 1 || nodeType === 9 ) { // Use textContent || innerText for elements if ( typeof elem.textContent === 'string' ) { return elem.textContent; } else if ( typeof elem.innerText === 'string' ) { // Replace IE's carriage returns return elem.innerText.replace( rReturn, '' ); } else { // Traverse it's children for ( elem = elem.firstChild; elem; elem = elem.nextSibling) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } } else { // If no nodeType, this is expected to be an array for ( i = 0; (node = elem[i]); i++ ) { // Do not traverse comment nodes if ( node.nodeType !== 8 ) { ret += getText( node ); } } } return ret; }; var Expr = Sizzle.selectors = { order: [ "ID", "NAME", "TAG" ], match: { ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/, ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/, TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/, CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/, POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/, PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/ }, leftMatch: {}, attrMap: { "class": "className", "for": "htmlFor" }, attrHandle: { href: function( elem ) { return elem.getAttribute( "href" ); }, type: function( elem ) { return elem.getAttribute( "type" ); } }, relative: { "+": function(checkSet, part){ var isPartStr = typeof part === "string", isTag = isPartStr && !rNonWord.test( part ), isPartStrNotTag = isPartStr && !isTag; if ( isTag ) { part = part.toLowerCase(); } for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) { if ( (elem = checkSet[i]) ) { while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {} checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ? elem || false : elem === part; } } if ( isPartStrNotTag ) { Sizzle.filter( part, checkSet, true ); } }, ">": function( checkSet, part ) { var elem, isPartStr = typeof part === "string", i = 0, l = checkSet.length; if ( isPartStr && !rNonWord.test( part ) ) { part = part.toLowerCase(); for ( ; i < l; i++ ) { elem = checkSet[i]; if ( elem ) { var parent = elem.parentNode; checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false; } } } else { for ( ; i < l; i++ ) { elem = checkSet[i]; if ( elem ) { checkSet[i] = isPartStr ? elem.parentNode : elem.parentNode === part; } } if ( isPartStr ) { Sizzle.filter( part, checkSet, true ); } } }, "": function(checkSet, part, isXML){ var nodeCheck, doneName = done++, checkFn = dirCheck; if ( typeof part === "string" && !rNonWord.test( part ) ) { part = part.toLowerCase(); nodeCheck = part; checkFn = dirNodeCheck; } checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML ); }, "~": function( checkSet, part, isXML ) { var nodeCheck, doneName = done++, checkFn = dirCheck; if ( typeof part === "string" && !rNonWord.test( part ) ) { part = part.toLowerCase(); nodeCheck = part; checkFn = dirNodeCheck; } checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML ); } }, find: { ID: function( match, context, isXML ) { if ( typeof context.getElementById !== "undefined" && !isXML ) { var m = context.getElementById(match[1]); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } }, NAME: function( match, context ) { if ( typeof context.getElementsByName !== "undefined" ) { var ret = [], results = context.getElementsByName( match[1] ); for ( var i = 0, l = results.length; i < l; i++ ) { if ( results[i].getAttribute("name") === match[1] ) { ret.push( results[i] ); } } return ret.length === 0 ? null : ret; } }, TAG: function( match, context ) { if ( typeof context.getElementsByTagName !== "undefined" ) { return context.getElementsByTagName( match[1] ); } } }, preFilter: { CLASS: function( match, curLoop, inplace, result, not, isXML ) { match = " " + match[1].replace( rBackslash, "" ) + " "; if ( isXML ) { return match; } for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) { if ( elem ) { if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) { if ( !inplace ) { result.push( elem ); } } else if ( inplace ) { curLoop[i] = false; } } } return false; }, ID: function( match ) { return match[1].replace( rBackslash, "" ); }, TAG: function( match, curLoop ) { return match[1].replace( rBackslash, "" ).toLowerCase(); }, CHILD: function( match ) { if ( match[1] === "nth" ) { if ( !match[2] ) { Sizzle.error( match[0] ); } match[2] = match[2].replace(/^\+|\s*/g, ''); // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6' var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec( match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" || !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]); // calculate the numbers (first)n+(last) including if they are negative match[2] = (test[1] + (test[2] || 1)) - 0; match[3] = test[3] - 0; } else if ( match[2] ) { Sizzle.error( match[0] ); } // TODO: Move to normal caching system match[0] = done++; return match; }, ATTR: function( match, curLoop, inplace, result, not, isXML ) { var name = match[1] = match[1].replace( rBackslash, "" ); if ( !isXML && Expr.attrMap[name] ) { match[1] = Expr.attrMap[name]; } // Handle if an un-quoted value was used match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" ); if ( match[2] === "~=" ) { match[4] = " " + match[4] + " "; } return match; }, PSEUDO: function( match, curLoop, inplace, result, not ) { if ( match[1] === "not" ) { // If we're dealing with a complex expression, or a simple one if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) { match[3] = Sizzle(match[3], null, null, curLoop); } else { var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not); if ( !inplace ) { result.push.apply( result, ret ); } return false; } } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) { return true; } return match; }, POS: function( match ) { match.unshift( true ); return match; } }, filters: { enabled: function( elem ) { return elem.disabled === false && elem.type !== "hidden"; }, disabled: function( elem ) { return elem.disabled === true; }, checked: function( elem ) { return elem.checked === true; }, selected: function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, parent: function( elem ) { return !!elem.firstChild; }, empty: function( elem ) { return !elem.firstChild; }, has: function( elem, i, match ) { return !!Sizzle( match[3], elem ).length; }, header: function( elem ) { return (/h\d/i).test( elem.nodeName ); }, text: function( elem ) { var attr = elem.getAttribute( "type" ), type = elem.type; // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) // use getAttribute instead to test this case return elem.nodeName.toLowerCase() === "input" && "text" === type && ( attr === type || attr === null ); }, radio: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "radio" === elem.type; }, checkbox: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "checkbox" === elem.type; }, file: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "file" === elem.type; }, password: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "password" === elem.type; }, submit: function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && "submit" === elem.type; }, image: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "image" === elem.type; }, reset: function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && "reset" === elem.type; }, button: function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && "button" === elem.type || name === "button"; }, input: function( elem ) { return (/input|select|textarea|button/i).test( elem.nodeName ); }, focus: function( elem ) { return elem === elem.ownerDocument.activeElement; } }, setFilters: { first: function( elem, i ) { return i === 0; }, last: function( elem, i, match, array ) { return i === array.length - 1; }, even: function( elem, i ) { return i % 2 === 0; }, odd: function( elem, i ) { return i % 2 === 1; }, lt: function( elem, i, match ) { return i < match[3] - 0; }, gt: function( elem, i, match ) { return i > match[3] - 0; }, nth: function( elem, i, match ) { return match[3] - 0 === i; }, eq: function( elem, i, match ) { return match[3] - 0 === i; } }, filter: { PSEUDO: function( elem, match, i, array ) { var name = match[1], filter = Expr.filters[ name ]; if ( filter ) { return filter( elem, i, match, array ); } else if ( name === "contains" ) { return (elem.textContent || elem.innerText || getText([ elem ]) || "").indexOf(match[3]) >= 0; } else if ( name === "not" ) { var not = match[3]; for ( var j = 0, l = not.length; j < l; j++ ) { if ( not[j] === elem ) { return false; } } return true; } else { Sizzle.error( name ); } }, CHILD: function( elem, match ) { var first, last, doneName, parent, cache, count, diff, type = match[1], node = elem; switch ( type ) { case "only": case "first": while ( (node = node.previousSibling) ) { if ( node.nodeType === 1 ) { return false; } } if ( type === "first" ) { return true; } node = elem; case "last": while ( (node = node.nextSibling) ) { if ( node.nodeType === 1 ) { return false; } } return true; case "nth": first = match[2]; last = match[3]; if ( first === 1 && last === 0 ) { return true; } doneName = match[0]; parent = elem.parentNode; if ( parent && (parent[ expando ] !== doneName || !elem.nodeIndex) ) { count = 0; for ( node = parent.firstChild; node; node = node.nextSibling ) { if ( node.nodeType === 1 ) { node.nodeIndex = ++count; } } parent[ expando ] = doneName; } diff = elem.nodeIndex - last; if ( first === 0 ) { return diff === 0; } else { return ( diff % first === 0 && diff / first >= 0 ); } } }, ID: function( elem, match ) { return elem.nodeType === 1 && elem.getAttribute("id") === match; }, TAG: function( elem, match ) { return (match === "*" && elem.nodeType === 1) || !!elem.nodeName && elem.nodeName.toLowerCase() === match; }, CLASS: function( elem, match ) { return (" " + (elem.className || elem.getAttribute("class")) + " ") .indexOf( match ) > -1; }, ATTR: function( elem, match ) { var name = match[1], result = Sizzle.attr ? Sizzle.attr( elem, name ) : Expr.attrHandle[ name ] ? Expr.attrHandle[ name ]( elem ) : elem[ name ] != null ? elem[ name ] : elem.getAttribute( name ), value = result + "", type = match[2], check = match[4]; return result == null ? type === "!=" : !type && Sizzle.attr ? result != null : type === "=" ? value === check : type === "*=" ? value.indexOf(check) >= 0 : type === "~=" ? (" " + value + " ").indexOf(check) >= 0 : !check ? value && result !== false : type === "!=" ? value !== check : type === "^=" ? value.indexOf(check) === 0 : type === "$=" ? value.substr(value.length - check.length) === check : type === "|=" ? value === check || value.substr(0, check.length + 1) === check + "-" : false; }, POS: function( elem, match, i, array ) { var name = match[2], filter = Expr.setFilters[ name ]; if ( filter ) { return filter( elem, i, match, array ); } } } }; var origPOS = Expr.match.POS, fescape = function(all, num){ return "\\" + (num - 0 + 1); }; for ( var type in Expr.match ) { Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) ); Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) ); } var makeArray = function( array, results ) { array = Array.prototype.slice.call( array, 0 ); if ( results ) { results.push.apply( results, array ); return results; } return array; }; // Perform a simple check to determine if the browser is capable of // converting a NodeList to an array using builtin methods. // Also verifies that the returned array holds DOM nodes // (which is not the case in the Blackberry browser) try { Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType; // Provide a fallback method if it does not work } catch( e ) { makeArray = function( array, results ) { var i = 0, ret = results || []; if ( toString.call(array) === "[object Array]" ) { Array.prototype.push.apply( ret, array ); } else { if ( typeof array.length === "number" ) { for ( var l = array.length; i < l; i++ ) { ret.push( array[i] ); } } else { for ( ; array[i]; i++ ) { ret.push( array[i] ); } } } return ret; }; } var sortOrder, siblingCheck; if ( document.documentElement.compareDocumentPosition ) { sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; return 0; } if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) { return a.compareDocumentPosition ? -1 : 1; } return a.compareDocumentPosition(b) & 4 ? -1 : 1; }; } else { sortOrder = function( a, b ) { // The nodes are identical, we can exit early if ( a === b ) { hasDuplicate = true; return 0; // Fallback to using sourceIndex (in IE) if it's available on both nodes } else if ( a.sourceIndex && b.sourceIndex ) { return a.sourceIndex - b.sourceIndex; } var al, bl, ap = [], bp = [], aup = a.parentNode, bup = b.parentNode, cur = aup; // If the nodes are siblings (or identical) we can do a quick check if ( aup === bup ) { return siblingCheck( a, b ); // If no parents were found then the nodes are disconnected } else if ( !aup ) { return -1; } else if ( !bup ) { return 1; } // Otherwise they're somewhere else in the tree so we need // to build up a full list of the parentNodes for comparison while ( cur ) { ap.unshift( cur ); cur = cur.parentNode; } cur = bup; while ( cur ) { bp.unshift( cur ); cur = cur.parentNode; } al = ap.length; bl = bp.length; // Start walking down the tree looking for a discrepancy for ( var i = 0; i < al && i < bl; i++ ) { if ( ap[i] !== bp[i] ) { return siblingCheck( ap[i], bp[i] ); } } // We ended someplace up the tree so do a sibling check return i === al ? siblingCheck( a, bp[i], -1 ) : siblingCheck( ap[i], b, 1 ); }; siblingCheck = function( a, b, ret ) { if ( a === b ) { return ret; } var cur = a.nextSibling; while ( cur ) { if ( cur === b ) { return -1; } cur = cur.nextSibling; } return 1; }; } // Check to see if the browser returns elements by name when // querying by getElementById (and provide a workaround) (function(){ // We're going to inject a fake input element with a specified name var form = document.createElement("div"), id = "script" + (new Date()).getTime(), root = document.documentElement; form.innerHTML = "<a name='" + id + "'/>"; // Inject it into the root element, check its status, and remove it quickly root.insertBefore( form, root.firstChild ); // The workaround has to do additional checks after a getElementById // Which slows things down for other browsers (hence the branching) if ( document.getElementById( id ) ) { Expr.find.ID = function( match, context, isXML ) { if ( typeof context.getElementById !== "undefined" && !isXML ) { var m = context.getElementById(match[1]); return m ? m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? [m] : undefined : []; } }; Expr.filter.ID = function( elem, match ) { var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); return elem.nodeType === 1 && node && node.nodeValue === match; }; } root.removeChild( form ); // release memory in IE root = form = null; })(); (function(){ // Check to see if the browser returns only elements // when doing getElementsByTagName("*") // Create a fake element var div = document.createElement("div"); div.appendChild( document.createComment("") ); // Make sure no comments are found if ( div.getElementsByTagName("*").length > 0 ) { Expr.find.TAG = function( match, context ) { var results = context.getElementsByTagName( match[1] ); // Filter out possible comments if ( match[1] === "*" ) { var tmp = []; for ( var i = 0; results[i]; i++ ) { if ( results[i].nodeType === 1 ) { tmp.push( results[i] ); } } results = tmp; } return results; }; } // Check to see if an attribute returns normalized href attributes div.innerHTML = "<a href='#'></a>"; if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" && div.firstChild.getAttribute("href") !== "#" ) { Expr.attrHandle.href = function( elem ) { return elem.getAttribute( "href", 2 ); }; } // release memory in IE div = null; })(); if ( document.querySelectorAll ) { (function(){ var oldSizzle = Sizzle, div = document.createElement("div"), id = "__sizzle__"; div.innerHTML = "<p class='TEST'></p>"; // Safari can't handle uppercase or unicode characters when // in quirks mode. if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) { return; } Sizzle = function( query, context, extra, seed ) { context = context || document; // Only use querySelectorAll on non-XML documents // (ID selectors don't work in non-HTML documents) if ( !seed && !Sizzle.isXML(context) ) { // See if we find a selector to speed up var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query ); if ( match && (context.nodeType === 1 || context.nodeType === 9) ) { // Speed-up: Sizzle("TAG") if ( match[1] ) { return makeArray( context.getElementsByTagName( query ), extra ); // Speed-up: Sizzle(".CLASS") } else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) { return makeArray( context.getElementsByClassName( match[2] ), extra ); } } if ( context.nodeType === 9 ) { // Speed-up: Sizzle("body") // The body element only exists once, optimize finding it if ( query === "body" && context.body ) { return makeArray( [ context.body ], extra ); // Speed-up: Sizzle("#ID") } else if ( match && match[3] ) { var elem = context.getElementById( match[3] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id === match[3] ) { return makeArray( [ elem ], extra ); } } else { return makeArray( [], extra ); } } try { return makeArray( context.querySelectorAll(query), extra ); } catch(qsaError) {} // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements } else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { var oldContext = context, old = context.getAttribute( "id" ), nid = old || id, hasParent = context.parentNode, relativeHierarchySelector = /^\s*[+~]/.test( query ); if ( !old ) { context.setAttribute( "id", nid ); } else { nid = nid.replace( /'/g, "\\$&" ); } if ( relativeHierarchySelector && hasParent ) { context = context.parentNode; } try { if ( !relativeHierarchySelector || hasParent ) { return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra ); } } catch(pseudoError) { } finally { if ( !old ) { oldContext.removeAttribute( "id" ); } } } } return oldSizzle(query, context, extra, seed); }; for ( var prop in oldSizzle ) { Sizzle[ prop ] = oldSizzle[ prop ]; } // release memory in IE div = null; })(); } (function(){ var html = document.documentElement, matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector; if ( matches ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9 fails this) var disconnectedMatch = !matches.call( document.createElement( "div" ), "div" ), pseudoWorks = false; try { // This should fail with an exception // Gecko does not error, returns false instead matches.call( document.documentElement, "[test!='']:sizzle" ); } catch( pseudoError ) { pseudoWorks = true; } Sizzle.matchesSelector = function( node, expr ) { // Make sure that attribute selectors are quoted expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']"); if ( !Sizzle.isXML( node ) ) { try { if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) { var ret = matches.call( node, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || !disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9, so check for that node.document && node.document.nodeType !== 11 ) { return ret; } } } catch(e) {} } return Sizzle(expr, null, null, [node]).length > 0; }; } })(); (function(){ var div = document.createElement("div"); div.innerHTML = "<div class='test e'></div><div class='test'></div>"; // Opera can't find a second classname (in 9.6) // Also, make sure that getElementsByClassName actually exists if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) { return; } // Safari caches class attributes, doesn't catch changes (in 3.2) div.lastChild.className = "e"; if ( div.getElementsByClassName("e").length === 1 ) { return; } Expr.order.splice(1, 0, "CLASS"); Expr.find.CLASS = function( match, context, isXML ) { if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) { return context.getElementsByClassName(match[1]); } }; // release memory in IE div = null; })(); function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { var match = false; elem = elem[dir]; while ( elem ) { if ( elem[ expando ] === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 && !isXML ){ elem[ expando ] = doneName; elem.sizset = i; } if ( elem.nodeName.toLowerCase() === cur ) { match = elem; break; } elem = elem[dir]; } checkSet[i] = match; } } } function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { var match = false; elem = elem[dir]; while ( elem ) { if ( elem[ expando ] === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 ) { if ( !isXML ) { elem[ expando ] = doneName; elem.sizset = i; } if ( typeof cur !== "string" ) { if ( elem === cur ) { match = true; break; } } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) { match = elem; break; } } elem = elem[dir]; } checkSet[i] = match; } } } if ( document.documentElement.contains ) { Sizzle.contains = function( a, b ) { return a !== b && (a.contains ? a.contains(b) : true); }; } else if ( document.documentElement.compareDocumentPosition ) { Sizzle.contains = function( a, b ) { return !!(a.compareDocumentPosition(b) & 16); }; } else { Sizzle.contains = function() { return false; }; } Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; var posProcess = function( selector, context, seed ) { var match, tmpSet = [], later = "", root = context.nodeType ? [context] : context; // Position selectors must be done after the filter // And so must :not(positional) so we move all PSEUDOs to the end while ( (match = Expr.match.PSEUDO.exec( selector )) ) { later += match[0]; selector = selector.replace( Expr.match.PSEUDO, "" ); } selector = Expr.relative[selector] ? selector + "*" : selector; for ( var i = 0, l = root.length; i < l; i++ ) { Sizzle( selector, root[i], tmpSet, seed ); } return Sizzle.filter( later, tmpSet ); }; // EXPOSE // Override sizzle attribute retrieval Sizzle.attr = jQuery.attr; Sizzle.selectors.attrMap = {}; jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.filters; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; })(); var runtil = /Until$/, rparentsprev = /^(?:parents|prevUntil|prevAll)/, // Note: This RegExp should be improved, or likely pulled from Sizzle rmultiselector = /,/, isSimple = /^.[^:#\[\.,]*$/, slice = Array.prototype.slice, POS = jQuery.expr.match.POS, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend({ find: function( selector ) { var self = this, i, l; if ( typeof selector !== "string" ) { return jQuery( selector ).filter(function() { for ( i = 0, l = self.length; i < l; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }); } var ret = this.pushStack( "", "find", selector ), length, n, r; for ( i = 0, l = this.length; i < l; i++ ) { length = ret.length; jQuery.find( selector, this[i], ret ); if ( i > 0 ) { // Make sure that the results are unique for ( n = length; n < ret.length; n++ ) { for ( r = 0; r < length; r++ ) { if ( ret[r] === ret[n] ) { ret.splice(n--, 1); break; } } } } } return ret; }, has: function( target ) { var targets = jQuery( target ); return this.filter(function() { for ( var i = 0, l = targets.length; i < l; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, not: function( selector ) { return this.pushStack( winnow(this, selector, false), "not", selector); }, filter: function( selector ) { return this.pushStack( winnow(this, selector, true), "filter", selector ); }, is: function( selector ) { return !!selector && ( typeof selector === "string" ? // If this is a positional selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". POS.test( selector ) ? jQuery( selector, this.context ).index( this[0] ) >= 0 : jQuery.filter( selector, this ).length > 0 : this.filter( selector ).length > 0 ); }, closest: function( selectors, context ) { var ret = [], i, l, cur = this[0]; // Array (deprecated as of jQuery 1.7) if ( jQuery.isArray( selectors ) ) { var level = 1; while ( cur && cur.ownerDocument && cur !== context ) { for ( i = 0; i < selectors.length; i++ ) { if ( jQuery( cur ).is( selectors[ i ] ) ) { ret.push({ selector: selectors[ i ], elem: cur, level: level }); } } cur = cur.parentNode; level++; } return ret; } // String var pos = POS.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( i = 0, l = this.length; i < l; i++ ) { cur = this[i]; while ( cur ) { if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { ret.push( cur ); break; } else { cur = cur.parentNode; if ( !cur || !cur.ownerDocument || cur === context || cur.nodeType === 11 ) { break; } } } } ret = ret.length > 1 ? jQuery.unique( ret ) : ret; return this.pushStack( ret, "closest", selectors ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return jQuery.inArray( this[0], jQuery( elem ) ); } // Locate the position of the desired element return jQuery.inArray( // If it receives a jQuery object, the first element is used elem.jquery ? elem[0] : elem, this ); }, add: function( selector, context ) { var set = typeof selector === "string" ? jQuery( selector, context ) : jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), all = jQuery.merge( this.get(), set ); return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ? all : jQuery.unique( all ) ); }, andSelf: function() { return this.add( this.prevObject ); } }); // A painfully simple check to see if an element is disconnected // from a document (should be improved, where feasible). function isDisconnected( node ) { return !node || !node.parentNode || node.parentNode.nodeType === 11; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return jQuery.nth( elem, 2, "nextSibling" ); }, prev: function( elem ) { return jQuery.nth( elem, 2, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( elem.parentNode.firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return jQuery.nodeName( elem, "iframe" ) ? elem.contentDocument || elem.contentWindow.document : jQuery.makeArray( elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var ret = jQuery.map( this, fn, until ); if ( !runtil.test( name ) ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) { ret = ret.reverse(); } return this.pushStack( ret, name, slice.call( arguments ).join(",") ); }; }); jQuery.extend({ filter: function( expr, elems, not ) { if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 ? jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : jQuery.find.matches(expr, elems); }, dir: function( elem, dir, until ) { var matched = [], cur = elem[ dir ]; while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { if ( cur.nodeType === 1 ) { matched.push( cur ); } cur = cur[dir]; } return matched; }, nth: function( cur, result, dir, elem ) { result = result || 1; var num = 0; for ( ; cur; cur = cur[dir] ) { if ( cur.nodeType === 1 && ++num === result ) { break; } } return cur; }, sibling: function( n, elem ) { var r = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { r.push( n ); } } return r; } }); // Implement the identical functionality for filter and not function winnow( elements, qualifier, keep ) { // Can't pass null or undefined to indexOf in Firefox 4 // Set to 0 to skip string check qualifier = qualifier || 0; if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep(elements, function( elem, i ) { var retVal = !!qualifier.call( elem, i, elem ); return retVal === keep; }); } else if ( qualifier.nodeType ) { return jQuery.grep(elements, function( elem, i ) { return ( elem === qualifier ) === keep; }); } else if ( typeof qualifier === "string" ) { var filtered = jQuery.grep(elements, function( elem ) { return elem.nodeType === 1; }); if ( isSimple.test( qualifier ) ) { return jQuery.filter(qualifier, filtered, !keep); } else { qualifier = jQuery.filter( qualifier, filtered ); } } return jQuery.grep(elements, function( elem, i ) { return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep; }); } function createSafeFragment( document ) { var list = nodeNames.split( "|" ), safeFrag = document.createDocumentFragment(); if ( safeFrag.createElement ) { while ( list.length ) { safeFrag.createElement( list.pop() ); } } return safeFrag; } var nodeNames = "abbr|article|aside|audio|canvas|datalist|details|figcaption|figure|footer|" + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g, rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style)/i, rnocache = /<(?:script|object|embed|option|style)/i, rnoshimcache = new RegExp("<(?:" + nodeNames + ")", "i"), // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /\/(java|ecma)script/i, rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)/, wrapMap = { option: [ 1, "<select multiple='multiple'>", "</select>" ], legend: [ 1, "<fieldset>", "</fieldset>" ], thead: [ 1, "<table>", "</table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], area: [ 1, "<map>", "</map>" ], _default: [ 0, "", "" ] }, safeFragment = createSafeFragment( document ); wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; // IE can't serialize <link> and <script> tags normally if ( !jQuery.support.htmlSerialize ) { wrapMap._default = [ 1, "div<div>", "</div>" ]; } jQuery.fn.extend({ text: function( 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 ) { var isFunction = jQuery.isFunction( html ); return this.each(function(i) { jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); }, append: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 ) { this.appendChild( elem ); } }); }, prepend: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 ) { this.insertBefore( elem, this.firstChild ); } }); }, before: function() { if ( this[0] && this[0].parentNode ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this ); }); } else if ( arguments.length ) { var set = jQuery.clean( arguments ); set.push.apply( set, this.toArray() ); return this.pushStack( set, "before", arguments ); } }, after: function() { if ( this[0] && this[0].parentNode ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this.nextSibling ); }); } else if ( arguments.length ) { var set = this.pushStack( this, "after", arguments ); set.push.apply( set, jQuery.clean(arguments) ); return set; } }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { for ( var i = 0, elem; (elem = this[i]) != null; i++ ) { if ( !selector || jQuery.filter( selector, [ elem ] ).length ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); jQuery.cleanData( [ elem ] ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } } } return this; }, empty: function() { for ( var i = 0, elem; (elem = this[i]) != null; i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function () { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { 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" && !rnoInnerhtml.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.length ? this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) : this; } }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, table, callback ) { var results, first, fragment, parent, value = args[0], scripts = []; // We can't cloneNode fragments that contain checked, in WebKit if ( !jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test( value ) ) { return this.each(function() { jQuery(this).domManip( args, table, callback, true ); }); } if ( jQuery.isFunction(value) ) { return this.each(function(i) { var self = jQuery(this); args[0] = value.call(this, i, table ? self.html() : undefined); self.domManip( args, table, callback ); }); } if ( this[0] ) { parent = value && value.parentNode; // If we're in a fragment, just use that instead of building a new one if ( jQuery.support.parentNode && parent && parent.nodeType === 11 && parent.childNodes.length === this.length ) { results = { fragment: parent }; } else { results = jQuery.buildFragment( args, this, scripts ); } fragment = results.fragment; if ( fragment.childNodes.length === 1 ) { first = fragment = fragment.firstChild; } else { first = fragment.firstChild; } if ( first ) { table = table && jQuery.nodeName( first, "tr" ); for ( var i = 0, l = this.length, lastIndex = l - 1; i < l; i++ ) { callback.call( table ? root(this[i], first) : this[i], // Make sure that we do not leak memory by inadvertently discarding // the original fragment (which might have attached data) instead of // using it; in addition, use the original fragment object for the last // item instead of first because it can end up being emptied incorrectly // in certain situations (Bug #8070). // Fragments from the fragment cache must always be cloned and never used // in place. results.cacheable || ( l > 1 && i < lastIndex ) ? jQuery.clone( fragment, true, true ) : fragment ); } } if ( scripts.length ) { jQuery.each( scripts, 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( 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 ].namespace ? "." : "" ) + events[ type ][ i ].namespace, events[ type ][ i ], events[ type ][ i ].data ); } } } // make the cloned public data object a copy from the original if ( curData.data ) { curData.data = jQuery.extend( {}, curData.data ); } } function cloneFixAttributes( src, dest ) { var nodeName; // We do not need to do anything for non-Elements if ( dest.nodeType !== 1 ) { return; } // clearAttributes removes the attributes, which we don't want, // but also removes the attachEvent events, which we *do* want if ( dest.clearAttributes ) { dest.clearAttributes(); } // mergeAttributes, in contrast, only merges back on the // original attributes, not the events if ( dest.mergeAttributes ) { dest.mergeAttributes( src ); } nodeName = dest.nodeName.toLowerCase(); // IE6-8 fail to clone children inside object elements that use // the proprietary classid attribute value (rather than the type // attribute) to identify the type of content to display if ( nodeName === "object" ) { dest.outerHTML = src.outerHTML; } else if ( nodeName === "input" && (src.type === "checkbox" || src.type === "radio") ) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set if ( src.checked ) { dest.defaultChecked = dest.checked = src.checked; } // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if ( dest.value !== src.value ) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if ( nodeName === "option" ) { dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } // Event data gets referenced instead of copied if the expando // gets copied too dest.removeAttribute( jQuery.expando ); } jQuery.buildFragment = function( args, nodes, scripts ) { var fragment, cacheable, cacheresults, doc, first = args[ 0 ]; // nodes may contain either an explicit document object, // a jQuery collection or context object. // If nodes[0] contains a valid object to assign to doc if ( nodes && nodes[0] ) { doc = nodes[0].ownerDocument || nodes[0]; } // Ensure that an attr object doesn't incorrectly stand in as a document object // Chrome and Firefox seem to allow this to occur and will throw exception // Fixes #8950 if ( !doc.createDocumentFragment ) { doc = document; } // Only cache "small" (1/2 KB) HTML strings that are associated with the main document // Cloning options loses the selected state, so don't cache them // IE 6 doesn't like it when you put <object> or <embed> elements in a fragment // Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache // Lastly, IE6,7,8 will not correctly reuse cached fragments that were created from unknown elems #10501 if ( args.length === 1 && typeof first === "string" && first.length < 512 && doc === document && first.charAt(0) === "<" && !rnocache.test( first ) && (jQuery.support.checkClone || !rchecked.test( first )) && (jQuery.support.html5Clone || !rnoshimcache.test( first )) ) { cacheable = true; cacheresults = jQuery.fragments[ first ]; if ( cacheresults && cacheresults !== 1 ) { fragment = cacheresults; } } if ( !fragment ) { fragment = doc.createDocumentFragment(); jQuery.clean( args, doc, fragment, scripts ); } if ( cacheable ) { jQuery.fragments[ first ] = cacheresults ? fragment : 1; } return { fragment: fragment, cacheable: cacheable }; }; jQuery.fragments = {}; jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var ret = [], insert = jQuery( selector ), parent = this.length === 1 && this[0].parentNode; if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) { insert[ original ]( this[0] ); return this; } else { for ( var i = 0, l = insert.length; i < l; i++ ) { var elems = ( i > 0 ? this.clone(true) : this ).get(); jQuery( insert[i] )[ original ]( elems ); ret = ret.concat( elems ); } return this.pushStack( ret, name, insert.selector ); } }; }); function getAll( elem ) { if ( typeof elem.getElementsByTagName !== "undefined" ) { return elem.getElementsByTagName( "*" ); } else if ( typeof elem.querySelectorAll !== "undefined" ) { return elem.querySelectorAll( "*" ); } else { return []; } } // Used in clean, fixes the defaultChecked property function fixDefaultChecked( elem ) { if ( elem.type === "checkbox" || elem.type === "radio" ) { elem.defaultChecked = elem.checked; } } // Finds all inputs and passes them to fixDefaultChecked function findInputs( elem ) { var nodeName = ( elem.nodeName || "" ).toLowerCase(); if ( nodeName === "input" ) { fixDefaultChecked( elem ); // Skip scripts, get other children } else if ( nodeName !== "script" && typeof elem.getElementsByTagName !== "undefined" ) { jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked ); } } // Derived From: http://www.iecss.com/shimprove/javascript/shimprove.1-0-1.js function shimCloneNode( elem ) { var div = document.createElement( "div" ); safeFragment.appendChild( div ); div.innerHTML = elem.outerHTML; return div.firstChild; } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var srcElements, destElements, i, // IE<=8 does not properly clone detached, unknown element nodes clone = jQuery.support.html5Clone || !rnoshimcache.test( "<" + elem.nodeName ) ? elem.cloneNode( true ) : shimCloneNode( elem ); if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { // IE copies events bound via attachEvent when using cloneNode. // Calling detachEvent on the clone will also remove the events // from the original. In order to get around this, we use some // proprietary methods to clear the events. Thanks to MooTools // guys for this hotness. cloneFixAttributes( elem, clone ); // Using Sizzle here is crazy slow, so we use getElementsByTagName instead srcElements = getAll( elem ); destElements = getAll( clone ); // Weird iteration because IE will replace the length property // with an element if you are cloning the body and one of the // elements on the page has a name or id of "length" for ( i = 0; srcElements[i]; ++i ) { // Ensure that the destination node is not null; Fixes #9587 if ( destElements[i] ) { cloneFixAttributes( srcElements[i], destElements[i] ); } } } // Copy the events from the original to the clone if ( dataAndEvents ) { cloneCopyEvent( elem, clone ); if ( deepDataAndEvents ) { srcElements = getAll( elem ); destElements = getAll( clone ); for ( i = 0; srcElements[i]; ++i ) { cloneCopyEvent( srcElements[i], destElements[i] ); } } } srcElements = destElements = null; // Return the cloned set return clone; }, clean: function( elems, context, fragment, scripts ) { var checkScriptType; 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 = [], j; for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { if ( typeof elem === "number" ) { elem += ""; } if ( !elem ) { continue; } // Convert html string into DOM nodes if ( typeof elem === "string" ) { if ( !rhtml.test( elem ) ) { elem = context.createTextNode( elem ); } else { // Fix "XHTML"-style tags in all browsers elem = elem.replace(rxhtmlTag, "<$1></$2>"); // Trim whitespace, otherwise indexOf won't work as expected var tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(), wrap = wrapMap[ tag ] || wrapMap._default, depth = wrap[0], div = context.createElement("div"); // Append wrapper element to unknown element safe doc fragment if ( context === document ) { // Use the fragment we've already created for this document safeFragment.appendChild( div ); } else { // Use a fragment created with the owner document createSafeFragment( context ).appendChild( div ); } // Go to html and back, then peel off extra wrappers div.innerHTML = wrap[1] + elem + wrap[2]; // Move to the right depth while ( depth-- ) { div = div.lastChild; } // Remove IE's autoinserted <tbody> from table fragments if ( !jQuery.support.tbody ) { // String was a <table>, *may* have spurious <tbody> var hasBody = rtbody.test(elem), tbody = tag === "table" && !hasBody ? div.firstChild && div.firstChild.childNodes : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !hasBody ? div.childNodes : []; for ( j = tbody.length - 1; j >= 0 ; --j ) { if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) { tbody[ j ].parentNode.removeChild( tbody[ j ] ); } } } // IE completely kills leading whitespace when innerHTML is used if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild ); } elem = div.childNodes; } } // Resets defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) var len; if ( !jQuery.support.appendChecked ) { if ( elem[0] && typeof (len = elem.length) === "number" ) { for ( j = 0; j < len; j++ ) { findInputs( elem[j] ); } } else { findInputs( elem ); } } if ( elem.nodeType ) { ret.push( elem ); } else { ret = jQuery.merge( ret, elem ); } } if ( fragment ) { checkScriptType = function( elem ) { return !elem.type || rscriptType.test( elem.type ); }; for ( i = 0; ret[i]; i++ ) { 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 ) { var jsTags = jQuery.grep( ret[i].getElementsByTagName( "script" ), checkScriptType ); ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) ); } 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 ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } // Null the DOM reference to avoid IE6/7/8 leak (#7054) if ( data.handle ) { data.handle.elem = null; } } if ( deleteExpando ) { delete elem[ jQuery.expando ]; } else if ( elem.removeAttribute ) { elem.removeAttribute( jQuery.expando ); } delete cache[ id ]; } } } }); 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 || "" ).replace( rcleanScript, "/*$0*/" ) ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } } var ralpha = /alpha\([^)]*\)/i, ropacity = /opacity=([^)]*)/, // fixed for IE9, see #8346 rupper = /([A-Z]|^ms)/g, rnumpx = /^-?\d+(?:px)?$/i, rnum = /^-?\d/, rrelNum = /^([\-+])=([\-+.\de]+)/, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssWidth = [ "Left", "Right" ], cssHeight = [ "Top", "Bottom" ], curCSS, getComputedStyle, currentStyle; 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: { "fillOpacity": true, "fontWeight": true, "lineHeight": true, "opacity": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, origName = jQuery.camelCase( name ), style = elem.style, hooks = jQuery.cssHooks[ origName ]; name = jQuery.cssProps[ origName ] || origName; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && (ret = rrelNum.exec( value )) ) { value = ( +( ret[1] + 1) * +ret[2] ) + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // Make sure that NaN and null values aren't set. See: #7116 if ( value == null || type === "number" && isNaN( value ) ) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value )) !== undefined ) { // Wrapped to prevent IE from throwing errors when 'invalid' values are provided // Fixes bug #5509 try { style[ name ] = value; } catch(e) {} } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra ) { var ret, hooks; // Make sure that we're working with the right name name = jQuery.camelCase( name ); hooks = jQuery.cssHooks[ name ]; name = jQuery.cssProps[ name ] || name; // cssFloat needs a special treatment if ( name === "cssFloat" ) { name = "float"; } // If a hook was provided get the computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, true, extra )) !== undefined ) { return ret; // Otherwise, if a way to get the computed value exists, use that } else if ( curCSS ) { return curCSS( elem, name ); } }, // A method for quickly swapping in/out CSS properties to get correct calculations swap: function( elem, options, callback ) { var old = {}; // 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 ]; } } }); // 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 ) { return getWH( elem, name, extra ); } else { jQuery.swap( elem, cssShow, function() { val = getWH( elem, name, extra ); }); } return val; } }, 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, currentStyle = elem.currentStyle, opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "", filter = currentStyle && currentStyle.filter || style.filter || ""; // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652 if ( value >= 1 && jQuery.trim( filter.replace( ralpha, "" ) ) === "" ) { // Setting style.filter to null, "" & " " still leave "filter:" in the cssText // if "filter:" is present at all, clearType is disabled, we want to avoid this // style.removeAttribute is IE Only, but so apparently is this code path... style.removeAttribute( "filter" ); // if there there is no filter style applied in a css rule, we are done if ( currentStyle && !currentStyle.filter ) { return; } } // otherwise, set new filter values style.filter = ralpha.test( filter ) ? filter.replace( ralpha, opacity ) : filter + " " + opacity; } }; } jQuery(function() { // This hook cannot be added until DOM ready because the support test // for it is not run until after DOM ready if ( !jQuery.support.reliableMarginRight ) { jQuery.cssHooks.marginRight = { get: function( elem, computed ) { // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // Work around by temporarily setting element display to inline-block var ret; jQuery.swap( elem, { "display": "inline-block" }, function() { if ( computed ) { ret = curCSS( elem, "margin-right", "marginRight" ); } else { ret = elem.style.marginRight; } }); return ret; } }; } }); if ( document.defaultView && document.defaultView.getComputedStyle ) { getComputedStyle = function( elem, name ) { var ret, defaultView, computedStyle; name = name.replace( rupper, "-$1" ).toLowerCase(); if ( (defaultView = elem.ownerDocument.defaultView) && (computedStyle = defaultView.getComputedStyle( elem, null )) ) { ret = computedStyle.getPropertyValue( name ); if ( ret === "" && !jQuery.contains( elem.ownerDocument.documentElement, elem ) ) { ret = jQuery.style( elem, name ); } } return ret; }; } if ( document.documentElement.currentStyle ) { currentStyle = function( elem, name ) { var left, rsLeft, uncomputed, ret = elem.currentStyle && elem.currentStyle[ name ], style = elem.style; // Avoid setting ret to empty string here // so we don't default to auto if ( ret === null && style && (uncomputed = style[ name ]) ) { ret = uncomputed; } // From the awesome hack by Dean Edwards // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 // If we're not dealing with a regular pixel number // but a number that has a weird ending, we need to convert it to pixels if ( !rnumpx.test( ret ) && rnum.test( ret ) ) { // Remember the original values left = style.left; rsLeft = elem.runtimeStyle && elem.runtimeStyle.left; // Put in the new values to get a computed value out if ( rsLeft ) { elem.runtimeStyle.left = elem.currentStyle.left; } style.left = name === "fontSize" ? "1em" : ( ret || 0 ); ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; if ( rsLeft ) { elem.runtimeStyle.left = rsLeft; } } return ret === "" ? "auto" : ret; }; } curCSS = getComputedStyle || currentStyle; function getWH( elem, name, extra ) { // Start with offset property var val = name === "width" ? elem.offsetWidth : elem.offsetHeight, which = name === "width" ? cssWidth : cssHeight, i = 0, len = which.length; if ( val > 0 ) { if ( extra !== "border" ) { for ( ; i < len; i++ ) { if ( !extra ) { val -= parseFloat( jQuery.css( elem, "padding" + which[ i ] ) ) || 0; } if ( extra === "margin" ) { val += parseFloat( jQuery.css( elem, extra + which[ i ] ) ) || 0; } else { val -= parseFloat( jQuery.css( elem, "border" + which[ i ] + "Width" ) ) || 0; } } } return val + "px"; } // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name, name ); if ( val < 0 || val == null ) { val = elem.style[ name ] || 0; } // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; // Add padding, border, margin if ( extra ) { for ( ; i < len; i++ ) { val += parseFloat( jQuery.css( elem, "padding" + which[ i ] ) ) || 0; if ( extra !== "padding" ) { val += parseFloat( jQuery.css( elem, "border" + which[ i ] + "Width" ) ) || 0; } if ( extra === "margin" ) { val += parseFloat( jQuery.css( elem, extra + which[ i ] ) ) || 0; } } } return val + "px"; } if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.hidden = function( elem ) { var width = elem.offsetWidth, height = elem.offsetHeight; return ( width === 0 && height === 0 ) || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none"); }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; } var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rhash = /#.*$/, rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i, // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rquery = /\?/, rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, rselectTextarea = /^(?:select|textarea)/i, rspacesAjax = /\s+/, rts = /([?&])_=[^&]*/, rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/, // Keep a copy of the old load method _load = jQuery.fn.load, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Document location ajaxLocation, // Document location segments ajaxLocParts, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = ["*/"] + ["*"]; // #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement( "a" ); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } if ( jQuery.isFunction( func ) ) { var dataTypes = dataTypeExpression.toLowerCase().split( rspacesAjax ), i = 0, length = dataTypes.length, dataType, list, placeBefore; // For each dataType in the dataTypeExpression for ( ; i < length; i++ ) { dataType = dataTypes[ i ]; // We control if we're asked to add before // any existing element placeBefore = /^\+/.test( dataType ); if ( placeBefore ) { dataType = dataType.substr( 1 ) || "*"; } list = structure[ dataType ] = structure[ dataType ] || []; // then we add to the structure accordingly list[ placeBefore ? "unshift" : "push" ]( func ); } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, dataType /* internal */, inspected /* internal */ ) { dataType = dataType || options.dataTypes[ 0 ]; inspected = inspected || {}; inspected[ dataType ] = true; var list = structure[ dataType ], i = 0, length = list ? list.length : 0, executeOnly = ( structure === prefilters ), selection; for ( ; i < length && ( executeOnly || !selection ); i++ ) { selection = list[ i ]( options, originalOptions, jqXHR ); // If we got redirected to another dataType // we try there if executing only and not done already if ( typeof selection === "string" ) { if ( !executeOnly || inspected[ selection ] ) { selection = undefined; } else { options.dataTypes.unshift( selection ); selection = inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, selection, inspected ); } } } // If we're only executing or nothing was selected // we try the catchall dataType if not done already if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) { selection = inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, "*", inspected ); } // unnecessary when only executing (prefilters) // but it'll be ignored by the caller in that case return selection; } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var key, deep, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } } jQuery.fn.extend({ load: function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); // Don't do a request if no elements are being requested } else if ( !this.length ) { return this; } var off = url.indexOf( " " ); if ( off >= 0 ) { var selector = url.slice( off, url.length ); url = url.slice( 0, off ); } // Default to a GET request var type = "GET"; // If the second parameter was provided if ( params ) { // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( typeof params === "object" ) { params = jQuery.param( params, jQuery.ajaxSettings.traditional ); type = "POST"; } } var self = this; // Request the remote document jQuery.ajax({ url: url, type: type, dataType: "html", data: params, // Complete callback (responseText is used internally) complete: function( jqXHR, status, responseText ) { // Store the response as specified by the jqXHR object responseText = jqXHR.responseText; // If successful, inject the HTML into all the matched elements if ( jqXHR.isResolved() ) { // #4825: Get the actual response in case // a dataFilter is present in ajaxSettings jqXHR.done(function( r ) { responseText = r; }); // See if a selector was specified self.html( selector ? // Create a dummy div to hold the results jQuery("<div>") // inject the contents of the document in, removing the scripts // to avoid any 'Permission Denied' errors in IE .append(responseText.replace(rscript, "")) // Locate the specified elements .find(selector) : // If not, just inject the full result responseText ); } if ( callback ) { self.each( callback, [ responseText, status, jqXHR ] ); } } }); return this; }, serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function(){ return this.elements ? jQuery.makeArray( this.elements ) : this; }) .filter(function(){ return this.name && !this.disabled && ( this.checked || rselectTextarea.test( this.nodeName ) || rinput.test( this.type ) ); }) .map(function( i, elem ){ var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val, i ){ return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); // Attach a bunch of functions for handling common AJAX events jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){ jQuery.fn[ o ] = function( f ){ return this.on( o, f ); }; }); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ type: method, url: url, data: data, success: callback, dataType: type }); }; }); jQuery.extend({ getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { if ( settings ) { // Building a settings object ajaxExtend( target, jQuery.ajaxSettings ); } else { // Extending ajaxSettings settings = target; target = jQuery.ajaxSettings; } ajaxExtend( target, settings ); return target; }, ajaxSettings: { url: ajaxLocation, isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, type: "GET", contentType: "application/x-www-form-urlencoded", processData: true, async: true, /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, traditional: false, headers: {}, */ accepts: { xml: "application/xml, text/xml", html: "text/html", text: "text/plain", json: "application/json, text/javascript", "*": allTypes }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText" }, // List of data converters // 1) key format is "source_type destination_type" (a single space in-between) // 2) the catchall symbol "*" can be used for source_type converters: { // Convert anything to text "* text": window.String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { context: true, url: true } }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events // It's the callbackContext if one was provided in the options // and if it's a DOM node or a jQuery collection globalEventContext = callbackContext !== s && ( callbackContext.nodeType || callbackContext instanceof jQuery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks( "once memory" ), // Status-dependent callbacks statusCode = s.statusCode || {}, // ifModified key ifModifiedKey, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // Response headers responseHeadersString, responseHeaders, // transport transport, // timeout handle timeoutTimer, // Cross-domain detection vars parts, // The jqXHR state state = 0, // To know if global events are to be dispatched fireGlobals, // Loop variable i, // Fake xhr jqXHR = { readyState: 0, // Caches the header setRequestHeader: function( name, value ) { if ( !state ) { var lname = name.toLowerCase(); name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( state === 2 ) { if ( !responseHeaders ) { responseHeaders = {}; while( ( match = rheaders.exec( responseHeadersString ) ) ) { responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match === undefined ? null : match; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Cancel the request abort: function( statusText ) { statusText = statusText || "abort"; if ( transport ) { transport.abort( statusText ); } done( 0, statusText ); return this; } }; // Callback for when everything is done // It is defined here because jslint complains if it is declared // at the end of the function (which would be more logical and readable) function done( status, nativeStatusText, responses, headers ) { // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; var isSuccess, success, error, statusText = nativeStatusText, response = responses ? ajaxHandleResponses( s, jqXHR, responses ) : undefined, lastModified, etag; // If successful, handle type chaining if ( status >= 200 && status < 300 || status === 304 ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( ( lastModified = jqXHR.getResponseHeader( "Last-Modified" ) ) ) { jQuery.lastModified[ ifModifiedKey ] = lastModified; } if ( ( etag = jqXHR.getResponseHeader( "Etag" ) ) ) { jQuery.etag[ ifModifiedKey ] = etag; } } // If not modified if ( status === 304 ) { statusText = "notmodified"; isSuccess = true; // If we have data } else { try { success = ajaxConvert( s, response ); statusText = "success"; isSuccess = true; } catch(e) { // We have a parsererror statusText = "parsererror"; error = e; } } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if ( !statusText || status ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = "" + ( nativeStatusText || statusText ); // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ), [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger( "ajaxStop" ); } } } // Attach deferreds deferred.promise( jqXHR ); jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; jqXHR.complete = completeDeferred.add; // Status-dependent callbacks jqXHR.statusCode = function( map ) { if ( map ) { var tmp; if ( state < 2 ) { for ( tmp in map ) { statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ]; } } else { tmp = map[ jqXHR.status ]; jqXHR.then( tmp, tmp ); } } return this; }; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (#5866: IE7 issue with protocol-less urls) // We also use the url parameter if available s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( rspacesAjax ); // Determine if a cross-domain request is in order if ( s.crossDomain == null ) { parts = rurl.exec( s.url.toLowerCase() ); s.crossDomain = !!( parts && ( parts[ 1 ] != ajaxLocParts[ 1 ] || parts[ 2 ] != ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) != ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) ) ); } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefiler, stop there if ( state === 2 ) { return false; } // We can fire global events as of now if asked to fireGlobals = s.global; // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger( "ajaxStart" ); } // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data; // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Get ifModifiedKey before adding the anti-cache parameter ifModifiedKey = s.url; // Add anti-cache in url if needed if ( s.cache === false ) { var ts = jQuery.now(), // try replacing _= if it is there ret = s.url.replace( rts, "$1_=" + ts ); // if nothing was replaced, add timestamp to the end s.url = ret + ( ( ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { ifModifiedKey = ifModifiedKey || s.url; if ( jQuery.lastModified[ ifModifiedKey ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] ); } if ( jQuery.etag[ ifModifiedKey ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] ); } } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already jqXHR.abort(); return false; } // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout( function(){ jqXHR.abort( "timeout" ); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch (e) { // Propagate exception as error if not done if ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { throw e; } } } return jqXHR; }, // Serialize an array of form elements or a set of // key/values into a query string param: function( a, traditional ) { var s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : value; s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( var prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); } }); function buildParams( prefix, obj, traditional, add ) { if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // If array item is non-scalar (array or object), encode its // numeric index to resolve deserialization ambiguity issues. // Note that rack (as of 1.0.0) can't currently deserialize // nested arrays properly, and attempting to do so may cause // a server error. Possible fixes are to modify rack's // deserialization algorithm or to provide an option or flag // to force array serialization to be shallow. buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && obj != null && typeof obj === "object" ) { // Serialize object item. for ( var name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } // This is still on the jQuery object... for now // Want to move this to jQuery.ajax some day jQuery.extend({ // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {} }); /* Handles responses to an ajax request: * - sets all responseXXX fields accordingly * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var contents = s.contents, dataTypes = s.dataTypes, responseFields = s.responseFields, ct, type, finalDataType, firstDataType; // Fill responseXXX fields for ( type in responseFields ) { if ( type in responses ) { jqXHR[ responseFields[type] ] = responses[ type ]; } } // Remove auto dataType and get content-type in the process while( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader( "content-type" ); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } // Chain conversions given the request and the original response function ajaxConvert( s, response ) { // Apply the dataFilter if provided if ( s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } var dataTypes = s.dataTypes, converters = {}, i, key, length = dataTypes.length, tmp, // Current and previous dataTypes current = dataTypes[ 0 ], prev, // Conversion expression conversion, // Conversion function conv, // Conversion functions (transitive conversion) conv1, conv2; // For each dataType in the chain for ( i = 1; i < length; i++ ) { // Create converters map // with lowercased keys if ( i === 1 ) { for ( key in s.converters ) { if ( typeof key === "string" ) { converters[ key.toLowerCase() ] = s.converters[ key ]; } } } // Get the dataTypes prev = current; current = dataTypes[ i ]; // If current is auto dataType, update it to prev if ( current === "*" ) { current = prev; // If no auto and dataTypes are actually different } else if ( prev !== "*" && prev !== current ) { // Get the converter conversion = prev + " " + current; conv = converters[ conversion ] || converters[ "* " + current ]; // If there is no direct converter, search transitively if ( !conv ) { conv2 = undefined; for ( conv1 in converters ) { tmp = conv1.split( " " ); if ( tmp[ 0 ] === prev || tmp[ 0 ] === "*" ) { conv2 = converters[ tmp[1] + " " + current ]; if ( conv2 ) { conv1 = converters[ conv1 ]; if ( conv1 === true ) { conv = conv2; } else if ( conv2 === true ) { conv = conv1; } break; } } } } // If we found no converter, dispatch an error if ( !( conv || conv2 ) ) { jQuery.error( "No conversion from " + conversion.replace(" "," to ") ); } // If found converter is not an equivalence if ( conv !== true ) { // Convert with 1 or 2 converters accordingly response = conv ? conv( response ) : conv2( conv1(response) ); } } } return response; } var jsc = jQuery.now(), jsre = /(\=)\?(&|$)|\?\?/i; // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { return jQuery.expando + "_" + ( jsc++ ); } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var inspectData = s.contentType === "application/x-www-form-urlencoded" && ( typeof s.data === "string" ); if ( s.dataTypes[ 0 ] === "jsonp" || s.jsonp !== false && ( jsre.test( s.url ) || inspectData && jsre.test( s.data ) ) ) { var responseContainer, jsonpCallback = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback, previous = window[ jsonpCallback ], url = s.url, data = s.data, replace = "$1" + jsonpCallback + "$2"; if ( s.jsonp !== false ) { url = url.replace( jsre, replace ); if ( s.url === url ) { if ( inspectData ) { data = data.replace( jsre, replace ); } if ( s.data === data ) { // Add callback manually url += (/\?/.test( url ) ? "&" : "?") + s.jsonp + "=" + jsonpCallback; } } } s.url = url; s.data = data; // Install callback window[ jsonpCallback ] = function( response ) { responseContainer = [ response ]; }; // Clean-up function jqXHR.always(function() { // Set callback back to previous value window[ jsonpCallback ] = previous; // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( previous ) ) { window[ jsonpCallback ]( responseContainer[ 0 ] ); } }); // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( jsonpCallback + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Delegate to script return "script"; } }); // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /javascript|ecmascript/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and global jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; s.global = false; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function(s) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement; return { send: function( _, callback ) { script = document.createElement( "script" ); script.async = "async"; if ( s.scriptCharset ) { script.charset = s.scriptCharset; } script.src = s.url; // Attach handlers for all browsers script.onload = script.onreadystatechange = function( _, isAbort ) { if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) { // Handle memory leak in IE script.onload = script.onreadystatechange = null; // Remove the script if ( head && script.parentNode ) { head.removeChild( script ); } // Dereference the script script = undefined; // Callback if not abort if ( !isAbort ) { callback( 200, "success" ); } } }; // Use insertBefore instead of appendChild to circumvent an IE6 bug. // This arises when a base node is used (#2709 and #4378). head.insertBefore( script, head.firstChild ); }, abort: function() { if ( script ) { script.onload( 0, 1 ); } } }; } }); var // #5280: Internet Explorer will keep connections alive if we don't abort on unload xhrOnUnloadAbort = window.ActiveXObject ? function() { // Abort all pending requests for ( var key in xhrCallbacks ) { xhrCallbacks[ key ]( 0, 1 ); } } : false, xhrId = 0, xhrCallbacks; // Functions to create xhrs function createStandardXHR() { try { return new window.XMLHttpRequest(); } catch( e ) {} } function createActiveXHR() { try { return new window.ActiveXObject( "Microsoft.XMLHTTP" ); } catch( e ) {} } // Create the request object // (This is still attached to ajaxSettings for backward compatibility) jQuery.ajaxSettings.xhr = window.ActiveXObject ? /* Microsoft failed to properly * implement the XMLHttpRequest in IE7 (can't request local files), * so we use the ActiveXObject when it is available * Additionally XMLHttpRequest can be disabled in IE7/IE8 so * we need a fallback. */ function() { return !this.isLocal && createStandardXHR() || createActiveXHR(); } : // For all other browsers, use the standard XMLHttpRequest object createStandardXHR; // Determine support properties (function( xhr ) { jQuery.extend( jQuery.support, { ajax: !!xhr, cors: !!xhr && ( "withCredentials" in xhr ) }); })( jQuery.ajaxSettings.xhr() ); // Create transport if the browser can provide an xhr if ( jQuery.support.ajax ) { jQuery.ajaxTransport(function( s ) { // Cross domain only allowed if supported through XMLHttpRequest if ( !s.crossDomain || jQuery.support.cors ) { var callback; return { send: function( headers, complete ) { // Get a new xhr var xhr = s.xhr(), handle, i; // Open the socket // Passing null username, generates a login popup on Opera (#2865) if ( s.username ) { xhr.open( s.type, s.url, s.async, s.username, s.password ); } else { xhr.open( s.type, s.url, s.async ); } // Apply custom fields if provided if ( s.xhrFields ) { for ( i in s.xhrFields ) { xhr[ i ] = s.xhrFields[ i ]; } } // Override mime type if needed if ( s.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( s.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !s.crossDomain && !headers["X-Requested-With"] ) { headers[ "X-Requested-With" ] = "XMLHttpRequest"; } // Need an extra try/catch for cross domain requests in Firefox 3 try { for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } } catch( _ ) {} // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send( ( s.hasContent && s.data ) || null ); // Listener callback = function( _, isAbort ) { var status, statusText, responseHeaders, responses, xml; // Firefox throws exceptions when accessing properties // of an xhr when a network error occured // http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE) try { // Was never called and is aborted or complete if ( callback && ( isAbort || xhr.readyState === 4 ) ) { // Only called once callback = undefined; // Do not keep as active anymore if ( handle ) { xhr.onreadystatechange = jQuery.noop; if ( xhrOnUnloadAbort ) { delete xhrCallbacks[ handle ]; } } // If it's an abort if ( isAbort ) { // Abort it manually if needed if ( xhr.readyState !== 4 ) { xhr.abort(); } } else { status = xhr.status; responseHeaders = xhr.getAllResponseHeaders(); responses = {}; xml = xhr.responseXML; // Construct response list if ( xml && xml.documentElement /* #4958 */ ) { responses.xml = xml; } 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 && s.isLocal && !s.crossDomain ) { status = responses.text ? 200 : 404; // IE - #1450: sometimes returns 1223 when it should be 204 } else if ( status === 1223 ) { status = 204; } } } } catch( firefoxAccessException ) { if ( !isAbort ) { complete( -1, firefoxAccessException ); } } // Call complete if needed if ( responses ) { complete( status, statusText, responses, responseHeaders ); } }; // if we're in sync mode or it's in cache // and has been retrieved directly (IE6 & IE7) // we need to manually fire the callback if ( !s.async || xhr.readyState === 4 ) { callback(); } else { handle = ++xhrId; if ( xhrOnUnloadAbort ) { // Create the active xhrs callbacks list if needed // and attach the unload handler if ( !xhrCallbacks ) { xhrCallbacks = {}; jQuery( window ).unload( xhrOnUnloadAbort ); } // Add to list of active xhrs callbacks xhrCallbacks[ handle ] = callback; } xhr.onreadystatechange = callback; } }, abort: function() { if ( callback ) { callback(0,1); } } }; } }); } var elemdisplay = {}, iframe, iframeDoc, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = /^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i, timerId, fxAttrs = [ // height animations [ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ], // width animations [ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ], // opacity animations [ "opacity" ] ], fxNow; jQuery.fn.extend({ show: function( speed, easing, callback ) { var elem, display; if ( speed || speed === 0 ) { return this.animate( genFx("show", 3), speed, easing, callback ); } else { for ( var i = 0, j = this.length; i < j; i++ ) { elem = this[ i ]; if ( elem.style ) { display = elem.style.display; // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !jQuery._data(elem, "olddisplay") && display === "none" ) { display = elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( display === "" && jQuery.css(elem, "display") === "none" ) { jQuery._data( elem, "olddisplay", defaultDisplay(elem.nodeName) ); } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( i = 0; i < j; i++ ) { elem = this[ i ]; if ( elem.style ) { display = elem.style.display; if ( display === "" || display === "none" ) { elem.style.display = jQuery._data( elem, "olddisplay" ) || ""; } } } return this; } }, hide: function( speed, easing, callback ) { if ( speed || speed === 0 ) { return this.animate( genFx("hide", 3), speed, easing, callback); } else { var elem, display, i = 0, j = this.length; for ( ; i < j; i++ ) { elem = this[i]; if ( elem.style ) { display = jQuery.css( elem, "display" ); if ( display !== "none" && !jQuery._data( elem, "olddisplay" ) ) { jQuery._data( elem, "olddisplay", display ); } } } // Set the display of the elements in a second loop // to avoid the constant reflow for ( i = 0; i < j; i++ ) { if ( this[i].style ) { this[i].style.display = "none"; } } return this; } }, // Save the old toggle function _toggle: jQuery.fn.toggle, toggle: function( fn, fn2, callback ) { var bool = typeof fn === "boolean"; if ( jQuery.isFunction(fn) && jQuery.isFunction(fn2) ) { this._toggle.apply( this, arguments ); } else if ( fn == null || bool ) { this.each(function() { var state = bool ? fn : jQuery(this).is(":hidden"); jQuery(this)[ state ? "show" : "hide" ](); }); } else { this.animate(genFx("toggle", 3), fn, fn2, callback); } return this; }, fadeTo: function( speed, to, easing, callback ) { return this.filter(":hidden").css("opacity", 0).show().end() .animate({opacity: to}, speed, easing, callback); }, animate: function( prop, speed, easing, callback ) { var optall = jQuery.speed( speed, easing, callback ); if ( jQuery.isEmptyObject( prop ) ) { return this.each( optall.complete, [ false ] ); } // Do not change referenced properties as per-property easing will be lost prop = jQuery.extend( {}, prop ); function doAnimation() { // XXX 'this' does not always have a nodeName when running the // test suite if ( optall.queue === false ) { jQuery._mark( this ); } var opt = jQuery.extend( {}, optall ), isElement = this.nodeType === 1, hidden = isElement && jQuery(this).is(":hidden"), name, val, p, e, parts, start, end, unit, method; // will store per property easing and be used to determine when an animation is complete opt.animatedProperties = {}; for ( p in prop ) { // property name normalization name = jQuery.camelCase( p ); if ( p !== name ) { prop[ name ] = prop[ p ]; delete prop[ p ]; } val = prop[ name ]; // easing resolution: per property > opt.specialEasing > opt.easing > 'swing' (default) if ( jQuery.isArray( val ) ) { opt.animatedProperties[ name ] = val[ 1 ]; val = prop[ name ] = val[ 0 ]; } else { opt.animatedProperties[ name ] = opt.specialEasing && opt.specialEasing[ name ] || opt.easing || 'swing'; } if ( val === "hide" && hidden || val === "show" && !hidden ) { return opt.complete.call( this ); } if ( isElement && ( name === "height" || name === "width" ) ) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE does not // change the overflow attribute when overflowX and // overflowY are set to the same value opt.overflow = [ this.style.overflow, this.style.overflowX, this.style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height animated if ( jQuery.css( this, "display" ) === "inline" && jQuery.css( this, "float" ) === "none" ) { // inline-level elements accept inline-block; // block-level elements need to be inline with layout if ( !jQuery.support.inlineBlockNeedsLayout || defaultDisplay( this.nodeName ) === "inline" ) { this.style.display = "inline-block"; } else { this.style.zoom = 1; } } } } if ( opt.overflow != null ) { this.style.overflow = "hidden"; } for ( p in prop ) { e = new jQuery.fx( this, opt, p ); val = prop[ p ]; if ( rfxtypes.test( val ) ) { // Tracks whether to show or hide based on private // data attached to the element method = jQuery._data( this, "toggle" + p ) || ( val === "toggle" ? hidden ? "show" : "hide" : 0 ); if ( method ) { jQuery._data( this, "toggle" + p, method === "show" ? "hide" : "show" ); e[ method ](); } else { e[ val ](); } } else { parts = rfxnum.exec( val ); start = e.cur(); if ( parts ) { end = parseFloat( parts[2] ); unit = parts[3] || ( jQuery.cssNumber[ p ] ? "" : "px" ); // We need to compute starting value if ( unit !== "px" ) { jQuery.style( this, p, (end || 1) + unit); start = ( (end || 1) / e.cur() ) * start; jQuery.style( this, p, start + unit); } // If a +=/-= token was provided, we're doing a relative animation if ( parts[1] ) { end = ( (parts[ 1 ] === "-=" ? -1 : 1) * end ) + start; } e.custom( start, end, unit ); } else { e.custom( start, val, "" ); } } } // For JS strict compliance return true; } return optall.queue === false ? this.each( doAnimation ) : this.queue( optall.queue, doAnimation ); }, stop: function( type, clearQueue, gotoEnd ) { if ( typeof type !== "string" ) { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if ( clearQueue && type !== false ) { this.queue( type || "fx", [] ); } return this.each(function() { var index, hadTimers = false, timers = jQuery.timers, data = jQuery._data( this ); // clear marker counters if we know they won't be if ( !gotoEnd ) { jQuery._unmark( true, this ); } function stopQueue( elem, data, index ) { var hooks = data[ index ]; jQuery.removeData( elem, index, true ); hooks.stop( gotoEnd ); } if ( type == null ) { for ( index in data ) { if ( data[ index ] && data[ index ].stop && index.indexOf(".run") === index.length - 4 ) { stopQueue( this, data, index ); } } } else if ( data[ index = type + ".run" ] && data[ index ].stop ){ stopQueue( this, data, index ); } for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) { if ( gotoEnd ) { // force the next step to be the last timers[ index ]( true ); } else { timers[ index ].saveState(); } hadTimers = true; timers.splice( index, 1 ); } } // start the next in the queue if the last step wasn't forced // timers currently will call their complete callbacks, which will dequeue // but only if they were gotoEnd if ( !( gotoEnd && hadTimers ) ) { jQuery.dequeue( this, type ); } }); } }); // Animations created synchronously will run synchronously function createFxNow() { setTimeout( clearFxNow, 0 ); return ( fxNow = jQuery.now() ); } function clearFxNow() { fxNow = undefined; } // Generate parameters to create a standard animation function genFx( type, num ) { var obj = {}; jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice( 0, num )), function() { obj[ this ] = type; }); return obj; } // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx( "show", 1 ), slideUp: genFx( "hide", 1 ), slideToggle: genFx( "toggle", 1 ), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; }); jQuery.extend({ speed: function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; // normalize opt.queue - true/undefined/null -> "fx" if ( opt.queue == null || opt.queue === true ) { opt.queue = "fx"; } // Queueing opt.old = opt.complete; opt.complete = function( noUnmark ) { if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } else if ( noUnmark !== false ) { jQuery._unmark( this ); } }; return opt; }, easing: { linear: function( p, 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; options.orig = options.orig || {}; } }); jQuery.fx.prototype = { // Simple function for setting a style value update: function() { if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } ( jQuery.fx.step[ this.prop ] || jQuery.fx.step._default )( this ); }, // Get the current size cur: function() { if ( this.elem[ this.prop ] != null && (!this.elem.style || this.elem.style[ this.prop ] == null) ) { return this.elem[ this.prop ]; } var parsed, r = jQuery.css( this.elem, this.prop ); // Empty strings, null, undefined and "auto" are converted to 0, // complex values such as "rotate(1rad)" are returned as is, // simple values such as "10px" are parsed to Float. return isNaN( parsed = parseFloat( r ) ) ? !r || r === "auto" ? 0 : r : parsed; }, // Start an animation from one number to another custom: function( from, to, unit ) { var self = this, fx = jQuery.fx; this.startTime = fxNow || createFxNow(); this.end = to; this.now = this.start = from; this.pos = this.state = 0; this.unit = unit || this.unit || ( jQuery.cssNumber[ this.prop ] ? "" : "px" ); function t( gotoEnd ) { return self.step( gotoEnd ); } t.queue = this.options.queue; t.elem = this.elem; t.saveState = function() { if ( self.options.hide && jQuery._data( self.elem, "fxshow" + self.prop ) === undefined ) { jQuery._data( self.elem, "fxshow" + self.prop, self.start ); } }; if ( t() && jQuery.timers.push(t) && !timerId ) { timerId = setInterval( fx.tick, fx.interval ); } }, // Simple 'show' function show: function() { var dataShow = jQuery._data( this.elem, "fxshow" + this.prop ); // Remember where we started, so that we can go back to it later this.options.orig[ this.prop ] = dataShow || jQuery.style( this.elem, this.prop ); this.options.show = true; // Begin the animation // Make sure that we start at a small width/height to avoid any flash of content if ( dataShow !== undefined ) { // This show is picking up where a previous hide or show left off this.custom( this.cur(), dataShow ); } else { this.custom( this.prop === "width" || this.prop === "height" ? 1 : 0, this.cur() ); } // Start by showing the element jQuery( this.elem ).show(); }, // Simple 'hide' function hide: function() { // Remember where we started, so that we can go back to it later this.options.orig[ this.prop ] = jQuery._data( this.elem, "fxshow" + this.prop ) || jQuery.style( this.elem, this.prop ); this.options.hide = true; // Begin the animation this.custom( this.cur(), 0 ); }, // Each step of an animation step: function( gotoEnd ) { var p, n, complete, t = fxNow || createFxNow(), done = true, elem = this.elem, options = this.options; if ( gotoEnd || t >= options.duration + this.startTime ) { this.now = this.end; this.pos = this.state = 1; this.update(); options.animatedProperties[ this.prop ] = true; for ( p in options.animatedProperties ) { if ( options.animatedProperties[ p ] !== true ) { done = false; } } if ( done ) { // Reset the overflow if ( options.overflow != null && !jQuery.support.shrinkWrapBlocks ) { jQuery.each( [ "", "X", "Y" ], function( index, value ) { elem.style[ "overflow" + value ] = options.overflow[ index ]; }); } // Hide the element if the "hide" operation was done if ( options.hide ) { jQuery( elem ).hide(); } // Reset the properties, if the item has been hidden or shown if ( options.hide || options.show ) { for ( p in options.animatedProperties ) { jQuery.style( elem, p, options.orig[ p ] ); jQuery.removeData( elem, "fxshow" + p, true ); // Toggle data is no longer needed jQuery.removeData( elem, "toggle" + p, true ); } } // Execute the complete function // in the event that the complete function throws an exception // we must ensure it won't be called twice. #5684 complete = options.complete; if ( complete ) { options.complete = false; complete.call( elem ); } } return false; } else { // classical easing cannot be used with an Infinity duration if ( options.duration == Infinity ) { this.now = t; } else { n = t - this.startTime; this.state = n / options.duration; // Perform the easing function, defaults to swing this.pos = jQuery.easing[ options.animatedProperties[this.prop] ]( this.state, n, 0, 1, options.duration ); this.now = this.start + ( (this.end - this.start) * this.pos ); } // Perform the next step of the animation this.update(); } return true; } }; jQuery.extend( jQuery.fx, { tick: function() { var timer, timers = jQuery.timers, i = 0; for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Checks the timer has not already been removed if ( !timer() && timers[ i ] === timer ) { timers.splice( i--, 1 ); } } if ( !timers.length ) { jQuery.fx.stop(); } }, interval: 13, stop: function() { clearInterval( timerId ); timerId = null; }, speeds: { slow: 600, fast: 200, // Default speed _default: 400 }, step: { opacity: function( fx ) { jQuery.style( fx.elem, "opacity", fx.now ); }, _default: function( fx ) { if ( fx.elem.style && fx.elem.style[ fx.prop ] != null ) { fx.elem.style[ fx.prop ] = fx.now + fx.unit; } else { fx.elem[ fx.prop ] = fx.now; } } } }); // Adds width/height step functions // Do not set anything below 0 jQuery.each([ "width", "height" ], function( i, prop ) { jQuery.fx.step[ prop ] = function( fx ) { jQuery.style( fx.elem, prop, Math.max(0, fx.now) + fx.unit ); }; }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; } // Try to restore the default display value of an element function defaultDisplay( nodeName ) { if ( !elemdisplay[ nodeName ] ) { var body = document.body, elem = jQuery( "<" + nodeName + ">" ).appendTo( body ), display = elem.css( "display" ); elem.remove(); // If the simple way fails, // get element's real default display by attaching it to a temp iframe if ( display === "none" || display === "" ) { // No iframe to use yet, so create it if ( !iframe ) { iframe = document.createElement( "iframe" ); iframe.frameBorder = iframe.width = iframe.height = 0; } body.appendChild( iframe ); // Create a cacheable copy of the iframe document on first call. // IE and Opera will allow us to reuse the iframeDoc without re-writing the fake HTML // document to it; WebKit & Firefox won't allow reusing the iframe document. if ( !iframeDoc || !iframe.createElement ) { iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document; iframeDoc.write( ( document.compatMode === "CSS1Compat" ? "<!doctype html>" : "" ) + "<html><body>" ); iframeDoc.close(); } elem = iframeDoc.createElement( nodeName ); iframeDoc.body.appendChild( elem ); display = jQuery.css( elem, "display" ); body.removeChild( iframe ); } // Store the correct default display elemdisplay[ nodeName ] = display; } return elemdisplay[ nodeName ]; } var 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: box.top, left: box.left } : { top: 0, left: 0 }; } var body = doc.body, win = getWindow(doc), clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0, scrollTop = win.pageYOffset || jQuery.support.boxModel && docElem.scrollTop || body.scrollTop, scrollLeft = win.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft, top = box.top + scrollTop - clientTop, left = box.left + scrollLeft - clientLeft; return { top: top, left: left }; }; } else { 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 ); } 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.support.fixedPosition && prevComputedStyle.position === "fixed" ) { break; } computedStyle = defaultView ? defaultView.getComputedStyle(elem, null) : elem.currentStyle; top -= elem.scrollTop; left -= elem.scrollLeft; if ( elem === offsetParent ) { top += elem.offsetTop; left += elem.offsetLeft; if ( jQuery.support.doesNotAddBorder && !(jQuery.support.doesAddBorderForTableAndCells && rtable.test(elem.nodeName)) ) { top += parseFloat( computedStyle.borderTopWidth ) || 0; left += parseFloat( computedStyle.borderLeftWidth ) || 0; } prevOffsetParent = offsetParent; offsetParent = elem.offsetParent; } if ( jQuery.support.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" ) { top += parseFloat( computedStyle.borderTopWidth ) || 0; left += parseFloat( computedStyle.borderLeftWidth ) || 0; } prevComputedStyle = computedStyle; } if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" ) { top += body.offsetTop; left += body.offsetLeft; } if ( jQuery.support.fixedPosition && prevComputedStyle.position === "fixed" ) { top += Math.max( docElem.scrollTop, body.scrollTop ); left += Math.max( docElem.scrollLeft, body.scrollLeft ); } return { top: top, left: left }; }; } jQuery.offset = { bodyOffset: function( body ) { var top = body.offsetTop, left = body.offsetLeft; if ( jQuery.support.doesNotIncludeMarginInBodyOffset ) { top += parseFloat( jQuery.css(body, "marginTop") ) || 0; left += parseFloat( jQuery.css(body, "marginLeft") ) || 0; } return { top: top, left: left }; }, setOffset: function( elem, options, i ) { var position = jQuery.css( elem, "position" ); // set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } var curElem = jQuery( elem ), curOffset = curElem.offset(), curCSSTop = jQuery.css( elem, "top" ), curCSSLeft = jQuery.css( elem, "left" ), calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1, props = {}, curPosition = {}, curTop, curLeft; // need to be able to calculate position if either top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } if ( options.top != null ) { props.top = ( options.top - curOffset.top ) + curTop; } if ( options.left != null ) { props.left = ( options.left - curOffset.left ) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ position: function() { if ( !this[0] ) { return null; } var elem = this[0], // Get *real* offsetParent offsetParent = this.offsetParent(), // Get correct offsets offset = this.offset(), parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset(); // Subtract element margins // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0; offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0; // Add offsetParent borders parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0; parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0; // Subtract the two offsets return { top: offset.top - parentOffset.top, left: offset.left - parentOffset.left }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || document.body; while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) { offsetParent = offsetParent.offsetParent; } return offsetParent; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( ["Left", "Top"], function( i, name ) { var method = "scroll" + name; jQuery.fn[ method ] = function( val ) { var elem, win; if ( val === undefined ) { elem = this[ 0 ]; if ( !elem ) { return null; } 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 ]; } // 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; } }); }; }); function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } // Create width, height, innerHeight, innerWidth, outerHeight and outerWidth methods jQuery.each([ "Height", "Width" ], function( i, name ) { var type = name.toLowerCase(); // innerHeight and innerWidth jQuery.fn[ "inner" + name ] = function() { var elem = this[0]; return elem ? elem.style ? parseFloat( jQuery.css( elem, type, "padding" ) ) : this[ type ]() : null; }; // outerHeight and outerWidth jQuery.fn[ "outer" + name ] = function( margin ) { var elem = this[0]; return elem ? elem.style ? parseFloat( jQuery.css( elem, type, margin ? "margin" : "border" ) ) : this[ type ]() : null; }; jQuery.fn[ type ] = function( 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 // 3rd condition allows Nokia support, as it supports the docElem prop but not CSS1Compat var docElemProp = elem.document.documentElement[ "client" + name ], body = elem.document.body; return elem.document.compatMode === "CSS1Compat" && docElemProp || body && body[ "client" + name ] || docElemProp; // 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.isNumeric( ret ) ? ret : orig; // 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" ); } }; }); // Expose jQuery to the global object window.jQuery = window.$ = jQuery; // Expose jQuery as an AMD module, but only for AMD loaders that // understand the issues with loading multiple versions of jQuery // in a page that all might call define(). The loader will indicate // they have special allowances for multiple jQuery versions by // specifying define.amd.jQuery = true. Register as a named module, // since jQuery can be concatenated with other files that may use define, // but not use a proper concatenation script that understands anonymous // AMD modules. A named AMD is safest and most robust way to register. // Lowercase jquery is used because AMD module names are derived from // file names, and jQuery is normally delivered in a lowercase file name. // Do this after creating the global so that if an AMD module wants to call // noConflict to hide this version of jQuery, it will work. if ( typeof define === "function" && define.amd && define.amd.jQuery ) { define( "jquery", [], function () { return jQuery; } ); } })( window );
src/pages/index.js
jsonnull/jsonnull.com
import React from 'react' import Link from 'next/link' import Image from 'next/image' import clsx from 'clsx' import { Heading, Page, Wrapper } from '../components' import { Spacer } from '../components/Spacer.tsx' import { ProjectGrid } from '../components/ProjectGrid' import { Button } from '../components/Button' import { profileDataURI } from '../lib/profileDataURI' import { jsonnull, configuration } from '../data/projects/index.ts' import { ArrowRight } from 'react-feather' export const Title = ({ className }) => { return ( <h1 className={clsx( 'pt-4 text-4xl sm:text-5xl font-semibold tracking-tight', className )} > Crafting{' '} <span className="text-transparent bg-clip-text bg-gradient-to-r from-fog to-steel"> experiences </span>{' '} with code. </h1> ) } const TitleSection = () => { return ( <div className="flex flex-col items-center"> <Image src={profileDataURI} alt="Picture of the author" width="80" height="80" className="rounded-full" /> <Title /> </div> ) } const Home = () => { return ( <Wrapper> <Spacer extraWide /> <TitleSection /> <Spacer extraWide /> <div className="flex flex-col items-center"> <Heading>Recent Projects</Heading> </div> <Spacer medium /> <ProjectGrid projects={[jsonnull, configuration]} /> <Spacer medium /> <div className="flex justify-center"> <Link href="/projects"> <a> <Button> <div className="flex items-center underline-themed"> See my other projects <ArrowRight size={18} className="ml-2" /> </div> </Button> </a> </Link> </div> </Wrapper> ) } Home.getLayout = (page) => ( <Page title="Home" pagePath="/" ogImagePath="/og-images/index.jpg"> {page} </Page> ) export default Home
Docker/KlusterKiteMonitoring/klusterkite-web/src/components/PackageForm/PackagesForm.js
KlusterKite/KlusterKite
import React from 'react'; import isEqual from 'lodash/isEqual'; import Form from '../Form/Form'; import PackagesMultiSelector from '../PackageSelector/PackagesMultiSelector'; export default class PackagesForm extends React.Component { // eslint-disable-line react/prefer-stateless-function constructor(props) { super(props); this.submit = this.submit.bind(this); this.state = { model: {} }; } static propTypes = { onSubmit: React.PropTypes.func.isRequired, onCancel: React.PropTypes.func, onDelete: React.PropTypes.func, initialValues: React.PropTypes.object, saving: React.PropTypes.bool, deleting: React.PropTypes.bool, saved: React.PropTypes.bool, saveErrors: React.PropTypes.arrayOf(React.PropTypes.string), saveError: React.PropTypes.string, }; componentWillMount() { this.onReceiveProps(this.props, true); } componentWillReceiveProps(nextProps) { this.onReceiveProps(nextProps, false); } onReceiveProps(nextProps, skipCheck) { if (nextProps.initialValues && (!isEqual(nextProps.initialValues, this.props.initialValues) || skipCheck)) { const packages = nextProps.initialValues.packages.edges.map(x => x.node).map(x => { return { id: x.__id, specificVersion: x.version } }); this.setState({ packages: packages }); } } arrayToString(data) { return data && this.replaceAll(data.join(), ',', '\n'); } stringToArray(data) { return data && data.length > 0 ? data.split('\n') : []; } replaceAll(value, search, replacement) { return value.replace(new RegExp(search, 'g'), replacement); } submit(model) { const packages = this.state.packages.map(x => { return { id: x.id, version: x.specificVersion } }); model.packages = packages; this.props.onSubmit(model); } cancel() { this.props.onCancel(); } onPackagesChange(data) { this.setState({ packages: data }); } render() { return ( <div> <h2>Edit Packages</h2> <Form onSubmit={this.submit} onCancel={this.props.onCancel} onDelete={this.props.onDelete ? this.props.onDelete : null} className="form-horizontal form-margin" saving={this.props.saving} deleting={this.props.deleting} saved={this.props.saved} saveError={this.props.saveError} saveErrors={this.props.saveErrors} > <fieldset> {this.props.packagesList && <PackagesMultiSelector packages={this.props.packagesList} values={this.state.packages} onChange={this.onPackagesChange.bind(this)} /> } </fieldset> </Form> </div> ); } }
ajax/libs/highmaps/1.0.4/highmaps.src.js
sufuf3/cdnjs
// ==ClosureCompiler== // @compilation_level SIMPLE_OPTIMIZATIONS /** * @license Highmaps JS v1.0.4 (2014-09-02) * * (c) 2009-2014 Torstein Honsi * * License: www.highcharts.com/license */ // JSLint options: /*global Highcharts, HighchartsAdapter, document, window, navigator, setInterval, clearInterval, clearTimeout, setTimeout, location, jQuery, $, console, each, grep */ /*jslint ass: true, sloppy: true, forin: true, plusplus: true, nomen: true, vars: true, regexp: true, newcap: true, browser: true, continue: true, white: true */ (function () { // encapsulated variables var UNDEFINED, doc = document, win = window, math = Math, mathRound = math.round, mathFloor = math.floor, mathCeil = math.ceil, mathMax = math.max, mathMin = math.min, mathAbs = math.abs, mathCos = math.cos, mathSin = math.sin, mathPI = math.PI, deg2rad = mathPI * 2 / 360, // some variables userAgent = navigator.userAgent, isOpera = win.opera, isIE = /msie/i.test(userAgent) && !isOpera, docMode8 = doc.documentMode === 8, isWebKit = /AppleWebKit/.test(userAgent), isFirefox = /Firefox/.test(userAgent), isTouchDevice = /(Mobile|Android|Windows Phone)/.test(userAgent), SVG_NS = 'http://www.w3.org/2000/svg', hasSVG = !!doc.createElementNS && !!doc.createElementNS(SVG_NS, 'svg').createSVGRect, hasBidiBug = isFirefox && parseInt(userAgent.split('Firefox/')[1], 10) < 4, // issue #38 useCanVG = !hasSVG && !isIE && !!doc.createElement('canvas').getContext, Renderer, hasTouch, symbolSizes = {}, idCounter = 0, garbageBin, defaultOptions, dateFormat, // function globalAnimation, pathAnim, timeUnits, error, noop = function () { return UNDEFINED; }, charts = [], chartCount = 0, PRODUCT = 'Highmaps', VERSION = '1.0.4', // some constants for frequently used strings DIV = 'div', ABSOLUTE = 'absolute', RELATIVE = 'relative', HIDDEN = 'hidden', PREFIX = 'highcharts-', VISIBLE = 'visible', PX = 'px', NONE = 'none', M = 'M', L = 'L', numRegex = /^[0-9]+$/, NORMAL_STATE = '', HOVER_STATE = 'hover', SELECT_STATE = 'select', // Object for extending Axis AxisPlotLineOrBandExtension, // constants for attributes STROKE_WIDTH = 'stroke-width', // time methods, changed based on whether or not UTC is used Date, // Allow using a different Date class makeTime, timezoneOffset, getMinutes, getHours, getDay, getDate, getMonth, getFullYear, setMinutes, setHours, setDate, setMonth, setFullYear, // lookup over the types and the associated classes seriesTypes = {}, Highcharts; // The Highcharts namespace if (win.Highcharts) { error(16, true); } else { Highcharts = win.Highcharts = {}; } /** * Extend an object with the members of another * @param {Object} a The object to be extended * @param {Object} b The object to add to the first one */ function extend(a, b) { var n; if (!a) { a = {}; } for (n in b) { a[n] = b[n]; } return a; } /** * Deep merge two or more objects and return a third object. If the first argument is * true, the contents of the second object is copied into the first object. * Previously this function redirected to jQuery.extend(true), but this had two limitations. * First, it deep merged arrays, which lead to workarounds in Highcharts. Second, * it copied properties from extended prototypes. */ function merge() { var i, args = arguments, len, ret = {}, doCopy = function (copy, original) { var value, key; // An object is replacing a primitive if (typeof copy !== 'object') { copy = {}; } for (key in original) { if (original.hasOwnProperty(key)) { value = original[key]; // Copy the contents of objects, but not arrays or DOM nodes if (value && typeof value === 'object' && Object.prototype.toString.call(value) !== '[object Array]' && key !== 'renderTo' && typeof value.nodeType !== 'number') { copy[key] = doCopy(copy[key] || {}, value); // Primitives and arrays are copied over directly } else { copy[key] = original[key]; } } } return copy; }; // If first argument is true, copy into the existing object. Used in setOptions. if (args[0] === true) { ret = args[1]; args = Array.prototype.slice.call(args, 2); } // For each argument, extend the return len = args.length; for (i = 0; i < len; i++) { ret = doCopy(ret, args[i]); } return ret; } /** * Shortcut for parseInt * @param {Object} s * @param {Number} mag Magnitude */ function pInt(s, mag) { return parseInt(s, mag || 10); } /** * Check for string * @param {Object} s */ function isString(s) { return typeof s === 'string'; } /** * Check for object * @param {Object} obj */ function isObject(obj) { return obj && typeof obj === 'object'; } /** * Check for array * @param {Object} obj */ function isArray(obj) { return Object.prototype.toString.call(obj) === '[object Array]'; } /** * Check for number * @param {Object} n */ function isNumber(n) { return typeof n === 'number'; } function log2lin(num) { return math.log(num) / math.LN10; } function lin2log(num) { return math.pow(10, num); } /** * Remove last occurence of an item from an array * @param {Array} arr * @param {Mixed} item */ function erase(arr, item) { var i = arr.length; while (i--) { if (arr[i] === item) { arr.splice(i, 1); break; } } //return arr; } /** * Returns true if the object is not null or undefined. Like MooTools' $.defined. * @param {Object} obj */ function defined(obj) { return obj !== UNDEFINED && obj !== null; } /** * Set or get an attribute or an object of attributes. Can't use jQuery attr because * it attempts to set expando properties on the SVG element, which is not allowed. * * @param {Object} elem The DOM element to receive the attribute(s) * @param {String|Object} prop The property or an abject of key-value pairs * @param {String} value The value if a single property is set */ function attr(elem, prop, value) { var key, ret; // if the prop is a string if (isString(prop)) { // set the value if (defined(value)) { elem.setAttribute(prop, value); // get the value } else if (elem && elem.getAttribute) { // elem not defined when printing pie demo... ret = elem.getAttribute(prop); } // else if prop is defined, it is a hash of key/value pairs } else if (defined(prop) && isObject(prop)) { for (key in prop) { elem.setAttribute(key, prop[key]); } } return ret; } /** * Check if an element is an array, and if not, make it into an array. Like * MooTools' $.splat. */ function splat(obj) { return isArray(obj) ? obj : [obj]; } /** * Return the first value that is defined. Like MooTools' $.pick. */ function pick() { var args = arguments, i, arg, length = args.length; for (i = 0; i < length; i++) { arg = args[i]; if (arg !== UNDEFINED && arg !== null) { return arg; } } } /** * Set CSS on a given element * @param {Object} el * @param {Object} styles Style object with camel case property names */ function css(el, styles) { if (isIE && !hasSVG) { // #2686 if (styles && styles.opacity !== UNDEFINED) { styles.filter = 'alpha(opacity=' + (styles.opacity * 100) + ')'; } } extend(el.style, styles); } /** * Utility function to create element with attributes and styles * @param {Object} tag * @param {Object} attribs * @param {Object} styles * @param {Object} parent * @param {Object} nopad */ function createElement(tag, attribs, styles, parent, nopad) { var el = doc.createElement(tag); if (attribs) { extend(el, attribs); } if (nopad) { css(el, {padding: 0, border: NONE, margin: 0}); } if (styles) { css(el, styles); } if (parent) { parent.appendChild(el); } return el; } /** * Extend a prototyped class by new members * @param {Object} parent * @param {Object} members */ function extendClass(parent, members) { var object = function () { return UNDEFINED; }; object.prototype = new parent(); extend(object.prototype, members); return object; } /** * Format a number and return a string based on input settings * @param {Number} number The input number to format * @param {Number} decimals The amount of decimals * @param {String} decPoint The decimal point, defaults to the one given in the lang options * @param {String} thousandsSep The thousands separator, defaults to the one given in the lang options */ function numberFormat(number, decimals, decPoint, thousandsSep) { var externalFn = Highcharts.numberFormat, lang = defaultOptions.lang, // http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_number_format/ n = +number || 0, c = decimals === -1 ? (n.toString().split('.')[1] || '').length : // preserve decimals (isNaN(decimals = mathAbs(decimals)) ? 2 : decimals), d = decPoint === undefined ? lang.decimalPoint : decPoint, t = thousandsSep === undefined ? lang.thousandsSep : thousandsSep, s = n < 0 ? "-" : "", i = String(pInt(n = mathAbs(n).toFixed(c))), j = i.length > 3 ? i.length % 3 : 0; return externalFn !== numberFormat ? externalFn(number, decimals, decPoint, thousandsSep) : (s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + mathAbs(n - i).toFixed(c).slice(2) : "")); } /** * Pad a string to a given length by adding 0 to the beginning * @param {Number} number * @param {Number} length */ function pad(number, length) { // Create an array of the remaining length +1 and join it with 0's return new Array((length || 2) + 1 - String(number).length).join(0) + number; } /** * Wrap a method with extended functionality, preserving the original function * @param {Object} obj The context object that the method belongs to * @param {String} method The name of the method to extend * @param {Function} func A wrapper function callback. This function is called with the same arguments * as the original function, except that the original function is unshifted and passed as the first * argument. */ function wrap(obj, method, func) { var proceed = obj[method]; obj[method] = function () { var args = Array.prototype.slice.call(arguments); args.unshift(proceed); return func.apply(this, args); }; } /** * Based on http://www.php.net/manual/en/function.strftime.php * @param {String} format * @param {Number} timestamp * @param {Boolean} capitalize */ dateFormat = function (format, timestamp, capitalize) { if (!defined(timestamp) || isNaN(timestamp)) { return 'Invalid date'; } format = pick(format, '%Y-%m-%d %H:%M:%S'); var date = new Date(timestamp - timezoneOffset), key, // used in for constuct below // get the basic time values hours = date[getHours](), day = date[getDay](), dayOfMonth = date[getDate](), month = date[getMonth](), fullYear = date[getFullYear](), lang = defaultOptions.lang, langWeekdays = lang.weekdays, // List all format keys. Custom formats can be added from the outside. replacements = extend({ // Day 'a': langWeekdays[day].substr(0, 3), // Short weekday, like 'Mon' 'A': langWeekdays[day], // Long weekday, like 'Monday' 'd': pad(dayOfMonth), // Two digit day of the month, 01 to 31 'e': dayOfMonth, // Day of the month, 1 through 31 // Week (none implemented) //'W': weekNumber(), // Month 'b': lang.shortMonths[month], // Short month, like 'Jan' 'B': lang.months[month], // Long month, like 'January' 'm': pad(month + 1), // Two digit month number, 01 through 12 // Year 'y': fullYear.toString().substr(2, 2), // Two digits year, like 09 for 2009 'Y': fullYear, // Four digits year, like 2009 // Time 'H': pad(hours), // Two digits hours in 24h format, 00 through 23 'I': pad((hours % 12) || 12), // Two digits hours in 12h format, 00 through 11 'l': (hours % 12) || 12, // Hours in 12h format, 1 through 12 'M': pad(date[getMinutes]()), // Two digits minutes, 00 through 59 'p': hours < 12 ? 'AM' : 'PM', // Upper case AM or PM 'P': hours < 12 ? 'am' : 'pm', // Lower case AM or PM 'S': pad(date.getSeconds()), // Two digits seconds, 00 through 59 'L': pad(mathRound(timestamp % 1000), 3) // Milliseconds (naming from Ruby) }, Highcharts.dateFormats); // do the replaces for (key in replacements) { while (format.indexOf('%' + key) !== -1) { // regex would do it in one line, but this is faster format = format.replace('%' + key, typeof replacements[key] === 'function' ? replacements[key](timestamp) : replacements[key]); } } // Optionally capitalize the string and return return capitalize ? format.substr(0, 1).toUpperCase() + format.substr(1) : format; }; /** * Format a single variable. Similar to sprintf, without the % prefix. */ function formatSingle(format, val) { var floatRegex = /f$/, decRegex = /\.([0-9])/, lang = defaultOptions.lang, decimals; if (floatRegex.test(format)) { // float decimals = format.match(decRegex); decimals = decimals ? decimals[1] : -1; if (val !== null) { val = numberFormat( val, decimals, lang.decimalPoint, format.indexOf(',') > -1 ? lang.thousandsSep : '' ); } } else { val = dateFormat(format, val); } return val; } /** * Format a string according to a subset of the rules of Python's String.format method. */ function format(str, ctx) { var splitter = '{', isInside = false, segment, valueAndFormat, path, i, len, ret = [], val, index; while ((index = str.indexOf(splitter)) !== -1) { segment = str.slice(0, index); if (isInside) { // we're on the closing bracket looking back valueAndFormat = segment.split(':'); path = valueAndFormat.shift().split('.'); // get first and leave format len = path.length; val = ctx; // Assign deeper paths for (i = 0; i < len; i++) { val = val[path[i]]; } // Format the replacement if (valueAndFormat.length) { val = formatSingle(valueAndFormat.join(':'), val); } // Push the result and advance the cursor ret.push(val); } else { ret.push(segment); } str = str.slice(index + 1); // the rest isInside = !isInside; // toggle splitter = isInside ? '}' : '{'; // now look for next matching bracket } ret.push(str); return ret.join(''); } /** * Get the magnitude of a number */ function getMagnitude(num) { return math.pow(10, mathFloor(math.log(num) / math.LN10)); } /** * Take an interval and normalize it to multiples of 1, 2, 2.5 and 5 * @param {Number} interval * @param {Array} multiples * @param {Number} magnitude * @param {Object} options */ function normalizeTickInterval(interval, multiples, magnitude, allowDecimals) { var normalized, i; // round to a tenfold of 1, 2, 2.5 or 5 magnitude = pick(magnitude, 1); normalized = interval / magnitude; // multiples for a linear scale if (!multiples) { multiples = [1, 2, 2.5, 5, 10]; // the allowDecimals option if (allowDecimals === false) { if (magnitude === 1) { multiples = [1, 2, 5, 10]; } else if (magnitude <= 0.1) { multiples = [1 / magnitude]; } } } // normalize the interval to the nearest multiple for (i = 0; i < multiples.length; i++) { interval = multiples[i]; if (normalized <= (multiples[i] + (multiples[i + 1] || multiples[i])) / 2) { break; } } // multiply back to the correct magnitude interval *= magnitude; return interval; } /** * Utility method that sorts an object array and keeping the order of equal items. * ECMA script standard does not specify the behaviour when items are equal. */ function stableSort(arr, sortFunction) { var length = arr.length, sortValue, i; // Add index to each item for (i = 0; i < length; i++) { arr[i].ss_i = i; // stable sort index } arr.sort(function (a, b) { sortValue = sortFunction(a, b); return sortValue === 0 ? a.ss_i - b.ss_i : sortValue; }); // Remove index from items for (i = 0; i < length; i++) { delete arr[i].ss_i; // stable sort index } } /** * Non-recursive method to find the lowest member of an array. Math.min raises a maximum * call stack size exceeded error in Chrome when trying to apply more than 150.000 points. This * method is slightly slower, but safe. */ function arrayMin(data) { var i = data.length, min = data[0]; while (i--) { if (data[i] < min) { min = data[i]; } } return min; } /** * Non-recursive method to find the lowest member of an array. Math.min raises a maximum * call stack size exceeded error in Chrome when trying to apply more than 150.000 points. This * method is slightly slower, but safe. */ function arrayMax(data) { var i = data.length, max = data[0]; while (i--) { if (data[i] > max) { max = data[i]; } } return max; } /** * Utility method that destroys any SVGElement or VMLElement that are properties on the given object. * It loops all properties and invokes destroy if there is a destroy method. The property is * then delete'ed. * @param {Object} The object to destroy properties on * @param {Object} Exception, do not destroy this property, only delete it. */ function destroyObjectProperties(obj, except) { var n; for (n in obj) { // If the object is non-null and destroy is defined if (obj[n] && obj[n] !== except && obj[n].destroy) { // Invoke the destroy obj[n].destroy(); } // Delete the property from the object. delete obj[n]; } } /** * Discard an element by moving it to the bin and delete * @param {Object} The HTML node to discard */ function discardElement(element) { // create a garbage bin element, not part of the DOM if (!garbageBin) { garbageBin = createElement(DIV); } // move the node and empty bin if (element) { garbageBin.appendChild(element); } garbageBin.innerHTML = ''; } /** * Provide error messages for debugging, with links to online explanation */ error = function (code, stop) { var msg = 'Highcharts error #' + code + ': www.highcharts.com/errors/' + code; if (stop) { throw msg; } // else ... if (win.console) { console.log(msg); } }; /** * Fix JS round off float errors * @param {Number} num */ function correctFloat(num) { return parseFloat( num.toPrecision(14) ); } /** * Set the global animation to either a given value, or fall back to the * given chart's animation option * @param {Object} animation * @param {Object} chart */ function setAnimation(animation, chart) { globalAnimation = pick(animation, chart.animation); } /** * The time unit lookup */ timeUnits = { millisecond: 1, second: 1000, minute: 60000, hour: 3600000, day: 24 * 3600000, week: 7 * 24 * 3600000, month: 31 * 24 * 3600000, year: 31556952000 }; /** * Path interpolation algorithm used across adapters */ pathAnim = { /** * Prepare start and end values so that the path can be animated one to one */ init: function (elem, fromD, toD) { fromD = fromD || ''; var shift = elem.shift, bezier = fromD.indexOf('C') > -1, numParams = bezier ? 7 : 3, endLength, slice, i, start = fromD.split(' '), end = [].concat(toD), // copy startBaseLine, endBaseLine, sixify = function (arr) { // in splines make move points have six parameters like bezier curves i = arr.length; while (i--) { if (arr[i] === M) { arr.splice(i + 1, 0, arr[i + 1], arr[i + 2], arr[i + 1], arr[i + 2]); } } }; if (bezier) { sixify(start); sixify(end); } // pull out the base lines before padding if (elem.isArea) { startBaseLine = start.splice(start.length - 6, 6); endBaseLine = end.splice(end.length - 6, 6); } // if shifting points, prepend a dummy point to the end path if (shift <= end.length / numParams && start.length === end.length) { while (shift--) { end = [].concat(end).splice(0, numParams).concat(end); } } elem.shift = 0; // reset for following animations // copy and append last point until the length matches the end length if (start.length) { endLength = end.length; while (start.length < endLength) { //bezier && sixify(start); slice = [].concat(start).splice(start.length - numParams, numParams); if (bezier) { // disable first control point slice[numParams - 6] = slice[numParams - 2]; slice[numParams - 5] = slice[numParams - 1]; } start = start.concat(slice); } } if (startBaseLine) { // append the base lines for areas start = start.concat(startBaseLine); end = end.concat(endBaseLine); } return [start, end]; }, /** * Interpolate each value of the path and return the array */ step: function (start, end, pos, complete) { var ret = [], i = start.length, startVal; if (pos === 1) { // land on the final path without adjustment points appended in the ends ret = complete; } else if (i === end.length && pos < 1) { while (i--) { startVal = parseFloat(start[i]); ret[i] = isNaN(startVal) ? // a letter instruction like M or L start[i] : pos * (parseFloat(end[i] - startVal)) + startVal; } } else { // if animation is finished or length not matching, land on right value ret = end; } return ret; } }; (function ($) { /** * The default HighchartsAdapter for jQuery */ win.HighchartsAdapter = win.HighchartsAdapter || ($ && { /** * Initialize the adapter by applying some extensions to jQuery */ init: function (pathAnim) { // extend the animate function to allow SVG animations var Fx = $.fx; /*jslint unparam: true*//* allow unused param x in this function */ $.extend($.easing, { easeOutQuad: function (x, t, b, c, d) { return -c * (t /= d) * (t - 2) + b; } }); /*jslint unparam: false*/ // extend some methods to check for elem.attr, which means it is a Highcharts SVG object $.each(['cur', '_default', 'width', 'height', 'opacity'], function (i, fn) { var obj = Fx.step, base; // Handle different parent objects if (fn === 'cur') { obj = Fx.prototype; // 'cur', the getter, relates to Fx.prototype } else if (fn === '_default' && $.Tween) { // jQuery 1.8 model obj = $.Tween.propHooks[fn]; fn = 'set'; } // Overwrite the method base = obj[fn]; if (base) { // step.width and step.height don't exist in jQuery < 1.7 // create the extended function replacement obj[fn] = function (fx) { var elem; // Fx.prototype.cur does not use fx argument fx = i ? fx : this; // Don't run animations on textual properties like align (#1821) if (fx.prop === 'align') { return; } // shortcut elem = fx.elem; // Fx.prototype.cur returns the current value. The other ones are setters // and returning a value has no effect. return elem.attr ? // is SVG element wrapper elem.attr(fx.prop, fn === 'cur' ? UNDEFINED : fx.now) : // apply the SVG wrapper's method base.apply(this, arguments); // use jQuery's built-in method }; } }); // Extend the opacity getter, needed for fading opacity with IE9 and jQuery 1.10+ wrap($.cssHooks.opacity, 'get', function (proceed, elem, computed) { return elem.attr ? (elem.opacity || 0) : proceed.call(this, elem, computed); }); // Define the setter function for d (path definitions) this.addAnimSetter('d', function (fx) { var elem = fx.elem, ends; // Normally start and end should be set in state == 0, but sometimes, // for reasons unknown, this doesn't happen. Perhaps state == 0 is skipped // in these cases if (!fx.started) { ends = pathAnim.init(elem, elem.d, elem.toD); fx.start = ends[0]; fx.end = ends[1]; fx.started = true; } // Interpolate each value of the path elem.attr('d', pathAnim.step(fx.start, fx.end, fx.pos, elem.toD)); }); /** * Utility for iterating over an array. Parameters are reversed compared to jQuery. * @param {Array} arr * @param {Function} fn */ this.each = Array.prototype.forEach ? function (arr, fn) { // modern browsers return Array.prototype.forEach.call(arr, fn); } : function (arr, fn) { // legacy var i, len = arr.length; for (i = 0; i < len; i++) { if (fn.call(arr[i], arr[i], i, arr) === false) { return i; } } }; /** * Register Highcharts as a plugin in the respective framework */ $.fn.highcharts = function () { var constr = 'Chart', // default constructor args = arguments, options, ret, chart; if (this[0]) { if (isString(args[0])) { constr = args[0]; args = Array.prototype.slice.call(args, 1); } options = args[0]; // Create the chart if (options !== UNDEFINED) { /*jslint unused:false*/ options.chart = options.chart || {}; options.chart.renderTo = this[0]; chart = new Highcharts[constr](options, args[1]); ret = this; /*jslint unused:true*/ } // When called without parameters or with the return argument, get a predefined chart if (options === UNDEFINED) { ret = charts[attr(this[0], 'data-highcharts-chart')]; } } return ret; }; }, /** * Add an animation setter for a specific property */ addAnimSetter: function (prop, setter) { // jQuery 1.8 style if ($.Tween) { $.Tween.propHooks[prop] = { set: setter }; // pre 1.8 } else { $.fx.step[prop] = setter; } }, /** * Downloads a script and executes a callback when done. * @param {String} scriptLocation * @param {Function} callback */ getScript: $.getScript, /** * Return the index of an item in an array, or -1 if not found */ inArray: $.inArray, /** * A direct link to jQuery methods. MooTools and Prototype adapters must be implemented for each case of method. * @param {Object} elem The HTML element * @param {String} method Which method to run on the wrapped element */ adapterRun: function (elem, method) { return $(elem)[method](); }, /** * Filter an array */ grep: $.grep, /** * Map an array * @param {Array} arr * @param {Function} fn */ map: function (arr, fn) { //return jQuery.map(arr, fn); var results = [], i = 0, len = arr.length; for (; i < len; i++) { results[i] = fn.call(arr[i], arr[i], i, arr); } return results; }, /** * Get the position of an element relative to the top left of the page */ offset: function (el) { return $(el).offset(); }, /** * Add an event listener * @param {Object} el A HTML element or custom object * @param {String} event The event type * @param {Function} fn The event handler */ addEvent: function (el, event, fn) { $(el).bind(event, fn); }, /** * Remove event added with addEvent * @param {Object} el The object * @param {String} eventType The event type. Leave blank to remove all events. * @param {Function} handler The function to remove */ removeEvent: function (el, eventType, handler) { // workaround for jQuery issue with unbinding custom events: // http://forum.jQuery.com/topic/javascript-error-when-unbinding-a-custom-event-using-jQuery-1-4-2 var func = doc.removeEventListener ? 'removeEventListener' : 'detachEvent'; if (doc[func] && el && !el[func]) { el[func] = function () {}; } $(el).unbind(eventType, handler); }, /** * Fire an event on a custom object * @param {Object} el * @param {String} type * @param {Object} eventArguments * @param {Function} defaultFunction */ fireEvent: function (el, type, eventArguments, defaultFunction) { var event = $.Event(type), detachedType = 'detached' + type, defaultPrevented; // Remove warnings in Chrome when accessing returnValue (#2790), layerX and layerY. Although Highcharts // never uses these properties, Chrome includes them in the default click event and // raises the warning when they are copied over in the extend statement below. // // To avoid problems in IE (see #1010) where we cannot delete the properties and avoid // testing if they are there (warning in chrome) the only option is to test if running IE. if (!isIE && eventArguments) { delete eventArguments.layerX; delete eventArguments.layerY; delete eventArguments.returnValue; } extend(event, eventArguments); // Prevent jQuery from triggering the object method that is named the // same as the event. For example, if the event is 'select', jQuery // attempts calling el.select and it goes into a loop. if (el[type]) { el[detachedType] = el[type]; el[type] = null; } // Wrap preventDefault and stopPropagation in try/catch blocks in // order to prevent JS errors when cancelling events on non-DOM // objects. #615. /*jslint unparam: true*/ $.each(['preventDefault', 'stopPropagation'], function (i, fn) { var base = event[fn]; event[fn] = function () { try { base.call(event); } catch (e) { if (fn === 'preventDefault') { defaultPrevented = true; } } }; }); /*jslint unparam: false*/ // trigger it $(el).trigger(event); // attach the method if (el[detachedType]) { el[type] = el[detachedType]; el[detachedType] = null; } if (defaultFunction && !event.isDefaultPrevented() && !defaultPrevented) { defaultFunction(event); } }, /** * Extension method needed for MooTools */ washMouseEvent: function (e) { var ret = e.originalEvent || e; // computed by jQuery, needed by IE8 if (ret.pageX === UNDEFINED) { // #1236 ret.pageX = e.pageX; ret.pageY = e.pageY; } return ret; }, /** * Animate a HTML element or SVG element wrapper * @param {Object} el * @param {Object} params * @param {Object} options jQuery-like animation options: duration, easing, callback */ animate: function (el, params, options) { var $el = $(el); if (!el.style) { el.style = {}; // #1881 } if (params.d) { el.toD = params.d; // keep the array form for paths, used in $.fx.step.d params.d = 1; // because in jQuery, animating to an array has a different meaning } $el.stop(); if (params.opacity !== UNDEFINED && el.attr) { params.opacity += 'px'; // force jQuery to use same logic as width and height (#2161) } el.hasAnim = 1; // #3342 $el.animate(params, options); }, /** * Stop running animation */ stop: function (el) { if (el.hasAnim) { // #3342, memory leak on calling $(el) from destroy $(el).stop(); } } }); }(win.jQuery)); // check for a custom HighchartsAdapter defined prior to this file var globalAdapter = win.HighchartsAdapter, adapter = globalAdapter || {}; // Initialize the adapter if (globalAdapter) { globalAdapter.init.call(globalAdapter, pathAnim); } // Utility functions. If the HighchartsAdapter is not defined, adapter is an empty object // and all the utility functions will be null. In that case they are populated by the // default adapters below. var adapterRun = adapter.adapterRun, getScript = adapter.getScript, inArray = adapter.inArray, each = adapter.each, grep = adapter.grep, offset = adapter.offset, map = adapter.map, addEvent = adapter.addEvent, removeEvent = adapter.removeEvent, fireEvent = adapter.fireEvent, washMouseEvent = adapter.washMouseEvent, animate = adapter.animate, stop = adapter.stop; /* **************************************************************************** * Handle the options * *****************************************************************************/ var defaultLabelOptions = { enabled: true, // rotation: 0, // align: 'center', x: 0, y: 15, /*formatter: function () { return this.value; },*/ style: { color: '#606060', cursor: 'default', fontSize: '11px' } }; defaultOptions = { colors: ['#7cb5ec', '#434348', '#90ed7d', '#f7a35c', '#8085e9', '#f15c80', '#e4d354', '#8085e8', '#8d4653', '#91e8e1'], symbols: ['circle', 'diamond', 'square', 'triangle', 'triangle-down'], lang: { loading: 'Loading...', 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'], weekdays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], decimalPoint: '.', numericSymbols: ['k', 'M', 'G', 'T', 'P', 'E'], // SI prefixes used in axis labels resetZoom: 'Reset zoom', resetZoomTitle: 'Reset zoom level 1:1', thousandsSep: ',' }, global: { useUTC: true, //timezoneOffset: 0, canvasToolsURL: 'http://code.highcharts.com/maps/1.0.4/modules/canvas-tools.js', VMLRadialGradientURL: 'http://code.highcharts.com/maps/1.0.4/gfx/vml-radial-gradient.png' }, chart: { //animation: true, //alignTicks: false, //reflow: true, //className: null, //events: { load, selection }, //margin: [null], //marginTop: null, //marginRight: null, //marginBottom: null, //marginLeft: null, borderColor: '#4572A7', //borderWidth: 0, borderRadius: 0, defaultSeriesType: 'line', ignoreHiddenSeries: true, //inverted: false, //shadow: false, spacing: [10, 10, 15, 10], //spacingTop: 10, //spacingRight: 10, //spacingBottom: 15, //spacingLeft: 10, //style: { // fontFamily: '"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif', // default font // fontSize: '12px' //}, backgroundColor: '#FFFFFF', //plotBackgroundColor: null, plotBorderColor: '#C0C0C0', //plotBorderWidth: 0, //plotShadow: false, //zoomType: '' resetZoomButton: { theme: { zIndex: 20 }, position: { align: 'right', x: -10, //verticalAlign: 'top', y: 10 } // relativeTo: 'plot' } }, title: { text: 'Chart title', align: 'center', // floating: false, margin: 15, // x: 0, // verticalAlign: 'top', // y: null, style: { color: '#333333', fontSize: '18px' } }, subtitle: { text: '', align: 'center', // floating: false // x: 0, // verticalAlign: 'top', // y: null, style: { color: '#555555' } }, plotOptions: { line: { // base series options allowPointSelect: false, showCheckbox: false, animation: { duration: 1000 }, //connectNulls: false, //cursor: 'default', //clip: true, //dashStyle: null, //enableMouseTracking: true, events: {}, //legendIndex: 0, //linecap: 'round', lineWidth: 2, //shadow: false, // stacking: null, marker: { //enabled: true, //symbol: null, lineWidth: 0, radius: 4, lineColor: '#FFFFFF', //fillColor: null, states: { // states for a single point hover: { enabled: true, lineWidthPlus: 1, radiusPlus: 2 }, select: { fillColor: '#FFFFFF', lineColor: '#000000', lineWidth: 2 } } }, point: { events: {} }, dataLabels: merge(defaultLabelOptions, { align: 'center', //defer: true, enabled: false, formatter: function () { return this.y === null ? '' : numberFormat(this.y, -1); }, verticalAlign: 'bottom', // above singular point y: 0 // backgroundColor: undefined, // borderColor: undefined, // borderRadius: undefined, // borderWidth: undefined, // padding: 3, // shadow: false }), cropThreshold: 300, // draw points outside the plot area when the number of points is less than this pointRange: 0, //pointStart: 0, //pointInterval: 1, //showInLegend: null, // auto: true for standalone series, false for linked series states: { // states for the entire series hover: { //enabled: false, lineWidthPlus: 1, marker: { // lineWidth: base + 1, // radius: base + 1 }, halo: { size: 10, opacity: 0.25 } }, select: { marker: {} } }, stickyTracking: true, //tooltip: { //pointFormat: '<span style="color:{series.color}">\u25CF</span> {series.name}: <b>{point.y}</b>' //valueDecimals: null, //xDateFormat: '%A, %b %e, %Y', //valuePrefix: '', //ySuffix: '' //} turboThreshold: 1000 // zIndex: null } }, labels: { //items: [], style: { //font: defaultFont, position: ABSOLUTE, color: '#3E576F' } }, legend: { enabled: true, align: 'center', //floating: false, layout: 'horizontal', labelFormatter: function () { return this.name; }, //borderWidth: 0, borderColor: '#909090', borderRadius: 0, navigation: { // animation: true, activeColor: '#274b6d', // arrowSize: 12 inactiveColor: '#CCC' // style: {} // text styles }, // margin: 20, // reversed: false, shadow: false, // backgroundColor: null, /*style: { padding: '5px' },*/ itemStyle: { color: '#333333', fontSize: '12px', fontWeight: 'bold' }, itemHoverStyle: { //cursor: 'pointer', removed as of #601 color: '#000' }, itemHiddenStyle: { color: '#CCC' }, itemCheckboxStyle: { position: ABSOLUTE, width: '13px', // for IE precision height: '13px' }, // itemWidth: undefined, // symbolRadius: 0, // symbolWidth: 16, symbolPadding: 5, verticalAlign: 'bottom', // width: undefined, x: 0, y: 0, title: { //text: null, style: { fontWeight: 'bold' } } }, loading: { // hideDuration: 100, labelStyle: { fontWeight: 'bold', position: RELATIVE, top: '45%' }, // showDuration: 0, style: { position: ABSOLUTE, backgroundColor: 'white', opacity: 0.5, textAlign: 'center' } }, tooltip: { enabled: true, animation: hasSVG, //crosshairs: null, backgroundColor: 'rgba(249, 249, 249, .85)', borderWidth: 1, borderRadius: 3, dateTimeLabelFormats: { millisecond: '%A, %b %e, %H:%M:%S.%L', second: '%A, %b %e, %H:%M:%S', minute: '%A, %b %e, %H:%M', hour: '%A, %b %e, %H:%M', day: '%A, %b %e, %Y', week: 'Week from %A, %b %e, %Y', month: '%B %Y', year: '%Y' }, //formatter: defaultFormatter, headerFormat: '<span style="font-size: 10px">{point.key}</span><br/>', pointFormat: '<span style="color:{series.color}">\u25CF</span> {series.name}: <b>{point.y}</b><br/>', shadow: true, //shape: 'callout', //shared: false, snap: isTouchDevice ? 25 : 10, style: { color: '#333333', cursor: 'default', fontSize: '12px', padding: '8px', whiteSpace: 'nowrap' } //xDateFormat: '%A, %b %e, %Y', //valueDecimals: null, //valuePrefix: '', //valueSuffix: '' }, credits: { enabled: true, text: 'Highcharts.com', href: 'http://www.highcharts.com', position: { align: 'right', x: -10, verticalAlign: 'bottom', y: -5 }, style: { cursor: 'pointer', color: '#909090', fontSize: '9px' } } }; // Series defaults var defaultPlotOptions = defaultOptions.plotOptions, defaultSeriesOptions = defaultPlotOptions.line; // set the default time methods setTimeMethods(); /** * Set the time methods globally based on the useUTC option. Time method can be either * local time or UTC (default). */ function setTimeMethods() { var useUTC = defaultOptions.global.useUTC, GET = useUTC ? 'getUTC' : 'get', SET = useUTC ? 'setUTC' : 'set'; Date = defaultOptions.global.Date || window.Date; timezoneOffset = ((useUTC && defaultOptions.global.timezoneOffset) || 0) * 60000; makeTime = useUTC ? Date.UTC : function (year, month, date, hours, minutes, seconds) { return new Date( year, month, pick(date, 1), pick(hours, 0), pick(minutes, 0), pick(seconds, 0) ).getTime(); }; getMinutes = GET + 'Minutes'; getHours = GET + 'Hours'; getDay = GET + 'Day'; getDate = GET + 'Date'; getMonth = GET + 'Month'; getFullYear = GET + 'FullYear'; setMinutes = SET + 'Minutes'; setHours = SET + 'Hours'; setDate = SET + 'Date'; setMonth = SET + 'Month'; setFullYear = SET + 'FullYear'; } /** * Merge the default options with custom options and return the new options structure * @param {Object} options The new custom options */ function setOptions(options) { // Copy in the default options defaultOptions = merge(true, defaultOptions, options); // Apply UTC setTimeMethods(); return defaultOptions; } /** * Get the updated default options. Until 3.0.7, merely exposing defaultOptions for outside modules * wasn't enough because the setOptions method created a new object. */ function getOptions() { return defaultOptions; } /** * Handle color operations. The object methods are chainable. * @param {String} input The input color in either rbga or hex format */ var rgbaRegEx = /rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]?(?:\.[0-9]+)?)\s*\)/, hexRegEx = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/, rgbRegEx = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/; var Color = function (input) { // declare variables var rgba = [], result, stops; /** * Parse the input color to rgba array * @param {String} input */ function init(input) { // Gradients if (input && input.stops) { stops = map(input.stops, function (stop) { return Color(stop[1]); }); // Solid colors } else { // rgba result = rgbaRegEx.exec(input); if (result) { rgba = [pInt(result[1]), pInt(result[2]), pInt(result[3]), parseFloat(result[4], 10)]; } else { // hex result = hexRegEx.exec(input); if (result) { rgba = [pInt(result[1], 16), pInt(result[2], 16), pInt(result[3], 16), 1]; } else { // rgb result = rgbRegEx.exec(input); if (result) { rgba = [pInt(result[1]), pInt(result[2]), pInt(result[3]), 1]; } } } } } /** * Return the color a specified format * @param {String} format */ function get(format) { var ret; if (stops) { ret = merge(input); ret.stops = [].concat(ret.stops); each(stops, function (stop, i) { ret.stops[i] = [ret.stops[i][0], stop.get(format)]; }); // it's NaN if gradient colors on a column chart } else if (rgba && !isNaN(rgba[0])) { if (format === 'rgb') { ret = 'rgb(' + rgba[0] + ',' + rgba[1] + ',' + rgba[2] + ')'; } else if (format === 'a') { ret = rgba[3]; } else { ret = 'rgba(' + rgba.join(',') + ')'; } } else { ret = input; } return ret; } /** * Brighten the color * @param {Number} alpha */ function brighten(alpha) { if (stops) { each(stops, function (stop) { stop.brighten(alpha); }); } else if (isNumber(alpha) && alpha !== 0) { var i; for (i = 0; i < 3; i++) { rgba[i] += pInt(alpha * 255); if (rgba[i] < 0) { rgba[i] = 0; } if (rgba[i] > 255) { rgba[i] = 255; } } } return this; } /** * Set the color's opacity to a given alpha value * @param {Number} alpha */ function setOpacity(alpha) { rgba[3] = alpha; return this; } // initialize: parse the input init(input); // public methods return { get: get, brighten: brighten, rgba: rgba, setOpacity: setOpacity }; }; /** * A wrapper object for SVG elements */ function SVGElement() {} SVGElement.prototype = { // Default base for animation opacity: 1, // For labels, these CSS properties are applied to the <text> node directly textProps: ['fontSize', 'fontWeight', 'fontFamily', 'color', 'lineHeight', 'width', 'textDecoration', 'textShadow', 'HcTextStroke'], /** * Initialize the SVG renderer * @param {Object} renderer * @param {String} nodeName */ init: function (renderer, nodeName) { var wrapper = this; wrapper.element = nodeName === 'span' ? createElement(nodeName) : doc.createElementNS(SVG_NS, nodeName); wrapper.renderer = renderer; }, /** * Animate a given attribute * @param {Object} params * @param {Number} options The same options as in jQuery animation * @param {Function} complete Function to perform at the end of animation */ animate: function (params, options, complete) { var animOptions = pick(options, globalAnimation, true); stop(this); // stop regardless of animation actually running, or reverting to .attr (#607) if (animOptions) { animOptions = merge(animOptions, {}); //#2625 if (complete) { // allows using a callback with the global animation without overwriting it animOptions.complete = complete; } animate(this, params, animOptions); } else { this.attr(params); if (complete) { complete(); } } return this; }, /** * Build an SVG gradient out of a common JavaScript configuration object */ colorGradient: function (color, prop, elem) { var renderer = this.renderer, colorObject, gradName, gradAttr, gradients, gradientObject, stops, stopColor, stopOpacity, radialReference, n, id, key = []; // Apply linear or radial gradients if (color.linearGradient) { gradName = 'linearGradient'; } else if (color.radialGradient) { gradName = 'radialGradient'; } if (gradName) { gradAttr = color[gradName]; gradients = renderer.gradients; stops = color.stops; radialReference = elem.radialReference; // Keep < 2.2 kompatibility if (isArray(gradAttr)) { color[gradName] = gradAttr = { x1: gradAttr[0], y1: gradAttr[1], x2: gradAttr[2], y2: gradAttr[3], gradientUnits: 'userSpaceOnUse' }; } // Correct the radial gradient for the radial reference system if (gradName === 'radialGradient' && radialReference && !defined(gradAttr.gradientUnits)) { gradAttr = merge(gradAttr, { cx: (radialReference[0] - radialReference[2] / 2) + gradAttr.cx * radialReference[2], cy: (radialReference[1] - radialReference[2] / 2) + gradAttr.cy * radialReference[2], r: gradAttr.r * radialReference[2], gradientUnits: 'userSpaceOnUse' }); } // Build the unique key to detect whether we need to create a new element (#1282) for (n in gradAttr) { if (n !== 'id') { key.push(n, gradAttr[n]); } } for (n in stops) { key.push(stops[n]); } key = key.join(','); // Check if a gradient object with the same config object is created within this renderer if (gradients[key]) { id = gradients[key].attr('id'); } else { // Set the id and create the element gradAttr.id = id = PREFIX + idCounter++; gradients[key] = gradientObject = renderer.createElement(gradName) .attr(gradAttr) .add(renderer.defs); // The gradient needs to keep a list of stops to be able to destroy them gradientObject.stops = []; each(stops, function (stop) { var stopObject; if (stop[1].indexOf('rgba') === 0) { colorObject = Color(stop[1]); stopColor = colorObject.get('rgb'); stopOpacity = colorObject.get('a'); } else { stopColor = stop[1]; stopOpacity = 1; } stopObject = renderer.createElement('stop').attr({ offset: stop[0], 'stop-color': stopColor, 'stop-opacity': stopOpacity }).add(gradientObject); // Add the stop element to the gradient gradientObject.stops.push(stopObject); }); } // Set the reference to the gradient object elem.setAttribute(prop, 'url(' + renderer.url + '#' + id + ')'); } }, /** * Set or get a given attribute * @param {Object|String} hash * @param {Mixed|Undefined} val */ attr: function (hash, val) { var key, value, element = this.element, hasSetSymbolSize, ret = this, skipAttr; // single key-value pair if (typeof hash === 'string' && val !== UNDEFINED) { key = hash; hash = {}; hash[key] = val; } // used as a getter: first argument is a string, second is undefined if (typeof hash === 'string') { ret = (this[hash + 'Getter'] || this._defaultGetter).call(this, hash, element); // setter } else { for (key in hash) { value = hash[key]; skipAttr = false; if (this.symbolName && /^(x|y|width|height|r|start|end|innerR|anchorX|anchorY)/.test(key)) { if (!hasSetSymbolSize) { this.symbolAttr(hash); hasSetSymbolSize = true; } skipAttr = true; } if (this.rotation && (key === 'x' || key === 'y')) { this.doTransform = true; } if (!skipAttr) { (this[key + 'Setter'] || this._defaultSetter).call(this, value, key, element); } // Let the shadow follow the main element if (this.shadows && /^(width|height|visibility|x|y|d|transform|cx|cy|r)$/.test(key)) { this.updateShadows(key, value); } } // Update transform. Do this outside the loop to prevent redundant updating for batch setting // of attributes. if (this.doTransform) { this.updateTransform(); this.doTransform = false; } } return ret; }, updateShadows: function (key, value) { var shadows = this.shadows, i = shadows.length; while (i--) { shadows[i].setAttribute( key, key === 'height' ? mathMax(value - (shadows[i].cutHeight || 0), 0) : key === 'd' ? this.d : value ); } }, /** * Add a class name to an element */ addClass: function (className) { var element = this.element, currentClassName = attr(element, 'class') || ''; if (currentClassName.indexOf(className) === -1) { attr(element, 'class', currentClassName + ' ' + className); } return this; }, /* hasClass and removeClass are not (yet) needed hasClass: function (className) { return attr(this.element, 'class').indexOf(className) !== -1; }, removeClass: function (className) { attr(this.element, 'class', attr(this.element, 'class').replace(className, '')); return this; }, */ /** * If one of the symbol size affecting parameters are changed, * check all the others only once for each call to an element's * .attr() method * @param {Object} hash */ symbolAttr: function (hash) { var wrapper = this; each(['x', 'y', 'r', 'start', 'end', 'width', 'height', 'innerR', 'anchorX', 'anchorY'], function (key) { wrapper[key] = pick(hash[key], wrapper[key]); }); wrapper.attr({ d: wrapper.renderer.symbols[wrapper.symbolName]( wrapper.x, wrapper.y, wrapper.width, wrapper.height, wrapper ) }); }, /** * Apply a clipping path to this object * @param {String} id */ clip: function (clipRect) { return this.attr('clip-path', clipRect ? 'url(' + this.renderer.url + '#' + clipRect.id + ')' : NONE); }, /** * Calculate the coordinates needed for drawing a rectangle crisply and return the * calculated attributes * @param {Number} strokeWidth * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ crisp: function (rect) { var wrapper = this, key, attribs = {}, normalizer, strokeWidth = rect.strokeWidth || wrapper.strokeWidth || 0; normalizer = mathRound(strokeWidth) % 2 / 2; // mathRound because strokeWidth can sometimes have roundoff errors // normalize for crisp edges rect.x = mathFloor(rect.x || wrapper.x || 0) + normalizer; rect.y = mathFloor(rect.y || wrapper.y || 0) + normalizer; rect.width = mathFloor((rect.width || wrapper.width || 0) - 2 * normalizer); rect.height = mathFloor((rect.height || wrapper.height || 0) - 2 * normalizer); rect.strokeWidth = strokeWidth; for (key in rect) { if (wrapper[key] !== rect[key]) { // only set attribute if changed wrapper[key] = attribs[key] = rect[key]; } } return attribs; }, /** * Set styles for the element * @param {Object} styles */ css: function (styles) { var elemWrapper = this, oldStyles = elemWrapper.styles, newStyles = {}, elem = elemWrapper.element, textWidth, n, serializedCss = '', hyphenate, hasNew = !oldStyles; // convert legacy if (styles && styles.color) { styles.fill = styles.color; } // Filter out existing styles to increase performance (#2640) if (oldStyles) { for (n in styles) { if (styles[n] !== oldStyles[n]) { newStyles[n] = styles[n]; hasNew = true; } } } if (hasNew) { textWidth = elemWrapper.textWidth = styles && styles.width && elem.nodeName.toLowerCase() === 'text' && pInt(styles.width); // Merge the new styles with the old ones if (oldStyles) { styles = extend( oldStyles, newStyles ); } // store object elemWrapper.styles = styles; if (textWidth && (useCanVG || (!hasSVG && elemWrapper.renderer.forExport))) { delete styles.width; } // serialize and set style attribute if (isIE && !hasSVG) { css(elemWrapper.element, styles); } else { /*jslint unparam: true*/ hyphenate = function (a, b) { return '-' + b.toLowerCase(); }; /*jslint unparam: false*/ for (n in styles) { serializedCss += n.replace(/([A-Z])/g, hyphenate) + ':' + styles[n] + ';'; } attr(elem, 'style', serializedCss); // #1881 } // re-build text if (textWidth && elemWrapper.added) { elemWrapper.renderer.buildText(elemWrapper); } } return elemWrapper; }, /** * Add an event listener * @param {String} eventType * @param {Function} handler */ on: function (eventType, handler) { var svgElement = this, element = svgElement.element; // touch if (hasTouch && eventType === 'click') { element.ontouchstart = function (e) { svgElement.touchEventFired = Date.now(); e.preventDefault(); handler.call(element, e); }; element.onclick = function (e) { if (userAgent.indexOf('Android') === -1 || Date.now() - (svgElement.touchEventFired || 0) > 1100) { // #2269 handler.call(element, e); } }; } else { // simplest possible event model for internal use element['on' + eventType] = handler; } return this; }, /** * Set the coordinates needed to draw a consistent radial gradient across * pie slices regardless of positioning inside the chart. The format is * [centerX, centerY, diameter] in pixels. */ setRadialReference: function (coordinates) { this.element.radialReference = coordinates; return this; }, /** * Move an object and its children by x and y values * @param {Number} x * @param {Number} y */ translate: function (x, y) { return this.attr({ translateX: x, translateY: y }); }, /** * Invert a group, rotate and flip */ invert: function () { var wrapper = this; wrapper.inverted = true; wrapper.updateTransform(); return wrapper; }, /** * Private method to update the transform attribute based on internal * properties */ updateTransform: function () { var wrapper = this, translateX = wrapper.translateX || 0, translateY = wrapper.translateY || 0, scaleX = wrapper.scaleX, scaleY = wrapper.scaleY, inverted = wrapper.inverted, rotation = wrapper.rotation, element = wrapper.element, transform; // flipping affects translate as adjustment for flipping around the group's axis if (inverted) { translateX += wrapper.attr('width'); translateY += wrapper.attr('height'); } // Apply translate. Nearly all transformed elements have translation, so instead // of checking for translate = 0, do it always (#1767, #1846). transform = ['translate(' + translateX + ',' + translateY + ')']; // apply rotation if (inverted) { transform.push('rotate(90) scale(-1,1)'); } else if (rotation) { // text rotation transform.push('rotate(' + rotation + ' ' + (element.getAttribute('x') || 0) + ' ' + (element.getAttribute('y') || 0) + ')'); } // apply scale if (defined(scaleX) || defined(scaleY)) { transform.push('scale(' + pick(scaleX, 1) + ' ' + pick(scaleY, 1) + ')'); } if (transform.length) { element.setAttribute('transform', transform.join(' ')); } }, /** * Bring the element to the front */ toFront: function () { var element = this.element; element.parentNode.appendChild(element); return this; }, /** * Break down alignment options like align, verticalAlign, x and y * to x and y relative to the chart. * * @param {Object} alignOptions * @param {Boolean} alignByTranslate * @param {String[Object} box The box to align to, needs a width and height. When the * box is a string, it refers to an object in the Renderer. For example, when * box is 'spacingBox', it refers to Renderer.spacingBox which holds width, height * x and y properties. * */ align: function (alignOptions, alignByTranslate, box) { var align, vAlign, x, y, attribs = {}, alignTo, renderer = this.renderer, alignedObjects = renderer.alignedObjects; // First call on instanciate if (alignOptions) { this.alignOptions = alignOptions; this.alignByTranslate = alignByTranslate; if (!box || isString(box)) { // boxes other than renderer handle this internally this.alignTo = alignTo = box || 'renderer'; erase(alignedObjects, this); // prevent duplicates, like legendGroup after resize alignedObjects.push(this); box = null; // reassign it below } // When called on resize, no arguments are supplied } else { alignOptions = this.alignOptions; alignByTranslate = this.alignByTranslate; alignTo = this.alignTo; } box = pick(box, renderer[alignTo], renderer); // Assign variables align = alignOptions.align; vAlign = alignOptions.verticalAlign; x = (box.x || 0) + (alignOptions.x || 0); // default: left align y = (box.y || 0) + (alignOptions.y || 0); // default: top align // Align if (align === 'right' || align === 'center') { x += (box.width - (alignOptions.width || 0)) / { right: 1, center: 2 }[align]; } attribs[alignByTranslate ? 'translateX' : 'x'] = mathRound(x); // Vertical align if (vAlign === 'bottom' || vAlign === 'middle') { y += (box.height - (alignOptions.height || 0)) / ({ bottom: 1, middle: 2 }[vAlign] || 1); } attribs[alignByTranslate ? 'translateY' : 'y'] = mathRound(y); // Animate only if already placed this[this.placed ? 'animate' : 'attr'](attribs); this.placed = true; this.alignAttr = attribs; return this; }, /** * Get the bounding box (width, height, x and y) for the element */ getBBox: function () { var wrapper = this, bBox = wrapper.bBox, renderer = wrapper.renderer, width, height, rotation = wrapper.rotation, element = wrapper.element, styles = wrapper.styles, rad = rotation * deg2rad, textStr = wrapper.textStr, cacheKey; // Since numbers are monospaced, and numerical labels appear a lot in a chart, // we assume that a label of n characters has the same bounding box as others // of the same length. if (textStr === '' || numRegex.test(textStr)) { cacheKey = 'num.' + textStr.toString().length + (styles ? ('|' + styles.fontSize + '|' + styles.fontFamily) : ''); } //else { // This code block made demo/waterfall fail, related to buildText // Caching all strings reduces rendering time by 4-5%. // TODO: Check how this affects places where bBox is found on the element //cacheKey = textStr + (styles ? ('|' + styles.fontSize + '|' + styles.fontFamily) : ''); //} if (cacheKey) { bBox = renderer.cache[cacheKey]; } // No cache found if (!bBox) { // SVG elements if (element.namespaceURI === SVG_NS || renderer.forExport) { try { // Fails in Firefox if the container has display: none. bBox = element.getBBox ? // SVG: use extend because IE9 is not allowed to change width and height in case // of rotation (below) extend({}, element.getBBox()) : // Canvas renderer and legacy IE in export mode { width: element.offsetWidth, height: element.offsetHeight }; } catch (e) {} // If the bBox is not set, the try-catch block above failed. The other condition // is for Opera that returns a width of -Infinity on hidden elements. if (!bBox || bBox.width < 0) { bBox = { width: 0, height: 0 }; } // VML Renderer or useHTML within SVG } else { bBox = wrapper.htmlGetBBox(); } // True SVG elements as well as HTML elements in modern browsers using the .useHTML option // need to compensated for rotation if (renderer.isSVG) { width = bBox.width; height = bBox.height; // Workaround for wrong bounding box in IE9 and IE10 (#1101, #1505, #1669, #2568) if (isIE && styles && styles.fontSize === '11px' && height.toPrecision(3) === '16.9') { bBox.height = height = 14; } // Adjust for rotated text if (rotation) { bBox.width = mathAbs(height * mathSin(rad)) + mathAbs(width * mathCos(rad)); bBox.height = mathAbs(height * mathCos(rad)) + mathAbs(width * mathSin(rad)); } } // Cache it wrapper.bBox = bBox; if (cacheKey) { renderer.cache[cacheKey] = bBox; } } return bBox; }, /** * Show the element */ show: function (inherit) { // IE9-11 doesn't handle visibilty:inherit well, so we remove the attribute instead (#2881) if (inherit && this.element.namespaceURI === SVG_NS) { this.element.removeAttribute('visibility'); } else { this.attr({ visibility: inherit ? 'inherit' : VISIBLE }); } return this; }, /** * Hide the element */ hide: function () { return this.attr({ visibility: HIDDEN }); }, fadeOut: function (duration) { var elemWrapper = this; elemWrapper.animate({ opacity: 0 }, { duration: duration || 150, complete: function () { elemWrapper.attr({ y: -9999 }); // #3088, assuming we're only using this for tooltips } }); }, /** * Add the element * @param {Object|Undefined} parent Can be an element, an element wrapper or undefined * to append the element to the renderer.box. */ add: function (parent) { var renderer = this.renderer, parentWrapper = parent || renderer, parentNode = parentWrapper.element || renderer.box, childNodes, element = this.element, zIndex = this.zIndex, otherElement, otherZIndex, i, inserted; if (parent) { this.parentGroup = parent; } // mark as inverted this.parentInverted = parent && parent.inverted; // build formatted text if (this.textStr !== undefined) { renderer.buildText(this); } // mark the container as having z indexed children if (zIndex) { parentWrapper.handleZ = true; zIndex = pInt(zIndex); } // insert according to this and other elements' zIndex if (parentWrapper.handleZ) { // this element or any of its siblings has a z index childNodes = parentNode.childNodes; for (i = 0; i < childNodes.length; i++) { otherElement = childNodes[i]; otherZIndex = attr(otherElement, 'zIndex'); if (otherElement !== element && ( // insert before the first element with a higher zIndex pInt(otherZIndex) > zIndex || // if no zIndex given, insert before the first element with a zIndex (!defined(zIndex) && defined(otherZIndex)) )) { parentNode.insertBefore(element, otherElement); inserted = true; break; } } } // default: append at the end if (!inserted) { parentNode.appendChild(element); } // mark as added this.added = true; // fire an event for internal hooks if (this.onAdd) { this.onAdd(); } return this; }, /** * Removes a child either by removeChild or move to garbageBin. * Issue 490; in VML removeChild results in Orphaned nodes according to sIEve, discardElement does not. */ safeRemoveChild: function (element) { var parentNode = element.parentNode; if (parentNode) { parentNode.removeChild(element); } }, /** * Destroy the element and element wrapper */ destroy: function () { var wrapper = this, element = wrapper.element || {}, shadows = wrapper.shadows, parentToClean = wrapper.renderer.isSVG && element.nodeName === 'SPAN' && wrapper.parentGroup, grandParent, key, i; // remove events element.onclick = element.onmouseout = element.onmouseover = element.onmousemove = element.point = null; stop(wrapper); // stop running animations if (wrapper.clipPath) { wrapper.clipPath = wrapper.clipPath.destroy(); } // Destroy stops in case this is a gradient object if (wrapper.stops) { for (i = 0; i < wrapper.stops.length; i++) { wrapper.stops[i] = wrapper.stops[i].destroy(); } wrapper.stops = null; } // remove element wrapper.safeRemoveChild(element); // destroy shadows if (shadows) { each(shadows, function (shadow) { wrapper.safeRemoveChild(shadow); }); } // In case of useHTML, clean up empty containers emulating SVG groups (#1960, #2393, #2697). while (parentToClean && parentToClean.div && parentToClean.div.childNodes.length === 0) { grandParent = parentToClean.parentGroup; wrapper.safeRemoveChild(parentToClean.div); delete parentToClean.div; parentToClean = grandParent; } // remove from alignObjects if (wrapper.alignTo) { erase(wrapper.renderer.alignedObjects, wrapper); } for (key in wrapper) { delete wrapper[key]; } return null; }, /** * Add a shadow to the element. Must be done after the element is added to the DOM * @param {Boolean|Object} shadowOptions */ shadow: function (shadowOptions, group, cutOff) { var shadows = [], i, shadow, element = this.element, strokeWidth, shadowWidth, shadowElementOpacity, // compensate for inverted plot area transform; if (shadowOptions) { shadowWidth = pick(shadowOptions.width, 3); shadowElementOpacity = (shadowOptions.opacity || 0.15) / shadowWidth; transform = this.parentInverted ? '(-1,-1)' : '(' + pick(shadowOptions.offsetX, 1) + ', ' + pick(shadowOptions.offsetY, 1) + ')'; for (i = 1; i <= shadowWidth; i++) { shadow = element.cloneNode(0); strokeWidth = (shadowWidth * 2) + 1 - (2 * i); attr(shadow, { 'isShadow': 'true', 'stroke': shadowOptions.color || 'black', 'stroke-opacity': shadowElementOpacity * i, 'stroke-width': strokeWidth, 'transform': 'translate' + transform, 'fill': NONE }); if (cutOff) { attr(shadow, 'height', mathMax(attr(shadow, 'height') - strokeWidth, 0)); shadow.cutHeight = strokeWidth; } if (group) { group.element.appendChild(shadow); } else { element.parentNode.insertBefore(shadow, element); } shadows.push(shadow); } this.shadows = shadows; } return this; }, xGetter: function (key) { if (this.element.nodeName === 'circle') { key = { x: 'cx', y: 'cy' }[key] || key; } return this._defaultGetter(key); }, /** * Get the current value of an attribute or pseudo attribute, used mainly * for animation. */ _defaultGetter: function (key) { var ret = pick(this[key], this.element ? this.element.getAttribute(key) : null, 0); if (/^[\-0-9\.]+$/.test(ret)) { // is numerical ret = parseFloat(ret); } return ret; }, dSetter: function (value, key, element) { if (value && value.join) { // join path value = value.join(' '); } if (/(NaN| {2}|^$)/.test(value)) { value = 'M 0 0'; } element.setAttribute(key, value); this[key] = value; }, dashstyleSetter: function (value) { var i; value = value && value.toLowerCase(); if (value) { value = value .replace('shortdashdotdot', '3,1,1,1,1,1,') .replace('shortdashdot', '3,1,1,1') .replace('shortdot', '1,1,') .replace('shortdash', '3,1,') .replace('longdash', '8,3,') .replace(/dot/g, '1,3,') .replace('dash', '4,3,') .replace(/,$/, '') .split(','); // ending comma i = value.length; while (i--) { value[i] = pInt(value[i]) * this['stroke-width']; } value = value.join(',') .replace('NaN', 'none'); // #3226 this.element.setAttribute('stroke-dasharray', value); } }, alignSetter: function (value) { this.element.setAttribute('text-anchor', { left: 'start', center: 'middle', right: 'end' }[value]); }, opacitySetter: function (value, key, element) { this[key] = value; element.setAttribute(key, value); }, titleSetter: function (value) { var titleNode = this.element.getElementsByTagName('title')[0]; if (!titleNode) { titleNode = doc.createElementNS(SVG_NS, 'title'); this.element.appendChild(titleNode); } titleNode.textContent = pick(value, '').replace(/<[^>]*>/g, ''); // #3276 }, textSetter: function (value) { if (value !== this.textStr) { // Delete bBox memo when the text changes delete this.bBox; this.textStr = value; if (this.added) { this.renderer.buildText(this); } } }, fillSetter: function (value, key, element) { if (typeof value === 'string') { element.setAttribute(key, value); } else if (value) { this.colorGradient(value, key, element); } }, zIndexSetter: function (value, key, element) { element.setAttribute(key, value); this[key] = value; }, _defaultSetter: function (value, key, element) { element.setAttribute(key, value); } }; // Some shared setters and getters SVGElement.prototype.yGetter = SVGElement.prototype.xGetter; SVGElement.prototype.translateXSetter = SVGElement.prototype.translateYSetter = SVGElement.prototype.rotationSetter = SVGElement.prototype.verticalAlignSetter = SVGElement.prototype.scaleXSetter = SVGElement.prototype.scaleYSetter = function (value, key) { this[key] = value; this.doTransform = true; }; // WebKit and Batik have problems with a stroke-width of zero, so in this case we remove the // stroke attribute altogether. #1270, #1369, #3065, #3072. SVGElement.prototype['stroke-widthSetter'] = SVGElement.prototype.strokeSetter = function (value, key, element) { this[key] = value; // Only apply the stroke attribute if the stroke width is defined and larger than 0 if (this.stroke && this['stroke-width']) { this.strokeWidth = this['stroke-width']; SVGElement.prototype.fillSetter.call(this, this.stroke, 'stroke', element); // use prototype as instance may be overridden element.setAttribute('stroke-width', this['stroke-width']); this.hasStroke = true; } else if (key === 'stroke-width' && value === 0 && this.hasStroke) { element.removeAttribute('stroke'); this.hasStroke = false; } }; /** * The default SVG renderer */ var SVGRenderer = function () { this.init.apply(this, arguments); }; SVGRenderer.prototype = { Element: SVGElement, /** * Initialize the SVGRenderer * @param {Object} container * @param {Number} width * @param {Number} height * @param {Boolean} forExport */ init: function (container, width, height, style, forExport) { var renderer = this, loc = location, boxWrapper, element, desc; boxWrapper = renderer.createElement('svg') .attr({ version: '1.1' }) .css(this.getStyle(style)); element = boxWrapper.element; container.appendChild(element); // For browsers other than IE, add the namespace attribute (#1978) if (container.innerHTML.indexOf('xmlns') === -1) { attr(element, 'xmlns', SVG_NS); } // object properties renderer.isSVG = true; renderer.box = element; renderer.boxWrapper = boxWrapper; renderer.alignedObjects = []; // Page url used for internal references. #24, #672, #1070 renderer.url = (isFirefox || isWebKit) && doc.getElementsByTagName('base').length ? loc.href .replace(/#.*?$/, '') // remove the hash .replace(/([\('\)])/g, '\\$1') // escape parantheses and quotes .replace(/ /g, '%20') : // replace spaces (needed for Safari only) ''; // Add description desc = this.createElement('desc').add(); desc.element.appendChild(doc.createTextNode('Created with ' + PRODUCT + ' ' + VERSION)); renderer.defs = this.createElement('defs').add(); renderer.forExport = forExport; renderer.gradients = {}; // Object where gradient SvgElements are stored renderer.cache = {}; // Cache for numerical bounding boxes renderer.setSize(width, height, false); // Issue 110 workaround: // In Firefox, if a div is positioned by percentage, its pixel position may land // between pixels. The container itself doesn't display this, but an SVG element // inside this container will be drawn at subpixel precision. In order to draw // sharp lines, this must be compensated for. This doesn't seem to work inside // iframes though (like in jsFiddle). var subPixelFix, rect; if (isFirefox && container.getBoundingClientRect) { renderer.subPixelFix = subPixelFix = function () { css(container, { left: 0, top: 0 }); rect = container.getBoundingClientRect(); css(container, { left: (mathCeil(rect.left) - rect.left) + PX, top: (mathCeil(rect.top) - rect.top) + PX }); }; // run the fix now subPixelFix(); // run it on resize addEvent(win, 'resize', subPixelFix); } }, getStyle: function (style) { return (this.style = extend({ fontFamily: '"Lucida Grande", "Lucida Sans Unicode", Arial, Helvetica, sans-serif', // default font fontSize: '12px' }, style)); }, /** * Detect whether the renderer is hidden. This happens when one of the parent elements * has display: none. #608. */ isHidden: function () { return !this.boxWrapper.getBBox().width; }, /** * Destroys the renderer and its allocated members. */ destroy: function () { var renderer = this, rendererDefs = renderer.defs; renderer.box = null; renderer.boxWrapper = renderer.boxWrapper.destroy(); // Call destroy on all gradient elements destroyObjectProperties(renderer.gradients || {}); renderer.gradients = null; // Defs are null in VMLRenderer // Otherwise, destroy them here. if (rendererDefs) { renderer.defs = rendererDefs.destroy(); } // Remove sub pixel fix handler // We need to check that there is a handler, otherwise all functions that are registered for event 'resize' are removed // See issue #982 if (renderer.subPixelFix) { removeEvent(win, 'resize', renderer.subPixelFix); } renderer.alignedObjects = null; return null; }, /** * Create a wrapper for an SVG element * @param {Object} nodeName */ createElement: function (nodeName) { var wrapper = new this.Element(); wrapper.init(this, nodeName); return wrapper; }, /** * Dummy function for use in canvas renderer */ draw: function () {}, /** * Parse a simple HTML string into SVG tspans * * @param {Object} textNode The parent text SVG node */ buildText: function (wrapper) { var textNode = wrapper.element, renderer = this, forExport = renderer.forExport, textStr = pick(wrapper.textStr, '').toString(), hasMarkup = textStr.indexOf('<') !== -1, lines, childNodes = textNode.childNodes, styleRegex, hrefRegex, parentX = attr(textNode, 'x'), textStyles = wrapper.styles, width = wrapper.textWidth, textLineHeight = textStyles && textStyles.lineHeight, textStroke = textStyles && textStyles.HcTextStroke, i = childNodes.length, getLineHeight = function (tspan) { return textLineHeight ? pInt(textLineHeight) : renderer.fontMetrics( /(px|em)$/.test(tspan && tspan.style.fontSize) ? tspan.style.fontSize : ((textStyles && textStyles.fontSize) || renderer.style.fontSize || 12), tspan ).h; }; /// remove old text while (i--) { textNode.removeChild(childNodes[i]); } // Skip tspans, add text directly to text node. The forceTSpan is a hook // used in text outline hack. if (!hasMarkup && !textStroke && textStr.indexOf(' ') === -1) { textNode.appendChild(doc.createTextNode(textStr)); return; // Complex strings, add more logic } else { styleRegex = /<.*style="([^"]+)".*>/; hrefRegex = /<.*href="(http[^"]+)".*>/; if (width && !wrapper.added) { this.box.appendChild(textNode); // attach it to the DOM to read offset width } if (hasMarkup) { lines = textStr .replace(/<(b|strong)>/g, '<span style="font-weight:bold">') .replace(/<(i|em)>/g, '<span style="font-style:italic">') .replace(/<a/g, '<span') .replace(/<\/(b|strong|i|em|a)>/g, '</span>') .split(/<br.*?>/g); } else { lines = [textStr]; } // remove empty line at end if (lines[lines.length - 1] === '') { lines.pop(); } // build the lines each(lines, function (line, lineNo) { var spans, spanNo = 0; line = line.replace(/<span/g, '|||<span').replace(/<\/span>/g, '</span>|||'); spans = line.split('|||'); each(spans, function (span) { if (span !== '' || spans.length === 1) { var attributes = {}, tspan = doc.createElementNS(SVG_NS, 'tspan'), spanStyle; // #390 if (styleRegex.test(span)) { spanStyle = span.match(styleRegex)[1].replace(/(;| |^)color([ :])/, '$1fill$2'); attr(tspan, 'style', spanStyle); } if (hrefRegex.test(span) && !forExport) { // Not for export - #1529 attr(tspan, 'onclick', 'location.href=\"' + span.match(hrefRegex)[1] + '\"'); css(tspan, { cursor: 'pointer' }); } span = (span.replace(/<(.|\n)*?>/g, '') || ' ') .replace(/&lt;/g, '<') .replace(/&gt;/g, '>'); // Nested tags aren't supported, and cause crash in Safari (#1596) if (span !== ' ') { // add the text node tspan.appendChild(doc.createTextNode(span)); if (!spanNo) { // first span in a line, align it to the left if (lineNo && parentX !== null) { attributes.x = parentX; } } else { attributes.dx = 0; // #16 } // add attributes attr(tspan, attributes); // Append it textNode.appendChild(tspan); // first span on subsequent line, add the line height if (!spanNo && lineNo) { // allow getting the right offset height in exporting in IE if (!hasSVG && forExport) { css(tspan, { display: 'block' }); } // Set the line height based on the font size of either // the text element or the tspan element attr( tspan, 'dy', getLineHeight(tspan) ); } // check width and apply soft breaks if (width) { var words = span.replace(/([^\^])-/g, '$1- ').split(' '), // #1273 hasWhiteSpace = spans.length > 1 || (words.length > 1 && textStyles.whiteSpace !== 'nowrap'), tooLong, actualWidth, hcHeight = textStyles.HcHeight, rest = [], dy = getLineHeight(tspan), softLineNo = 1, bBox; while (hasWhiteSpace && (words.length || rest.length)) { delete wrapper.bBox; // delete cache bBox = wrapper.getBBox(); actualWidth = bBox.width; // Old IE cannot measure the actualWidth for SVG elements (#2314) if (!hasSVG && renderer.forExport) { actualWidth = renderer.measureSpanWidth(tspan.firstChild.data, wrapper.styles); } tooLong = actualWidth > width; if (!tooLong || words.length === 1) { // new line needed words = rest; rest = []; if (words.length) { softLineNo++; if (hcHeight && softLineNo * dy > hcHeight) { words = ['...']; wrapper.attr('title', wrapper.textStr); } else { tspan = doc.createElementNS(SVG_NS, 'tspan'); attr(tspan, { dy: dy, x: parentX }); if (spanStyle) { // #390 attr(tspan, 'style', spanStyle); } textNode.appendChild(tspan); } } if (actualWidth > width) { // a single word is pressing it out width = actualWidth; } } else { // append to existing line tspan tspan.removeChild(tspan.firstChild); rest.unshift(words.pop()); } if (words.length) { tspan.appendChild(doc.createTextNode(words.join(' ').replace(/- /g, '-'))); } } } spanNo++; } } }); }); } }, /** * Create a button with preset states * @param {String} text * @param {Number} x * @param {Number} y * @param {Function} callback * @param {Object} normalState * @param {Object} hoverState * @param {Object} pressedState */ button: function (text, x, y, callback, normalState, hoverState, pressedState, disabledState, shape) { var label = this.label(text, x, y, shape, null, null, null, null, 'button'), curState = 0, stateOptions, stateStyle, normalStyle, hoverStyle, pressedStyle, disabledStyle, verticalGradient = { x1: 0, y1: 0, x2: 0, y2: 1 }; // Normal state - prepare the attributes normalState = merge({ 'stroke-width': 1, stroke: '#CCCCCC', fill: { linearGradient: verticalGradient, stops: [ [0, '#FEFEFE'], [1, '#F6F6F6'] ] }, r: 2, padding: 5, style: { color: 'black' } }, normalState); normalStyle = normalState.style; delete normalState.style; // Hover state hoverState = merge(normalState, { stroke: '#68A', fill: { linearGradient: verticalGradient, stops: [ [0, '#FFF'], [1, '#ACF'] ] } }, hoverState); hoverStyle = hoverState.style; delete hoverState.style; // Pressed state pressedState = merge(normalState, { stroke: '#68A', fill: { linearGradient: verticalGradient, stops: [ [0, '#9BD'], [1, '#CDF'] ] } }, pressedState); pressedStyle = pressedState.style; delete pressedState.style; // Disabled state disabledState = merge(normalState, { style: { color: '#CCC' } }, disabledState); disabledStyle = disabledState.style; delete disabledState.style; // Add the events. IE9 and IE10 need mouseover and mouseout to funciton (#667). addEvent(label.element, isIE ? 'mouseover' : 'mouseenter', function () { if (curState !== 3) { label.attr(hoverState) .css(hoverStyle); } }); addEvent(label.element, isIE ? 'mouseout' : 'mouseleave', function () { if (curState !== 3) { stateOptions = [normalState, hoverState, pressedState][curState]; stateStyle = [normalStyle, hoverStyle, pressedStyle][curState]; label.attr(stateOptions) .css(stateStyle); } }); label.setState = function (state) { label.state = curState = state; if (!state) { label.attr(normalState) .css(normalStyle); } else if (state === 2) { label.attr(pressedState) .css(pressedStyle); } else if (state === 3) { label.attr(disabledState) .css(disabledStyle); } }; return label .on('click', function () { if (curState !== 3) { callback.call(label); } }) .attr(normalState) .css(extend({ cursor: 'default' }, normalStyle)); }, /** * Make a straight line crisper by not spilling out to neighbour pixels * @param {Array} points * @param {Number} width */ crispLine: function (points, width) { // points format: [M, 0, 0, L, 100, 0] // normalize to a crisp line if (points[1] === points[4]) { // Substract due to #1129. Now bottom and left axis gridlines behave the same. points[1] = points[4] = mathRound(points[1]) - (width % 2 / 2); } if (points[2] === points[5]) { points[2] = points[5] = mathRound(points[2]) + (width % 2 / 2); } return points; }, /** * Draw a path * @param {Array} path An SVG path in array form */ path: function (path) { var attr = { fill: NONE }; if (isArray(path)) { attr.d = path; } else if (isObject(path)) { // attributes extend(attr, path); } return this.createElement('path').attr(attr); }, /** * Draw and return an SVG circle * @param {Number} x The x position * @param {Number} y The y position * @param {Number} r The radius */ circle: function (x, y, r) { var attr = isObject(x) ? x : { x: x, y: y, r: r }, wrapper = this.createElement('circle'); wrapper.xSetter = function (value) { this.element.setAttribute('cx', value); }; wrapper.ySetter = function (value) { this.element.setAttribute('cy', value); }; return wrapper.attr(attr); }, /** * Draw and return an arc * @param {Number} x X position * @param {Number} y Y position * @param {Number} r Radius * @param {Number} innerR Inner radius like used in donut charts * @param {Number} start Starting angle * @param {Number} end Ending angle */ arc: function (x, y, r, innerR, start, end) { var arc; if (isObject(x)) { y = x.y; r = x.r; innerR = x.innerR; start = x.start; end = x.end; x = x.x; } // Arcs are defined as symbols for the ability to set // attributes in attr and animate arc = this.symbol('arc', x || 0, y || 0, r || 0, r || 0, { innerR: innerR || 0, start: start || 0, end: end || 0 }); arc.r = r; // #959 return arc; }, /** * Draw and return a rectangle * @param {Number} x Left position * @param {Number} y Top position * @param {Number} width * @param {Number} height * @param {Number} r Border corner radius * @param {Number} strokeWidth A stroke width can be supplied to allow crisp drawing */ rect: function (x, y, width, height, r, strokeWidth) { r = isObject(x) ? x.r : r; var wrapper = this.createElement('rect'), attribs = isObject(x) ? x : x === UNDEFINED ? {} : { x: x, y: y, width: mathMax(width, 0), height: mathMax(height, 0) }; if (strokeWidth !== UNDEFINED) { attribs.strokeWidth = strokeWidth; attribs = wrapper.crisp(attribs); } if (r) { attribs.r = r; } wrapper.rSetter = function (value) { attr(this.element, { rx: value, ry: value }); }; return wrapper.attr(attribs); }, /** * Resize the box and re-align all aligned elements * @param {Object} width * @param {Object} height * @param {Boolean} animate * */ setSize: function (width, height, animate) { var renderer = this, alignedObjects = renderer.alignedObjects, i = alignedObjects.length; renderer.width = width; renderer.height = height; renderer.boxWrapper[pick(animate, true) ? 'animate' : 'attr']({ width: width, height: height }); while (i--) { alignedObjects[i].align(); } }, /** * Create a group * @param {String} name The group will be given a class name of 'highcharts-{name}'. * This can be used for styling and scripting. */ g: function (name) { var elem = this.createElement('g'); return defined(name) ? elem.attr({ 'class': PREFIX + name }) : elem; }, /** * Display an image * @param {String} src * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ image: function (src, x, y, width, height) { var attribs = { preserveAspectRatio: NONE }, elemWrapper; // optional properties if (arguments.length > 1) { extend(attribs, { x: x, y: y, width: width, height: height }); } elemWrapper = this.createElement('image').attr(attribs); // set the href in the xlink namespace if (elemWrapper.element.setAttributeNS) { elemWrapper.element.setAttributeNS('http://www.w3.org/1999/xlink', 'href', src); } else { // could be exporting in IE // using href throws "not supported" in ie7 and under, requries regex shim to fix later elemWrapper.element.setAttribute('hc-svg-href', src); } return elemWrapper; }, /** * Draw a symbol out of pre-defined shape paths from the namespace 'symbol' object. * * @param {Object} symbol * @param {Object} x * @param {Object} y * @param {Object} radius * @param {Object} options */ symbol: function (symbol, x, y, width, height, options) { var obj, // get the symbol definition function symbolFn = this.symbols[symbol], // check if there's a path defined for this symbol path = symbolFn && symbolFn( mathRound(x), mathRound(y), width, height, options ), imageElement, imageRegex = /^url\((.*?)\)$/, imageSrc, imageSize, centerImage; if (path) { obj = this.path(path); // expando properties for use in animate and attr extend(obj, { symbolName: symbol, x: x, y: y, width: width, height: height }); if (options) { extend(obj, options); } // image symbols } else if (imageRegex.test(symbol)) { // On image load, set the size and position centerImage = function (img, size) { if (img.element) { // it may be destroyed in the meantime (#1390) img.attr({ width: size[0], height: size[1] }); if (!img.alignByTranslate) { // #185 img.translate( mathRound((width - size[0]) / 2), // #1378 mathRound((height - size[1]) / 2) ); } } }; imageSrc = symbol.match(imageRegex)[1]; imageSize = symbolSizes[imageSrc] || (options && options.width && options.height && [options.width, options.height]); // Ireate the image synchronously, add attribs async obj = this.image(imageSrc) .attr({ x: x, y: y }); obj.isImg = true; if (imageSize) { centerImage(obj, imageSize); } else { // Initialize image to be 0 size so export will still function if there's no cached sizes. obj.attr({ width: 0, height: 0 }); // Create a dummy JavaScript image to get the width and height. Due to a bug in IE < 8, // the created element must be assigned to a variable in order to load (#292). imageElement = createElement('img', { onload: function () { centerImage(obj, symbolSizes[imageSrc] = [this.width, this.height]); }, src: imageSrc }); } } return obj; }, /** * An extendable collection of functions for defining symbol paths. */ symbols: { 'circle': function (x, y, w, h) { var cpw = 0.166 * w; return [ M, x + w / 2, y, 'C', x + w + cpw, y, x + w + cpw, y + h, x + w / 2, y + h, 'C', x - cpw, y + h, x - cpw, y, x + w / 2, y, 'Z' ]; }, 'square': function (x, y, w, h) { return [ M, x, y, L, x + w, y, x + w, y + h, x, y + h, 'Z' ]; }, 'triangle': function (x, y, w, h) { return [ M, x + w / 2, y, L, x + w, y + h, x, y + h, 'Z' ]; }, 'triangle-down': function (x, y, w, h) { return [ M, x, y, L, x + w, y, x + w / 2, y + h, 'Z' ]; }, 'diamond': function (x, y, w, h) { return [ M, x + w / 2, y, L, x + w, y + h / 2, x + w / 2, y + h, x, y + h / 2, 'Z' ]; }, 'arc': function (x, y, w, h, options) { var start = options.start, radius = options.r || w || h, end = options.end - 0.001, // to prevent cos and sin of start and end from becoming equal on 360 arcs (related: #1561) innerRadius = options.innerR, open = options.open, cosStart = mathCos(start), sinStart = mathSin(start), cosEnd = mathCos(end), sinEnd = mathSin(end), longArc = options.end - start < mathPI ? 0 : 1; return [ M, x + radius * cosStart, y + radius * sinStart, 'A', // arcTo radius, // x radius radius, // y radius 0, // slanting longArc, // long or short arc 1, // clockwise x + radius * cosEnd, y + radius * sinEnd, open ? M : L, x + innerRadius * cosEnd, y + innerRadius * sinEnd, 'A', // arcTo innerRadius, // x radius innerRadius, // y radius 0, // slanting longArc, // long or short arc 0, // clockwise x + innerRadius * cosStart, y + innerRadius * sinStart, open ? '' : 'Z' // close ]; }, /** * Callout shape used for default tooltips, also used for rounded rectangles in VML */ callout: function (x, y, w, h, options) { var arrowLength = 6, halfDistance = 6, r = mathMin((options && options.r) || 0, w, h), safeDistance = r + halfDistance, anchorX = options && options.anchorX, anchorY = options && options.anchorY, path, normalizer = mathRound(options.strokeWidth || 0) % 2 / 2; // mathRound because strokeWidth can sometimes have roundoff errors; x += normalizer; y += normalizer; path = [ 'M', x + r, y, 'L', x + w - r, y, // top side 'C', x + w, y, x + w, y, x + w, y + r, // top-right corner 'L', x + w, y + h - r, // right side 'C', x + w, y + h, x + w, y + h, x + w - r, y + h, // bottom-right corner 'L', x + r, y + h, // bottom side 'C', x, y + h, x, y + h, x, y + h - r, // bottom-left corner 'L', x, y + r, // left side 'C', x, y, x, y, x + r, y // top-right corner ]; if (anchorX && anchorX > w && anchorY > y + safeDistance && anchorY < y + h - safeDistance) { // replace right side path.splice(13, 3, 'L', x + w, anchorY - halfDistance, x + w + arrowLength, anchorY, x + w, anchorY + halfDistance, x + w, y + h - r ); } else if (anchorX && anchorX < 0 && anchorY > y + safeDistance && anchorY < y + h - safeDistance) { // replace left side path.splice(33, 3, 'L', x, anchorY + halfDistance, x - arrowLength, anchorY, x, anchorY - halfDistance, x, y + r ); } else if (anchorY && anchorY > h && anchorX > x + safeDistance && anchorX < x + w - safeDistance) { // replace bottom path.splice(23, 3, 'L', anchorX + halfDistance, y + h, anchorX, y + h + arrowLength, anchorX - halfDistance, y + h, x + r, y + h ); } else if (anchorY && anchorY < 0 && anchorX > x + safeDistance && anchorX < x + w - safeDistance) { // replace top path.splice(3, 3, 'L', anchorX - halfDistance, y, anchorX, y - arrowLength, anchorX + halfDistance, y, w - r, y ); } return path; } }, /** * Define a clipping rectangle * @param {String} id * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ clipRect: function (x, y, width, height) { var wrapper, id = PREFIX + idCounter++, clipPath = this.createElement('clipPath').attr({ id: id }).add(this.defs); wrapper = this.rect(x, y, width, height, 0).add(clipPath); wrapper.id = id; wrapper.clipPath = clipPath; return wrapper; }, /** * Add text to the SVG object * @param {String} str * @param {Number} x Left position * @param {Number} y Top position * @param {Boolean} useHTML Use HTML to render the text */ text: function (str, x, y, useHTML) { // declare variables var renderer = this, fakeSVG = useCanVG || (!hasSVG && renderer.forExport), wrapper, attr = {}; if (useHTML && !renderer.forExport) { return renderer.html(str, x, y); } attr.x = Math.round(x || 0); // X is always needed for line-wrap logic if (y) { attr.y = Math.round(y); } if (str || str === 0) { attr.text = str; } wrapper = renderer.createElement('text') .attr(attr); // Prevent wrapping from creating false offsetWidths in export in legacy IE (#1079, #1063) if (fakeSVG) { wrapper.css({ position: ABSOLUTE }); } if (!useHTML) { wrapper.xSetter = function (value, key, element) { var tspans = element.getElementsByTagName('tspan'), tspan, parentVal = element.getAttribute(key), i; for (i = 0; i < tspans.length; i++) { tspan = tspans[i]; // If the x values are equal, the tspan represents a linebreak if (tspan.getAttribute(key) === parentVal) { tspan.setAttribute(key, value); } } element.setAttribute(key, value); }; } return wrapper; }, /** * Utility to return the baseline offset and total line height from the font size */ fontMetrics: function (fontSize, elem) { fontSize = fontSize || this.style.fontSize; if (elem && win.getComputedStyle) { elem = elem.element || elem; // SVGElement fontSize = win.getComputedStyle(elem, "").fontSize; } fontSize = /px/.test(fontSize) ? pInt(fontSize) : /em/.test(fontSize) ? parseFloat(fontSize) * 12 : 12; // Empirical values found by comparing font size and bounding box height. // Applies to the default font family. http://jsfiddle.net/highcharts/7xvn7/ var lineHeight = fontSize < 24 ? fontSize + 4 : mathRound(fontSize * 1.2), baseline = mathRound(lineHeight * 0.8); return { h: lineHeight, b: baseline, f: fontSize }; }, /** * Add a label, a text item that can hold a colored or gradient background * as well as a border and shadow. * @param {string} str * @param {Number} x * @param {Number} y * @param {String} shape * @param {Number} anchorX In case the shape has a pointer, like a flag, this is the * coordinates it should be pinned to * @param {Number} anchorY * @param {Boolean} baseline Whether to position the label relative to the text baseline, * like renderer.text, or to the upper border of the rectangle. * @param {String} className Class name for the group */ label: function (str, x, y, shape, anchorX, anchorY, useHTML, baseline, className) { var renderer = this, wrapper = renderer.g(className), text = renderer.text('', 0, 0, useHTML) .attr({ zIndex: 1 }), //.add(wrapper), box, bBox, alignFactor = 0, padding = 3, paddingLeft = 0, width, height, wrapperX, wrapperY, crispAdjust = 0, deferredAttr = {}, baselineOffset, needsBox; /** * This function runs after the label is added to the DOM (when the bounding box is * available), and after the text of the label is updated to detect the new bounding * box and reflect it in the border box. */ function updateBoxSize() { var boxX, boxY, style = text.element.style; bBox = (width === undefined || height === undefined || wrapper.styles.textAlign) && text.textStr && text.getBBox(); wrapper.width = (width || bBox.width || 0) + 2 * padding + paddingLeft; wrapper.height = (height || bBox.height || 0) + 2 * padding; // update the label-scoped y offset baselineOffset = padding + renderer.fontMetrics(style && style.fontSize, text).b; if (needsBox) { // create the border box if it is not already present if (!box) { boxX = mathRound(-alignFactor * padding); boxY = baseline ? -baselineOffset : 0; wrapper.box = box = shape ? renderer.symbol(shape, boxX, boxY, wrapper.width, wrapper.height, deferredAttr) : renderer.rect(boxX, boxY, wrapper.width, wrapper.height, 0, deferredAttr[STROKE_WIDTH]); box.attr('fill', NONE).add(wrapper); } // apply the box attributes if (!box.isImg) { // #1630 box.attr(extend({ width: mathRound(wrapper.width), height: mathRound(wrapper.height) }, deferredAttr)); } deferredAttr = null; } } /** * This function runs after setting text or padding, but only if padding is changed */ function updateTextPadding() { var styles = wrapper.styles, textAlign = styles && styles.textAlign, x = paddingLeft + padding * (1 - alignFactor), y; // determin y based on the baseline y = baseline ? 0 : baselineOffset; // compensate for alignment if (defined(width) && bBox && (textAlign === 'center' || textAlign === 'right')) { x += { center: 0.5, right: 1 }[textAlign] * (width - bBox.width); } // update if anything changed if (x !== text.x || y !== text.y) { text.attr('x', x); if (y !== UNDEFINED) { text.attr('y', y); } } // record current values text.x = x; text.y = y; } /** * Set a box attribute, or defer it if the box is not yet created * @param {Object} key * @param {Object} value */ function boxAttr(key, value) { if (box) { box.attr(key, value); } else { deferredAttr[key] = value; } } /** * After the text element is added, get the desired size of the border box * and add it before the text in the DOM. */ wrapper.onAdd = function () { text.add(wrapper); wrapper.attr({ text: (str || str === 0) ? str : '', // alignment is available now // #3295: 0 not rendered if given as a value x: x, y: y }); if (box && defined(anchorX)) { wrapper.attr({ anchorX: anchorX, anchorY: anchorY }); } }; /* * Add specific attribute setters. */ // only change local variables wrapper.widthSetter = function (value) { width = value; }; wrapper.heightSetter = function (value) { height = value; }; wrapper.paddingSetter = function (value) { if (defined(value) && value !== padding) { padding = value; updateTextPadding(); } }; wrapper.paddingLeftSetter = function (value) { if (defined(value) && value !== paddingLeft) { paddingLeft = value; updateTextPadding(); } }; // change local variable and prevent setting attribute on the group wrapper.alignSetter = function (value) { alignFactor = { left: 0, center: 0.5, right: 1 }[value]; }; // apply these to the box and the text alike wrapper.textSetter = function (value) { if (value !== UNDEFINED) { text.textSetter(value); } updateBoxSize(); updateTextPadding(); }; // apply these to the box but not to the text wrapper['stroke-widthSetter'] = function (value, key) { if (value) { needsBox = true; } crispAdjust = value % 2 / 2; boxAttr(key, value); }; wrapper.strokeSetter = wrapper.fillSetter = wrapper.rSetter = function (value, key) { if (key === 'fill' && value) { needsBox = true; } boxAttr(key, value); }; wrapper.anchorXSetter = function (value, key) { anchorX = value; boxAttr(key, value + crispAdjust - wrapperX); }; wrapper.anchorYSetter = function (value, key) { anchorY = value; boxAttr(key, value - wrapperY); }; // rename attributes wrapper.xSetter = function (value) { wrapper.x = value; // for animation getter if (alignFactor) { value -= alignFactor * ((width || bBox.width) + padding); } wrapperX = mathRound(value); wrapper.attr('translateX', wrapperX); }; wrapper.ySetter = function (value) { wrapperY = wrapper.y = mathRound(value); wrapper.attr('translateY', wrapperY); }; // Redirect certain methods to either the box or the text var baseCss = wrapper.css; return extend(wrapper, { /** * Pick up some properties and apply them to the text instead of the wrapper */ css: function (styles) { if (styles) { var textStyles = {}; styles = merge(styles); // create a copy to avoid altering the original object (#537) each(wrapper.textProps, function (prop) { if (styles[prop] !== UNDEFINED) { textStyles[prop] = styles[prop]; delete styles[prop]; } }); text.css(textStyles); } return baseCss.call(wrapper, styles); }, /** * Return the bounding box of the box, not the group */ getBBox: function () { return { width: bBox.width + 2 * padding, height: bBox.height + 2 * padding, x: bBox.x - padding, y: bBox.y - padding }; }, /** * Apply the shadow to the box */ shadow: function (b) { if (box) { box.shadow(b); } return wrapper; }, /** * Destroy and release memory. */ destroy: function () { // Added by button implementation removeEvent(wrapper.element, 'mouseenter'); removeEvent(wrapper.element, 'mouseleave'); if (text) { text = text.destroy(); } if (box) { box = box.destroy(); } // Call base implementation to destroy the rest SVGElement.prototype.destroy.call(wrapper); // Release local pointers (#1298) wrapper = renderer = updateBoxSize = updateTextPadding = boxAttr = null; } }); } }; // end SVGRenderer // general renderer Renderer = SVGRenderer; // extend SvgElement for useHTML option extend(SVGElement.prototype, { /** * Apply CSS to HTML elements. This is used in text within SVG rendering and * by the VML renderer */ htmlCss: function (styles) { var wrapper = this, element = wrapper.element, textWidth = styles && element.tagName === 'SPAN' && styles.width; if (textWidth) { delete styles.width; wrapper.textWidth = textWidth; wrapper.updateTransform(); } wrapper.styles = extend(wrapper.styles, styles); css(wrapper.element, styles); return wrapper; }, /** * VML and useHTML method for calculating the bounding box based on offsets * @param {Boolean} refresh Whether to force a fresh value from the DOM or to * use the cached value * * @return {Object} A hash containing values for x, y, width and height */ htmlGetBBox: function () { var wrapper = this, element = wrapper.element, bBox = wrapper.bBox; // faking getBBox in exported SVG in legacy IE if (!bBox) { // faking getBBox in exported SVG in legacy IE (is this a duplicate of the fix for #1079?) if (element.nodeName === 'text') { element.style.position = ABSOLUTE; } bBox = wrapper.bBox = { x: element.offsetLeft, y: element.offsetTop, width: element.offsetWidth, height: element.offsetHeight }; } return bBox; }, /** * VML override private method to update elements based on internal * properties based on SVG transform */ htmlUpdateTransform: function () { // aligning non added elements is expensive if (!this.added) { this.alignOnAdd = true; return; } var wrapper = this, renderer = wrapper.renderer, elem = wrapper.element, translateX = wrapper.translateX || 0, translateY = wrapper.translateY || 0, x = wrapper.x || 0, y = wrapper.y || 0, align = wrapper.textAlign || 'left', alignCorrection = { left: 0, center: 0.5, right: 1 }[align], shadows = wrapper.shadows; // apply translate css(elem, { marginLeft: translateX, marginTop: translateY }); if (shadows) { // used in labels/tooltip each(shadows, function (shadow) { css(shadow, { marginLeft: translateX + 1, marginTop: translateY + 1 }); }); } // apply inversion if (wrapper.inverted) { // wrapper is a group each(elem.childNodes, function (child) { renderer.invertChild(child, elem); }); } if (elem.tagName === 'SPAN') { var width, rotation = wrapper.rotation, baseline, textWidth = pInt(wrapper.textWidth), currentTextTransform = [rotation, align, elem.innerHTML, wrapper.textWidth].join(','); if (currentTextTransform !== wrapper.cTT) { // do the calculations and DOM access only if properties changed baseline = renderer.fontMetrics(elem.style.fontSize).b; // Renderer specific handling of span rotation if (defined(rotation)) { wrapper.setSpanRotation(rotation, alignCorrection, baseline); } width = pick(wrapper.elemWidth, elem.offsetWidth); // Update textWidth if (width > textWidth && /[ \-]/.test(elem.textContent || elem.innerText)) { // #983, #1254 css(elem, { width: textWidth + PX, display: 'block', whiteSpace: 'normal' }); width = textWidth; } wrapper.getSpanCorrection(width, baseline, alignCorrection, rotation, align); } // apply position with correction css(elem, { left: (x + (wrapper.xCorr || 0)) + PX, top: (y + (wrapper.yCorr || 0)) + PX }); // force reflow in webkit to apply the left and top on useHTML element (#1249) if (isWebKit) { baseline = elem.offsetHeight; // assigned to baseline for JSLint purpose } // record current text transform wrapper.cTT = currentTextTransform; } }, /** * Set the rotation of an individual HTML span */ setSpanRotation: function (rotation, alignCorrection, baseline) { var rotationStyle = {}, cssTransformKey = isIE ? '-ms-transform' : isWebKit ? '-webkit-transform' : isFirefox ? 'MozTransform' : isOpera ? '-o-transform' : ''; rotationStyle[cssTransformKey] = rotationStyle.transform = 'rotate(' + rotation + 'deg)'; rotationStyle[cssTransformKey + (isFirefox ? 'Origin' : '-origin')] = rotationStyle.transformOrigin = (alignCorrection * 100) + '% ' + baseline + 'px'; css(this.element, rotationStyle); }, /** * Get the correction in X and Y positioning as the element is rotated. */ getSpanCorrection: function (width, baseline, alignCorrection) { this.xCorr = -width * alignCorrection; this.yCorr = -baseline; } }); // Extend SvgRenderer for useHTML option. extend(SVGRenderer.prototype, { /** * Create HTML text node. This is used by the VML renderer as well as the SVG * renderer through the useHTML option. * * @param {String} str * @param {Number} x * @param {Number} y */ html: function (str, x, y) { var wrapper = this.createElement('span'), element = wrapper.element, renderer = wrapper.renderer; // Text setter wrapper.textSetter = function (value) { if (value !== element.innerHTML) { delete this.bBox; } element.innerHTML = this.textStr = value; }; // Various setters which rely on update transform wrapper.xSetter = wrapper.ySetter = wrapper.alignSetter = wrapper.rotationSetter = function (value, key) { if (key === 'align') { key = 'textAlign'; // Do not overwrite the SVGElement.align method. Same as VML. } wrapper[key] = value; wrapper.htmlUpdateTransform(); }; // Set the default attributes wrapper.attr({ text: str, x: mathRound(x), y: mathRound(y) }) .css({ position: ABSOLUTE, whiteSpace: 'nowrap', fontFamily: this.style.fontFamily, fontSize: this.style.fontSize }); // Use the HTML specific .css method wrapper.css = wrapper.htmlCss; // This is specific for HTML within SVG if (renderer.isSVG) { wrapper.add = function (svgGroupWrapper) { var htmlGroup, container = renderer.box.parentNode, parentGroup, parents = []; this.parentGroup = svgGroupWrapper; // Create a mock group to hold the HTML elements if (svgGroupWrapper) { htmlGroup = svgGroupWrapper.div; if (!htmlGroup) { // Read the parent chain into an array and read from top down parentGroup = svgGroupWrapper; while (parentGroup) { parents.push(parentGroup); // Move up to the next parent group parentGroup = parentGroup.parentGroup; } // Ensure dynamically updating position when any parent is translated each(parents.reverse(), function (parentGroup) { var htmlGroupStyle; // Create a HTML div and append it to the parent div to emulate // the SVG group structure htmlGroup = parentGroup.div = parentGroup.div || createElement(DIV, { className: attr(parentGroup.element, 'class') }, { position: ABSOLUTE, left: (parentGroup.translateX || 0) + PX, top: (parentGroup.translateY || 0) + PX }, htmlGroup || container); // the top group is appended to container // Shortcut htmlGroupStyle = htmlGroup.style; // Set listeners to update the HTML div's position whenever the SVG group // position is changed extend(parentGroup, { translateXSetter: function (value, key) { htmlGroupStyle.left = value + PX; parentGroup[key] = value; parentGroup.doTransform = true; }, translateYSetter: function (value, key) { htmlGroupStyle.top = value + PX; parentGroup[key] = value; parentGroup.doTransform = true; }, visibilitySetter: function (value, key) { htmlGroupStyle[key] = value; } }); }); } } else { htmlGroup = container; } htmlGroup.appendChild(element); // Shared with VML: wrapper.added = true; if (wrapper.alignOnAdd) { wrapper.htmlUpdateTransform(); } return wrapper; }; } return wrapper; } }); /* **************************************************************************** * * * START OF INTERNET EXPLORER <= 8 SPECIFIC CODE * * * * For applications and websites that don't need IE support, like platform * * targeted mobile apps and web apps, this code can be removed. * * * *****************************************************************************/ /** * @constructor */ var VMLRenderer, VMLElement; if (!hasSVG && !useCanVG) { /** * The VML element wrapper. */ VMLElement = { /** * Initialize a new VML element wrapper. It builds the markup as a string * to minimize DOM traffic. * @param {Object} renderer * @param {Object} nodeName */ init: function (renderer, nodeName) { var wrapper = this, markup = ['<', nodeName, ' filled="f" stroked="f"'], style = ['position: ', ABSOLUTE, ';'], isDiv = nodeName === DIV; // divs and shapes need size if (nodeName === 'shape' || isDiv) { style.push('left:0;top:0;width:1px;height:1px;'); } style.push('visibility: ', isDiv ? HIDDEN : VISIBLE); markup.push(' style="', style.join(''), '"/>'); // create element with default attributes and style if (nodeName) { markup = isDiv || nodeName === 'span' || nodeName === 'img' ? markup.join('') : renderer.prepVML(markup); wrapper.element = createElement(markup); } wrapper.renderer = renderer; }, /** * Add the node to the given parent * @param {Object} parent */ add: function (parent) { var wrapper = this, renderer = wrapper.renderer, element = wrapper.element, box = renderer.box, inverted = parent && parent.inverted, // get the parent node parentNode = parent ? parent.element || parent : box; // if the parent group is inverted, apply inversion on all children if (inverted) { // only on groups renderer.invertChild(element, parentNode); } // append it parentNode.appendChild(element); // align text after adding to be able to read offset wrapper.added = true; if (wrapper.alignOnAdd && !wrapper.deferUpdateTransform) { wrapper.updateTransform(); } // fire an event for internal hooks if (wrapper.onAdd) { wrapper.onAdd(); } return wrapper; }, /** * VML always uses htmlUpdateTransform */ updateTransform: SVGElement.prototype.htmlUpdateTransform, /** * Set the rotation of a span with oldIE's filter */ setSpanRotation: function () { // Adjust for alignment and rotation. Rotation of useHTML content is not yet implemented // but it can probably be implemented for Firefox 3.5+ on user request. FF3.5+ // has support for CSS3 transform. The getBBox method also needs to be updated // to compensate for the rotation, like it currently does for SVG. // Test case: http://jsfiddle.net/highcharts/Ybt44/ var rotation = this.rotation, costheta = mathCos(rotation * deg2rad), sintheta = mathSin(rotation * deg2rad); css(this.element, { filter: rotation ? ['progid:DXImageTransform.Microsoft.Matrix(M11=', costheta, ', M12=', -sintheta, ', M21=', sintheta, ', M22=', costheta, ', sizingMethod=\'auto expand\')'].join('') : NONE }); }, /** * Get the positioning correction for the span after rotating. */ getSpanCorrection: function (width, baseline, alignCorrection, rotation, align) { var costheta = rotation ? mathCos(rotation * deg2rad) : 1, sintheta = rotation ? mathSin(rotation * deg2rad) : 0, height = pick(this.elemHeight, this.element.offsetHeight), quad, nonLeft = align && align !== 'left'; // correct x and y this.xCorr = costheta < 0 && -width; this.yCorr = sintheta < 0 && -height; // correct for baseline and corners spilling out after rotation quad = costheta * sintheta < 0; this.xCorr += sintheta * baseline * (quad ? 1 - alignCorrection : alignCorrection); this.yCorr -= costheta * baseline * (rotation ? (quad ? alignCorrection : 1 - alignCorrection) : 1); // correct for the length/height of the text if (nonLeft) { this.xCorr -= width * alignCorrection * (costheta < 0 ? -1 : 1); if (rotation) { this.yCorr -= height * alignCorrection * (sintheta < 0 ? -1 : 1); } css(this.element, { textAlign: align }); } }, /** * Converts a subset of an SVG path definition to its VML counterpart. Takes an array * as the parameter and returns a string. */ pathToVML: function (value) { // convert paths var i = value.length, path = []; while (i--) { // Multiply by 10 to allow subpixel precision. // Substracting half a pixel seems to make the coordinates // align with SVG, but this hasn't been tested thoroughly if (isNumber(value[i])) { path[i] = mathRound(value[i] * 10) - 5; } else if (value[i] === 'Z') { // close the path path[i] = 'x'; } else { path[i] = value[i]; // When the start X and end X coordinates of an arc are too close, // they are rounded to the same value above. In this case, substract or // add 1 from the end X and Y positions. #186, #760, #1371, #1410. if (value.isArc && (value[i] === 'wa' || value[i] === 'at')) { // Start and end X if (path[i + 5] === path[i + 7]) { path[i + 7] += value[i + 7] > value[i + 5] ? 1 : -1; } // Start and end Y if (path[i + 6] === path[i + 8]) { path[i + 8] += value[i + 8] > value[i + 6] ? 1 : -1; } } } } // Loop up again to handle path shortcuts (#2132) /*while (i++ < path.length) { if (path[i] === 'H') { // horizontal line to path[i] = 'L'; path.splice(i + 2, 0, path[i - 1]); } else if (path[i] === 'V') { // vertical line to path[i] = 'L'; path.splice(i + 1, 0, path[i - 2]); } }*/ return path.join(' ') || 'x'; }, /** * Set the element's clipping to a predefined rectangle * * @param {String} id The id of the clip rectangle */ clip: function (clipRect) { var wrapper = this, clipMembers, cssRet; if (clipRect) { clipMembers = clipRect.members; erase(clipMembers, wrapper); // Ensure unique list of elements (#1258) clipMembers.push(wrapper); wrapper.destroyClip = function () { erase(clipMembers, wrapper); }; cssRet = clipRect.getCSS(wrapper); } else { if (wrapper.destroyClip) { wrapper.destroyClip(); } cssRet = { clip: docMode8 ? 'inherit' : 'rect(auto)' }; // #1214 } return wrapper.css(cssRet); }, /** * Set styles for the element * @param {Object} styles */ css: SVGElement.prototype.htmlCss, /** * Removes a child either by removeChild or move to garbageBin. * Issue 490; in VML removeChild results in Orphaned nodes according to sIEve, discardElement does not. */ safeRemoveChild: function (element) { // discardElement will detach the node from its parent before attaching it // to the garbage bin. Therefore it is important that the node is attached and have parent. if (element.parentNode) { discardElement(element); } }, /** * Extend element.destroy by removing it from the clip members array */ destroy: function () { if (this.destroyClip) { this.destroyClip(); } return SVGElement.prototype.destroy.apply(this); }, /** * Add an event listener. VML override for normalizing event parameters. * @param {String} eventType * @param {Function} handler */ on: function (eventType, handler) { // simplest possible event model for internal use this.element['on' + eventType] = function () { var evt = win.event; evt.target = evt.srcElement; handler(evt); }; return this; }, /** * In stacked columns, cut off the shadows so that they don't overlap */ cutOffPath: function (path, length) { var len; path = path.split(/[ ,]/); len = path.length; if (len === 9 || len === 11) { path[len - 4] = path[len - 2] = pInt(path[len - 2]) - 10 * length; } return path.join(' '); }, /** * Apply a drop shadow by copying elements and giving them different strokes * @param {Boolean|Object} shadowOptions */ shadow: function (shadowOptions, group, cutOff) { var shadows = [], i, element = this.element, renderer = this.renderer, shadow, elemStyle = element.style, markup, path = element.path, strokeWidth, modifiedPath, shadowWidth, shadowElementOpacity; // some times empty paths are not strings if (path && typeof path.value !== 'string') { path = 'x'; } modifiedPath = path; if (shadowOptions) { shadowWidth = pick(shadowOptions.width, 3); shadowElementOpacity = (shadowOptions.opacity || 0.15) / shadowWidth; for (i = 1; i <= 3; i++) { strokeWidth = (shadowWidth * 2) + 1 - (2 * i); // Cut off shadows for stacked column items if (cutOff) { modifiedPath = this.cutOffPath(path.value, strokeWidth + 0.5); } markup = ['<shape isShadow="true" strokeweight="', strokeWidth, '" filled="false" path="', modifiedPath, '" coordsize="10 10" style="', element.style.cssText, '" />']; shadow = createElement(renderer.prepVML(markup), null, { left: pInt(elemStyle.left) + pick(shadowOptions.offsetX, 1), top: pInt(elemStyle.top) + pick(shadowOptions.offsetY, 1) } ); if (cutOff) { shadow.cutOff = strokeWidth + 1; } // apply the opacity markup = ['<stroke color="', shadowOptions.color || 'black', '" opacity="', shadowElementOpacity * i, '"/>']; createElement(renderer.prepVML(markup), null, null, shadow); // insert it if (group) { group.element.appendChild(shadow); } else { element.parentNode.insertBefore(shadow, element); } // record it shadows.push(shadow); } this.shadows = shadows; } return this; }, updateShadows: noop, // Used in SVG only setAttr: function (key, value) { if (docMode8) { // IE8 setAttribute bug this.element[key] = value; } else { this.element.setAttribute(key, value); } }, classSetter: function (value) { // IE8 Standards mode has problems retrieving the className unless set like this this.element.className = value; }, dashstyleSetter: function (value, key, element) { var strokeElem = element.getElementsByTagName('stroke')[0] || createElement(this.renderer.prepVML(['<stroke/>']), null, null, element); strokeElem[key] = value || 'solid'; this[key] = value; /* because changing stroke-width will change the dash length and cause an epileptic effect */ }, dSetter: function (value, key, element) { var i, shadows = this.shadows; value = value || []; this.d = value.join && value.join(' '); // used in getter for animation element.path = value = this.pathToVML(value); // update shadows if (shadows) { i = shadows.length; while (i--) { shadows[i].path = shadows[i].cutOff ? this.cutOffPath(value, shadows[i].cutOff) : value; } } this.setAttr(key, value); }, fillSetter: function (value, key, element) { var nodeName = element.nodeName; if (nodeName === 'SPAN') { // text color element.style.color = value; } else if (nodeName !== 'IMG') { // #1336 element.filled = value !== NONE; this.setAttr('fillcolor', this.renderer.color(value, element, key, this)); } }, opacitySetter: noop, // Don't bother - animation is too slow and filters introduce artifacts rotationSetter: function (value, key, element) { var style = element.style; this[key] = style[key] = value; // style is for #1873 // Correction for the 1x1 size of the shape container. Used in gauge needles. style.left = -mathRound(mathSin(value * deg2rad) + 1) + PX; style.top = mathRound(mathCos(value * deg2rad)) + PX; }, strokeSetter: function (value, key, element) { this.setAttr('strokecolor', this.renderer.color(value, element, key)); }, 'stroke-widthSetter': function (value, key, element) { element.stroked = !!value; // VML "stroked" attribute this[key] = value; // used in getter, issue #113 if (isNumber(value)) { value += PX; } this.setAttr('strokeweight', value); }, titleSetter: function (value, key) { this.setAttr(key, value); }, visibilitySetter: function (value, key, element) { // Handle inherited visibility if (value === 'inherit') { value = VISIBLE; } // Let the shadow follow the main element if (this.shadows) { each(this.shadows, function (shadow) { shadow.style[key] = value; }); } // Instead of toggling the visibility CSS property, move the div out of the viewport. // This works around #61 and #586 if (element.nodeName === 'DIV') { value = value === HIDDEN ? '-999em' : 0; // In order to redraw, IE7 needs the div to be visible when tucked away // outside the viewport. So the visibility is actually opposite of // the expected value. This applies to the tooltip only. if (!docMode8) { element.style[key] = value ? VISIBLE : HIDDEN; } key = 'top'; } element.style[key] = value; }, xSetter: function (value, key, element) { this[key] = value; // used in getter if (key === 'x') { key = 'left'; } else if (key === 'y') { key = 'top'; }/* else { value = mathMax(0, value); // don't set width or height below zero (#311) }*/ // clipping rectangle special if (this.updateClipping) { this[key] = value; // the key is now 'left' or 'top' for 'x' and 'y' this.updateClipping(); } else { // normal element.style[key] = value; } }, zIndexSetter: function (value, key, element) { element.style[key] = value; } }; Highcharts.VMLElement = VMLElement = extendClass(SVGElement, VMLElement); // Some shared setters VMLElement.prototype.ySetter = VMLElement.prototype.widthSetter = VMLElement.prototype.heightSetter = VMLElement.prototype.xSetter; /** * The VML renderer */ var VMLRendererExtension = { // inherit SVGRenderer Element: VMLElement, isIE8: userAgent.indexOf('MSIE 8.0') > -1, /** * Initialize the VMLRenderer * @param {Object} container * @param {Number} width * @param {Number} height */ init: function (container, width, height, style) { var renderer = this, boxWrapper, box, css; renderer.alignedObjects = []; boxWrapper = renderer.createElement(DIV) .css(extend(this.getStyle(style), { position: RELATIVE})); box = boxWrapper.element; container.appendChild(boxWrapper.element); // generate the containing box renderer.isVML = true; renderer.box = box; renderer.boxWrapper = boxWrapper; renderer.cache = {}; renderer.setSize(width, height, false); // The only way to make IE6 and IE7 print is to use a global namespace. However, // with IE8 the only way to make the dynamic shapes visible in screen and print mode // seems to be to add the xmlns attribute and the behaviour style inline. if (!doc.namespaces.hcv) { doc.namespaces.add('hcv', 'urn:schemas-microsoft-com:vml'); // Setup default CSS (#2153, #2368, #2384) css = 'hcv\\:fill, hcv\\:path, hcv\\:shape, hcv\\:stroke' + '{ behavior:url(#default#VML); display: inline-block; } '; try { doc.createStyleSheet().cssText = css; } catch (e) { doc.styleSheets[0].cssText += css; } } }, /** * Detect whether the renderer is hidden. This happens when one of the parent elements * has display: none */ isHidden: function () { return !this.box.offsetWidth; }, /** * Define a clipping rectangle. In VML it is accomplished by storing the values * for setting the CSS style to all associated members. * * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ clipRect: function (x, y, width, height) { // create a dummy element var clipRect = this.createElement(), isObj = isObject(x); // mimic a rectangle with its style object for automatic updating in attr return extend(clipRect, { members: [], left: (isObj ? x.x : x) + 1, top: (isObj ? x.y : y) + 1, width: (isObj ? x.width : width) - 1, height: (isObj ? x.height : height) - 1, getCSS: function (wrapper) { var element = wrapper.element, nodeName = element.nodeName, isShape = nodeName === 'shape', inverted = wrapper.inverted, rect = this, top = rect.top - (isShape ? element.offsetTop : 0), left = rect.left, right = left + rect.width, bottom = top + rect.height, ret = { clip: 'rect(' + mathRound(inverted ? left : top) + 'px,' + mathRound(inverted ? bottom : right) + 'px,' + mathRound(inverted ? right : bottom) + 'px,' + mathRound(inverted ? top : left) + 'px)' }; // issue 74 workaround if (!inverted && docMode8 && nodeName === 'DIV') { extend(ret, { width: right + PX, height: bottom + PX }); } return ret; }, // used in attr and animation to update the clipping of all members updateClipping: function () { each(clipRect.members, function (member) { if (member.element) { // Deleted series, like in stock/members/series-remove demo. Should be removed from members, but this will do. member.css(clipRect.getCSS(member)); } }); } }); }, /** * Take a color and return it if it's a string, make it a gradient if it's a * gradient configuration object, and apply opacity. * * @param {Object} color The color or config object */ color: function (color, elem, prop, wrapper) { var renderer = this, colorObject, regexRgba = /^rgba/, markup, fillType, ret = NONE; // Check for linear or radial gradient if (color && color.linearGradient) { fillType = 'gradient'; } else if (color && color.radialGradient) { fillType = 'pattern'; } if (fillType) { var stopColor, stopOpacity, gradient = color.linearGradient || color.radialGradient, x1, y1, x2, y2, opacity1, opacity2, color1, color2, fillAttr = '', stops = color.stops, firstStop, lastStop, colors = [], addFillNode = function () { // Add the fill subnode. When colors attribute is used, the meanings of opacity and o:opacity2 // are reversed. markup = ['<fill colors="' + colors.join(',') + '" opacity="', opacity2, '" o:opacity2="', opacity1, '" type="', fillType, '" ', fillAttr, 'focus="100%" method="any" />']; createElement(renderer.prepVML(markup), null, null, elem); }; // Extend from 0 to 1 firstStop = stops[0]; lastStop = stops[stops.length - 1]; if (firstStop[0] > 0) { stops.unshift([ 0, firstStop[1] ]); } if (lastStop[0] < 1) { stops.push([ 1, lastStop[1] ]); } // Compute the stops each(stops, function (stop, i) { if (regexRgba.test(stop[1])) { colorObject = Color(stop[1]); stopColor = colorObject.get('rgb'); stopOpacity = colorObject.get('a'); } else { stopColor = stop[1]; stopOpacity = 1; } // Build the color attribute colors.push((stop[0] * 100) + '% ' + stopColor); // Only start and end opacities are allowed, so we use the first and the last if (!i) { opacity1 = stopOpacity; color2 = stopColor; } else { opacity2 = stopOpacity; color1 = stopColor; } }); // Apply the gradient to fills only. if (prop === 'fill') { // Handle linear gradient angle if (fillType === 'gradient') { x1 = gradient.x1 || gradient[0] || 0; y1 = gradient.y1 || gradient[1] || 0; x2 = gradient.x2 || gradient[2] || 0; y2 = gradient.y2 || gradient[3] || 0; fillAttr = 'angle="' + (90 - math.atan( (y2 - y1) / // y vector (x2 - x1) // x vector ) * 180 / mathPI) + '"'; addFillNode(); // Radial (circular) gradient } else { var r = gradient.r, sizex = r * 2, sizey = r * 2, cx = gradient.cx, cy = gradient.cy, radialReference = elem.radialReference, bBox, applyRadialGradient = function () { if (radialReference) { bBox = wrapper.getBBox(); cx += (radialReference[0] - bBox.x) / bBox.width - 0.5; cy += (radialReference[1] - bBox.y) / bBox.height - 0.5; sizex *= radialReference[2] / bBox.width; sizey *= radialReference[2] / bBox.height; } fillAttr = 'src="' + defaultOptions.global.VMLRadialGradientURL + '" ' + 'size="' + sizex + ',' + sizey + '" ' + 'origin="0.5,0.5" ' + 'position="' + cx + ',' + cy + '" ' + 'color2="' + color2 + '" '; addFillNode(); }; // Apply radial gradient if (wrapper.added) { applyRadialGradient(); } else { // We need to know the bounding box to get the size and position right wrapper.onAdd = applyRadialGradient; } // The fill element's color attribute is broken in IE8 standards mode, so we // need to set the parent shape's fillcolor attribute instead. ret = color1; } // Gradients are not supported for VML stroke, return the first color. #722. } else { ret = stopColor; } // if the color is an rgba color, split it and add a fill node // to hold the opacity component } else if (regexRgba.test(color) && elem.tagName !== 'IMG') { colorObject = Color(color); markup = ['<', prop, ' opacity="', colorObject.get('a'), '"/>']; createElement(this.prepVML(markup), null, null, elem); ret = colorObject.get('rgb'); } else { var propNodes = elem.getElementsByTagName(prop); // 'stroke' or 'fill' node if (propNodes.length) { propNodes[0].opacity = 1; propNodes[0].type = 'solid'; } ret = color; } return ret; }, /** * Take a VML string and prepare it for either IE8 or IE6/IE7. * @param {Array} markup A string array of the VML markup to prepare */ prepVML: function (markup) { var vmlStyle = 'display:inline-block;behavior:url(#default#VML);', isIE8 = this.isIE8; markup = markup.join(''); if (isIE8) { // add xmlns and style inline markup = markup.replace('/>', ' xmlns="urn:schemas-microsoft-com:vml" />'); if (markup.indexOf('style="') === -1) { markup = markup.replace('/>', ' style="' + vmlStyle + '" />'); } else { markup = markup.replace('style="', 'style="' + vmlStyle); } } else { // add namespace markup = markup.replace('<', '<hcv:'); } return markup; }, /** * Create rotated and aligned text * @param {String} str * @param {Number} x * @param {Number} y */ text: SVGRenderer.prototype.html, /** * Create and return a path element * @param {Array} path */ path: function (path) { var attr = { // subpixel precision down to 0.1 (width and height = 1px) coordsize: '10 10' }; if (isArray(path)) { attr.d = path; } else if (isObject(path)) { // attributes extend(attr, path); } // create the shape return this.createElement('shape').attr(attr); }, /** * Create and return a circle element. In VML circles are implemented as * shapes, which is faster than v:oval * @param {Number} x * @param {Number} y * @param {Number} r */ circle: function (x, y, r) { var circle = this.symbol('circle'); if (isObject(x)) { r = x.r; y = x.y; x = x.x; } circle.isCircle = true; // Causes x and y to mean center (#1682) circle.r = r; return circle.attr({ x: x, y: y }); }, /** * Create a group using an outer div and an inner v:group to allow rotating * and flipping. A simple v:group would have problems with positioning * child HTML elements and CSS clip. * * @param {String} name The name of the group */ g: function (name) { var wrapper, attribs; // set the class name if (name) { attribs = { 'className': PREFIX + name, 'class': PREFIX + name }; } // the div to hold HTML and clipping wrapper = this.createElement(DIV).attr(attribs); return wrapper; }, /** * VML override to create a regular HTML image * @param {String} src * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ image: function (src, x, y, width, height) { var obj = this.createElement('img') .attr({ src: src }); if (arguments.length > 1) { obj.attr({ x: x, y: y, width: width, height: height }); } return obj; }, /** * For rectangles, VML uses a shape for rect to overcome bugs and rotation problems */ createElement: function (nodeName) { return nodeName === 'rect' ? this.symbol(nodeName) : SVGRenderer.prototype.createElement.call(this, nodeName); }, /** * In the VML renderer, each child of an inverted div (group) is inverted * @param {Object} element * @param {Object} parentNode */ invertChild: function (element, parentNode) { var ren = this, parentStyle = parentNode.style, imgStyle = element.tagName === 'IMG' && element.style; // #1111 css(element, { flip: 'x', left: pInt(parentStyle.width) - (imgStyle ? pInt(imgStyle.top) : 1), top: pInt(parentStyle.height) - (imgStyle ? pInt(imgStyle.left) : 1), rotation: -90 }); // Recursively invert child elements, needed for nested composite shapes like box plots and error bars. #1680, #1806. each(element.childNodes, function (child) { ren.invertChild(child, element); }); }, /** * Symbol definitions that override the parent SVG renderer's symbols * */ symbols: { // VML specific arc function arc: function (x, y, w, h, options) { var start = options.start, end = options.end, radius = options.r || w || h, innerRadius = options.innerR, cosStart = mathCos(start), sinStart = mathSin(start), cosEnd = mathCos(end), sinEnd = mathSin(end), ret; if (end - start === 0) { // no angle, don't show it. return ['x']; } ret = [ 'wa', // clockwise arc to x - radius, // left y - radius, // top x + radius, // right y + radius, // bottom x + radius * cosStart, // start x y + radius * sinStart, // start y x + radius * cosEnd, // end x y + radius * sinEnd // end y ]; if (options.open && !innerRadius) { ret.push( 'e', M, x,// - innerRadius, y// - innerRadius ); } ret.push( 'at', // anti clockwise arc to x - innerRadius, // left y - innerRadius, // top x + innerRadius, // right y + innerRadius, // bottom x + innerRadius * cosEnd, // start x y + innerRadius * sinEnd, // start y x + innerRadius * cosStart, // end x y + innerRadius * sinStart, // end y 'x', // finish path 'e' // close ); ret.isArc = true; return ret; }, // Add circle symbol path. This performs significantly faster than v:oval. circle: function (x, y, w, h, wrapper) { if (wrapper) { w = h = 2 * wrapper.r; } // Center correction, #1682 if (wrapper && wrapper.isCircle) { x -= w / 2; y -= h / 2; } // Return the path return [ 'wa', // clockwisearcto x, // left y, // top x + w, // right y + h, // bottom x + w, // start x y + h / 2, // start y x + w, // end x y + h / 2, // end y //'x', // finish path 'e' // close ]; }, /** * Add rectangle symbol path which eases rotation and omits arcsize problems * compared to the built-in VML roundrect shape. When borders are not rounded, * use the simpler square path, else use the callout path without the arrow. */ rect: function (x, y, w, h, options) { return SVGRenderer.prototype.symbols[ !defined(options) || !options.r ? 'square' : 'callout' ].call(0, x, y, w, h, options); } } }; Highcharts.VMLRenderer = VMLRenderer = function () { this.init.apply(this, arguments); }; VMLRenderer.prototype = merge(SVGRenderer.prototype, VMLRendererExtension); // general renderer Renderer = VMLRenderer; } // This method is used with exporting in old IE, when emulating SVG (see #2314) SVGRenderer.prototype.measureSpanWidth = function (text, styles) { var measuringSpan = doc.createElement('span'), offsetWidth, textNode = doc.createTextNode(text); measuringSpan.appendChild(textNode); css(measuringSpan, styles); this.box.appendChild(measuringSpan); offsetWidth = measuringSpan.offsetWidth; discardElement(measuringSpan); // #2463 return offsetWidth; }; /* **************************************************************************** * * * END OF INTERNET EXPLORER <= 8 SPECIFIC CODE * * * *****************************************************************************/ /* **************************************************************************** * * * START OF ANDROID < 3 SPECIFIC CODE. THIS CAN BE REMOVED IF YOU'RE NOT * * TARGETING THAT SYSTEM. * * * *****************************************************************************/ var CanVGRenderer, CanVGController; if (useCanVG) { /** * The CanVGRenderer is empty from start to keep the source footprint small. * When requested, the CanVGController downloads the rest of the source packaged * together with the canvg library. */ Highcharts.CanVGRenderer = CanVGRenderer = function () { // Override the global SVG namespace to fake SVG/HTML that accepts CSS SVG_NS = 'http://www.w3.org/1999/xhtml'; }; /** * Start with an empty symbols object. This is needed when exporting is used (exporting.src.js will add a few symbols), but * the implementation from SvgRenderer will not be merged in until first render. */ CanVGRenderer.prototype.symbols = {}; /** * Handles on demand download of canvg rendering support. */ CanVGController = (function () { // List of renderering calls var deferredRenderCalls = []; /** * When downloaded, we are ready to draw deferred charts. */ function drawDeferred() { var callLength = deferredRenderCalls.length, callIndex; // Draw all pending render calls for (callIndex = 0; callIndex < callLength; callIndex++) { deferredRenderCalls[callIndex](); } // Clear the list deferredRenderCalls = []; } return { push: function (func, scriptLocation) { // Only get the script once if (deferredRenderCalls.length === 0) { getScript(scriptLocation, drawDeferred); } // Register render call deferredRenderCalls.push(func); } }; }()); Renderer = CanVGRenderer; } // end CanVGRenderer /* **************************************************************************** * * * END OF ANDROID < 3 SPECIFIC CODE * * * *****************************************************************************/ /** * The Tick class */ function Tick(axis, pos, type, noLabel) { this.axis = axis; this.pos = pos; this.type = type || ''; this.isNew = true; if (!type && !noLabel) { this.addLabel(); } } Tick.prototype = { /** * Write the tick label */ addLabel: function () { var tick = this, axis = tick.axis, options = axis.options, chart = axis.chart, horiz = axis.horiz, categories = axis.categories, names = axis.names, pos = tick.pos, labelOptions = options.labels, rotation = labelOptions.rotation, str, tickPositions = axis.tickPositions, width = (horiz && categories && !labelOptions.step && !labelOptions.staggerLines && !labelOptions.rotation && chart.plotWidth / tickPositions.length) || (!horiz && (chart.margin[3] || chart.chartWidth * 0.33)), // #1580, #1931 isFirst = pos === tickPositions[0], isLast = pos === tickPositions[tickPositions.length - 1], css, attr, value = categories ? pick(categories[pos], names[pos], pos) : pos, label = tick.label, tickPositionInfo = tickPositions.info, dateTimeLabelFormat; // Set the datetime label format. If a higher rank is set for this position, use that. If not, // use the general format. if (axis.isDatetimeAxis && tickPositionInfo) { dateTimeLabelFormat = options.dateTimeLabelFormats[tickPositionInfo.higherRanks[pos] || tickPositionInfo.unitName]; } // set properties for access in render method tick.isFirst = isFirst; tick.isLast = isLast; // get the string str = axis.labelFormatter.call({ axis: axis, chart: chart, isFirst: isFirst, isLast: isLast, dateTimeLabelFormat: dateTimeLabelFormat, value: axis.isLog ? correctFloat(lin2log(value)) : value }); // prepare CSS css = width && { width: mathMax(1, mathRound(width - 2 * (labelOptions.padding || 10))) + PX }; // first call if (!defined(label)) { attr = { align: axis.labelAlign }; if (isNumber(rotation)) { attr.rotation = rotation; } if (width && labelOptions.ellipsis) { css.HcHeight = axis.len / tickPositions.length; } tick.label = label = defined(str) && labelOptions.enabled ? chart.renderer.text( str, 0, 0, labelOptions.useHTML ) .attr(attr) // without position absolute, IE export sometimes is wrong .css(extend(css, labelOptions.style)) .add(axis.labelGroup) : null; // Set the tick baseline and correct for rotation (#1764) axis.tickBaseline = chart.renderer.fontMetrics(labelOptions.style.fontSize, label).b; if (rotation && axis.side === 2) { axis.tickBaseline *= mathCos(rotation * deg2rad); } // update } else if (label) { label.attr({ text: str }) .css(css); } tick.yOffset = label ? pick(labelOptions.y, axis.tickBaseline + (axis.side === 2 ? 8 : -(label.getBBox().height / 2))) : 0; }, /** * Get the offset height or width of the label */ getLabelSize: function () { var label = this.label, axis = this.axis; return label ? label.getBBox()[axis.horiz ? 'height' : 'width'] : 0; }, /** * Find how far the labels extend to the right and left of the tick's x position. Used for anti-collision * detection with overflow logic. */ getLabelSides: function () { var bBox = this.label.getBBox(), axis = this.axis, horiz = axis.horiz, options = axis.options, labelOptions = options.labels, size = horiz ? bBox.width : bBox.height, leftSide = horiz ? labelOptions.x - size * { left: 0, center: 0.5, right: 1 }[axis.labelAlign] : 0, rightSide = horiz ? size + leftSide : size; return [leftSide, rightSide]; }, /** * Handle the label overflow by adjusting the labels to the left and right edge, or * hide them if they collide into the neighbour label. */ handleOverflow: function (index, xy) { var show = true, axis = this.axis, isFirst = this.isFirst, isLast = this.isLast, horiz = axis.horiz, pxPos = horiz ? xy.x : xy.y, reversed = axis.reversed, tickPositions = axis.tickPositions, sides = this.getLabelSides(), leftSide = sides[0], rightSide = sides[1], axisLeft, axisRight, neighbour, neighbourEdge, line = this.label.line, lineIndex = line || 0, labelEdge = axis.labelEdge, justifyLabel = axis.justifyLabels && (isFirst || isLast), justifyToPlot; // Hide it if it now overlaps the neighbour label if (labelEdge[lineIndex] === UNDEFINED || pxPos + leftSide > labelEdge[lineIndex]) { labelEdge[lineIndex] = pxPos + rightSide; } else if (!justifyLabel) { show = false; } if (justifyLabel) { justifyToPlot = axis.justifyToPlot; axisLeft = justifyToPlot ? axis.pos : 0; axisRight = justifyToPlot ? axisLeft + axis.len : axis.chart.chartWidth; // Find the firsth neighbour on the same line do { index += (isFirst ? 1 : -1); neighbour = axis.ticks[tickPositions[index]]; } while (tickPositions[index] && (!neighbour || !neighbour.label || neighbour.label.line !== line)); // #3044 neighbourEdge = neighbour && neighbour.label.xy && neighbour.label.xy.x + neighbour.getLabelSides()[isFirst ? 0 : 1]; if ((isFirst && !reversed) || (isLast && reversed)) { // Is the label spilling out to the left of the plot area? if (pxPos + leftSide < axisLeft) { // Align it to plot left pxPos = axisLeft - leftSide; // Hide it if it now overlaps the neighbour label if (neighbour && pxPos + rightSide > neighbourEdge) { show = false; } } } else { // Is the label spilling out to the right of the plot area? if (pxPos + rightSide > axisRight) { // Align it to plot right pxPos = axisRight - rightSide; // Hide it if it now overlaps the neighbour label if (neighbour && pxPos + leftSide < neighbourEdge) { show = false; } } } // Set the modified x position of the label xy.x = pxPos; } return show; }, /** * Get the x and y position for ticks and labels */ getPosition: function (horiz, pos, tickmarkOffset, old) { var axis = this.axis, chart = axis.chart, cHeight = (old && chart.oldChartHeight) || chart.chartHeight; return { x: horiz ? axis.translate(pos + tickmarkOffset, null, null, old) + axis.transB : axis.left + axis.offset + (axis.opposite ? ((old && chart.oldChartWidth) || chart.chartWidth) - axis.right - axis.left : 0), y: horiz ? cHeight - axis.bottom + axis.offset - (axis.opposite ? axis.height : 0) : cHeight - axis.translate(pos + tickmarkOffset, null, null, old) - axis.transB }; }, /** * Get the x, y position of the tick label */ getLabelPosition: function (x, y, label, horiz, labelOptions, tickmarkOffset, index, step) { var axis = this.axis, transA = axis.transA, reversed = axis.reversed, staggerLines = axis.staggerLines; x = x + labelOptions.x - (tickmarkOffset && horiz ? tickmarkOffset * transA * (reversed ? -1 : 1) : 0); y = y + this.yOffset - (tickmarkOffset && !horiz ? tickmarkOffset * transA * (reversed ? 1 : -1) : 0); // Correct for staggered labels if (staggerLines) { label.line = (index / (step || 1) % staggerLines); y += label.line * (axis.labelOffset / staggerLines); } return { x: x, y: y }; }, /** * Extendible method to return the path of the marker */ getMarkPath: function (x, y, tickLength, tickWidth, horiz, renderer) { return renderer.crispLine([ M, x, y, L, x + (horiz ? 0 : -tickLength), y + (horiz ? tickLength : 0) ], tickWidth); }, /** * Put everything in place * * @param index {Number} * @param old {Boolean} Use old coordinates to prepare an animation into new position */ render: function (index, old, opacity) { var tick = this, axis = tick.axis, options = axis.options, chart = axis.chart, renderer = chart.renderer, horiz = axis.horiz, type = tick.type, label = tick.label, pos = tick.pos, labelOptions = options.labels, gridLine = tick.gridLine, gridPrefix = type ? type + 'Grid' : 'grid', tickPrefix = type ? type + 'Tick' : 'tick', gridLineWidth = options[gridPrefix + 'LineWidth'], gridLineColor = options[gridPrefix + 'LineColor'], dashStyle = options[gridPrefix + 'LineDashStyle'], tickLength = options[tickPrefix + 'Length'], tickWidth = options[tickPrefix + 'Width'] || 0, tickColor = options[tickPrefix + 'Color'], tickPosition = options[tickPrefix + 'Position'], gridLinePath, mark = tick.mark, markPath, step = labelOptions.step, attribs, show = true, tickmarkOffset = axis.tickmarkOffset, xy = tick.getPosition(horiz, pos, tickmarkOffset, old), x = xy.x, y = xy.y, reverseCrisp = ((horiz && x === axis.pos + axis.len) || (!horiz && y === axis.pos)) ? -1 : 1; // #1480, #1687 opacity = pick(opacity, 1); this.isActive = true; // create the grid line if (gridLineWidth) { gridLinePath = axis.getPlotLinePath(pos + tickmarkOffset, gridLineWidth * reverseCrisp, old, true); if (gridLine === UNDEFINED) { attribs = { stroke: gridLineColor, 'stroke-width': gridLineWidth }; if (dashStyle) { attribs.dashstyle = dashStyle; } if (!type) { attribs.zIndex = 1; } if (old) { attribs.opacity = 0; } tick.gridLine = gridLine = gridLineWidth ? renderer.path(gridLinePath) .attr(attribs).add(axis.gridGroup) : null; } // If the parameter 'old' is set, the current call will be followed // by another call, therefore do not do any animations this time if (!old && gridLine && gridLinePath) { gridLine[tick.isNew ? 'attr' : 'animate']({ d: gridLinePath, opacity: opacity }); } } // create the tick mark if (tickWidth && tickLength) { // negate the length if (tickPosition === 'inside') { tickLength = -tickLength; } if (axis.opposite) { tickLength = -tickLength; } markPath = tick.getMarkPath(x, y, tickLength, tickWidth * reverseCrisp, horiz, renderer); if (mark) { // updating mark.animate({ d: markPath, opacity: opacity }); } else { // first time tick.mark = renderer.path( markPath ).attr({ stroke: tickColor, 'stroke-width': tickWidth, opacity: opacity }).add(axis.axisGroup); } } // the label is created on init - now move it into place if (label && !isNaN(x)) { label.xy = xy = tick.getLabelPosition(x, y, label, horiz, labelOptions, tickmarkOffset, index, step); // Apply show first and show last. If the tick is both first and last, it is // a single centered tick, in which case we show the label anyway (#2100). if ((tick.isFirst && !tick.isLast && !pick(options.showFirstLabel, 1)) || (tick.isLast && !tick.isFirst && !pick(options.showLastLabel, 1))) { show = false; // Handle label overflow and show or hide accordingly } else if (!axis.isRadial && !labelOptions.step && !labelOptions.rotation && !old && opacity !== 0) { show = tick.handleOverflow(index, xy); } // apply step if (step && index % step) { // show those indices dividable by step show = false; } // Set the new position, and show or hide if (show && !isNaN(xy.y)) { xy.opacity = opacity; label[tick.isNew ? 'attr' : 'animate'](xy); tick.isNew = false; } else { label.attr('y', -9999); // #1338 } } }, /** * Destructor for the tick prototype */ destroy: function () { destroyObjectProperties(this, this.axis); } }; /** * Create a new axis object * @param {Object} chart * @param {Object} options */ function Axis() { this.init.apply(this, arguments); } Axis.prototype = { /** * Default options for the X axis - the Y axis has extended defaults */ defaultOptions: { // allowDecimals: null, // alternateGridColor: null, // categories: [], dateTimeLabelFormats: { millisecond: '%H:%M:%S.%L', second: '%H:%M:%S', minute: '%H:%M', hour: '%H:%M', day: '%e. %b', week: '%e. %b', month: '%b \'%y', year: '%Y' }, endOnTick: false, gridLineColor: '#C0C0C0', // gridLineDashStyle: 'solid', // gridLineWidth: 0, // reversed: false, labels: defaultLabelOptions, // { step: null }, lineColor: '#C0D0E0', lineWidth: 1, //linkedTo: null, //max: undefined, //min: undefined, minPadding: 0.01, maxPadding: 0.01, //minRange: null, minorGridLineColor: '#E0E0E0', // minorGridLineDashStyle: null, minorGridLineWidth: 1, minorTickColor: '#A0A0A0', //minorTickInterval: null, minorTickLength: 2, minorTickPosition: 'outside', // inside or outside //minorTickWidth: 0, //opposite: false, //offset: 0, //plotBands: [{ // events: {}, // zIndex: 1, // labels: { align, x, verticalAlign, y, style, rotation, textAlign } //}], //plotLines: [{ // events: {} // dashStyle: {} // zIndex: // labels: { align, x, verticalAlign, y, style, rotation, textAlign } //}], //reversed: false, // showFirstLabel: true, // showLastLabel: true, startOfWeek: 1, startOnTick: false, tickColor: '#C0D0E0', //tickInterval: null, tickLength: 10, tickmarkPlacement: 'between', // on or between tickPixelInterval: 100, tickPosition: 'outside', tickWidth: 1, title: { //text: null, align: 'middle', // low, middle or high //margin: 0 for horizontal, 10 for vertical axes, //rotation: 0, //side: 'outside', style: { color: '#707070' } //x: 0, //y: 0 }, type: 'linear' // linear, logarithmic or datetime }, /** * This options set extends the defaultOptions for Y axes */ defaultYAxisOptions: { endOnTick: true, gridLineWidth: 1, tickPixelInterval: 72, showLastLabel: true, labels: { x: -8, y: 3 }, lineWidth: 0, maxPadding: 0.05, minPadding: 0.05, startOnTick: true, tickWidth: 0, title: { rotation: 270, text: 'Values' }, stackLabels: { enabled: false, //align: dynamic, //y: dynamic, //x: dynamic, //verticalAlign: dynamic, //textAlign: dynamic, //rotation: 0, formatter: function () { return numberFormat(this.total, -1); }, style: defaultLabelOptions.style } }, /** * These options extend the defaultOptions for left axes */ defaultLeftAxisOptions: { labels: { x: -15, y: null }, title: { rotation: 270 } }, /** * These options extend the defaultOptions for right axes */ defaultRightAxisOptions: { labels: { x: 15, y: null }, title: { rotation: 90 } }, /** * These options extend the defaultOptions for bottom axes */ defaultBottomAxisOptions: { labels: { x: 0, y: null // based on font size // overflow: undefined, // staggerLines: null }, title: { rotation: 0 } }, /** * These options extend the defaultOptions for left axes */ defaultTopAxisOptions: { labels: { x: 0, y: -15 // overflow: undefined // staggerLines: null }, title: { rotation: 0 } }, /** * Initialize the axis */ init: function (chart, userOptions) { var isXAxis = userOptions.isX, axis = this; // Flag, is the axis horizontal axis.horiz = chart.inverted ? !isXAxis : isXAxis; // Flag, isXAxis axis.isXAxis = isXAxis; axis.coll = isXAxis ? 'xAxis' : 'yAxis'; axis.opposite = userOptions.opposite; // needed in setOptions axis.side = userOptions.side || (axis.horiz ? (axis.opposite ? 0 : 2) : // top : bottom (axis.opposite ? 1 : 3)); // right : left axis.setOptions(userOptions); var options = this.options, type = options.type, isDatetimeAxis = type === 'datetime'; axis.labelFormatter = options.labels.formatter || axis.defaultLabelFormatter; // can be overwritten by dynamic format // Flag, stagger lines or not axis.userOptions = userOptions; //axis.axisTitleMargin = UNDEFINED,// = options.title.margin, axis.minPixelPadding = 0; //axis.ignoreMinPadding = UNDEFINED; // can be set to true by a column or bar series //axis.ignoreMaxPadding = UNDEFINED; axis.chart = chart; axis.reversed = options.reversed; axis.zoomEnabled = options.zoomEnabled !== false; // Initial categories axis.categories = options.categories || type === 'category'; axis.names = []; // Elements //axis.axisGroup = UNDEFINED; //axis.gridGroup = UNDEFINED; //axis.axisTitle = UNDEFINED; //axis.axisLine = UNDEFINED; // Shorthand types axis.isLog = type === 'logarithmic'; axis.isDatetimeAxis = isDatetimeAxis; // Flag, if axis is linked to another axis axis.isLinked = defined(options.linkedTo); // Linked axis. //axis.linkedParent = UNDEFINED; // Tick positions //axis.tickPositions = UNDEFINED; // array containing predefined positions // Tick intervals //axis.tickInterval = UNDEFINED; //axis.minorTickInterval = UNDEFINED; axis.tickmarkOffset = (axis.categories && options.tickmarkPlacement === 'between' && pick(options.tickInterval, 1) === 1) ? 0.5 : 0; // #3202 // Major ticks axis.ticks = {}; axis.labelEdge = []; // Minor ticks axis.minorTicks = {}; //axis.tickAmount = UNDEFINED; // List of plotLines/Bands axis.plotLinesAndBands = []; // Alternate bands axis.alternateBands = {}; // Axis metrics //axis.left = UNDEFINED; //axis.top = UNDEFINED; //axis.width = UNDEFINED; //axis.height = UNDEFINED; //axis.bottom = UNDEFINED; //axis.right = UNDEFINED; //axis.transA = UNDEFINED; //axis.transB = UNDEFINED; //axis.oldTransA = UNDEFINED; axis.len = 0; //axis.oldMin = UNDEFINED; //axis.oldMax = UNDEFINED; //axis.oldUserMin = UNDEFINED; //axis.oldUserMax = UNDEFINED; //axis.oldAxisLength = UNDEFINED; axis.minRange = axis.userMinRange = options.minRange || options.maxZoom; axis.range = options.range; axis.offset = options.offset || 0; // Dictionary for stacks axis.stacks = {}; axis.oldStacks = {}; // Min and max in the data //axis.dataMin = UNDEFINED, //axis.dataMax = UNDEFINED, // The axis range axis.max = null; axis.min = null; // User set min and max //axis.userMin = UNDEFINED, //axis.userMax = UNDEFINED, // Crosshair options axis.crosshair = pick(options.crosshair, splat(chart.options.tooltip.crosshairs)[isXAxis ? 0 : 1], false); // Run Axis var eventType, events = axis.options.events; // Register if (inArray(axis, chart.axes) === -1) { // don't add it again on Axis.update() if (isXAxis && !this.isColorAxis) { // #2713 chart.axes.splice(chart.xAxis.length, 0, axis); } else { chart.axes.push(axis); } chart[axis.coll].push(axis); } axis.series = axis.series || []; // populated by Series // inverted charts have reversed xAxes as default if (chart.inverted && isXAxis && axis.reversed === UNDEFINED) { axis.reversed = true; } axis.removePlotBand = axis.removePlotBandOrLine; axis.removePlotLine = axis.removePlotBandOrLine; // register event listeners for (eventType in events) { addEvent(axis, eventType, events[eventType]); } // extend logarithmic axis if (axis.isLog) { axis.val2lin = log2lin; axis.lin2val = lin2log; } }, /** * Merge and set options */ setOptions: function (userOptions) { this.options = merge( this.defaultOptions, this.isXAxis ? {} : this.defaultYAxisOptions, [this.defaultTopAxisOptions, this.defaultRightAxisOptions, this.defaultBottomAxisOptions, this.defaultLeftAxisOptions][this.side], merge( defaultOptions[this.coll], // if set in setOptions (#1053) userOptions ) ); }, /** * The default label formatter. The context is a special config object for the label. */ defaultLabelFormatter: function () { var axis = this.axis, value = this.value, categories = axis.categories, dateTimeLabelFormat = this.dateTimeLabelFormat, numericSymbols = defaultOptions.lang.numericSymbols, i = numericSymbols && numericSymbols.length, multi, ret, formatOption = axis.options.labels.format, // make sure the same symbol is added for all labels on a linear axis numericSymbolDetector = axis.isLog ? value : axis.tickInterval; if (formatOption) { ret = format(formatOption, this); } else if (categories) { ret = value; } else if (dateTimeLabelFormat) { // datetime axis ret = dateFormat(dateTimeLabelFormat, value); } else if (i && numericSymbolDetector >= 1000) { // Decide whether we should add a numeric symbol like k (thousands) or M (millions). // If we are to enable this in tooltip or other places as well, we can move this // logic to the numberFormatter and enable it by a parameter. while (i-- && ret === UNDEFINED) { multi = Math.pow(1000, i + 1); if (numericSymbolDetector >= multi && numericSymbols[i] !== null) { ret = numberFormat(value / multi, -1) + numericSymbols[i]; } } } if (ret === UNDEFINED) { if (mathAbs(value) >= 10000) { // add thousands separators ret = numberFormat(value, 0); } else { // small numbers ret = numberFormat(value, -1, UNDEFINED, ''); // #2466 } } return ret; }, /** * Get the minimum and maximum for the series of each axis */ getSeriesExtremes: function () { var axis = this, chart = axis.chart; axis.hasVisibleSeries = false; // Reset properties in case we're redrawing (#3353) axis.dataMin = axis.dataMax = axis.ignoreMinPadding = axis.ignoreMaxPadding = null; if (axis.buildStacks) { axis.buildStacks(); } // loop through this axis' series each(axis.series, function (series) { if (series.visible || !chart.options.chart.ignoreHiddenSeries) { var seriesOptions = series.options, xData, threshold = seriesOptions.threshold, seriesDataMin, seriesDataMax; axis.hasVisibleSeries = true; // Validate threshold in logarithmic axes if (axis.isLog && threshold <= 0) { threshold = null; } // Get dataMin and dataMax for X axes if (axis.isXAxis) { xData = series.xData; if (xData.length) { axis.dataMin = mathMin(pick(axis.dataMin, xData[0]), arrayMin(xData)); axis.dataMax = mathMax(pick(axis.dataMax, xData[0]), arrayMax(xData)); } // Get dataMin and dataMax for Y axes, as well as handle stacking and processed data } else { // Get this particular series extremes series.getExtremes(); seriesDataMax = series.dataMax; seriesDataMin = series.dataMin; // Get the dataMin and dataMax so far. If percentage is used, the min and max are // always 0 and 100. If seriesDataMin and seriesDataMax is null, then series // doesn't have active y data, we continue with nulls if (defined(seriesDataMin) && defined(seriesDataMax)) { axis.dataMin = mathMin(pick(axis.dataMin, seriesDataMin), seriesDataMin); axis.dataMax = mathMax(pick(axis.dataMax, seriesDataMax), seriesDataMax); } // Adjust to threshold if (defined(threshold)) { if (axis.dataMin >= threshold) { axis.dataMin = threshold; axis.ignoreMinPadding = true; } else if (axis.dataMax < threshold) { axis.dataMax = threshold; axis.ignoreMaxPadding = true; } } } } }); }, /** * Translate from axis value to pixel position on the chart, or back * */ translate: function (val, backwards, cvsCoord, old, handleLog, pointPlacement) { var axis = this, sign = 1, cvsOffset = 0, localA = old ? axis.oldTransA : axis.transA, localMin = old ? axis.oldMin : axis.min, returnValue, minPixelPadding = axis.minPixelPadding, postTranslate = (axis.options.ordinal || (axis.isLog && handleLog)) && axis.lin2val; if (!localA) { localA = axis.transA; } // In vertical axes, the canvas coordinates start from 0 at the top like in // SVG. if (cvsCoord) { sign *= -1; // canvas coordinates inverts the value cvsOffset = axis.len; } // Handle reversed axis if (axis.reversed) { sign *= -1; cvsOffset -= sign * (axis.sector || axis.len); } // From pixels to value if (backwards) { // reverse translation val = val * sign + cvsOffset; val -= minPixelPadding; returnValue = val / localA + localMin; // from chart pixel to value if (postTranslate) { // log and ordinal axes returnValue = axis.lin2val(returnValue); } // From value to pixels } else { if (postTranslate) { // log and ordinal axes val = axis.val2lin(val); } if (pointPlacement === 'between') { pointPlacement = 0.5; } returnValue = sign * (val - localMin) * localA + cvsOffset + (sign * minPixelPadding) + (isNumber(pointPlacement) ? localA * pointPlacement * axis.pointRange : 0); } return returnValue; }, /** * Utility method to translate an axis value to pixel position. * @param {Number} value A value in terms of axis units * @param {Boolean} paneCoordinates Whether to return the pixel coordinate relative to the chart * or just the axis/pane itself. */ toPixels: function (value, paneCoordinates) { return this.translate(value, false, !this.horiz, null, true) + (paneCoordinates ? 0 : this.pos); }, /* * Utility method to translate a pixel position in to an axis value * @param {Number} pixel The pixel value coordinate * @param {Boolean} paneCoordiantes Whether the input pixel is relative to the chart or just the * axis/pane itself. */ toValue: function (pixel, paneCoordinates) { return this.translate(pixel - (paneCoordinates ? 0 : this.pos), true, !this.horiz, null, true); }, /** * Create the path for a plot line that goes from the given value on * this axis, across the plot to the opposite side * @param {Number} value * @param {Number} lineWidth Used for calculation crisp line * @param {Number] old Use old coordinates (for resizing and rescaling) */ getPlotLinePath: function (value, lineWidth, old, force, translatedValue) { var axis = this, chart = axis.chart, axisLeft = axis.left, axisTop = axis.top, x1, y1, x2, y2, cHeight = (old && chart.oldChartHeight) || chart.chartHeight, cWidth = (old && chart.oldChartWidth) || chart.chartWidth, skip, transB = axis.transB; translatedValue = pick(translatedValue, axis.translate(value, null, null, old)); x1 = x2 = mathRound(translatedValue + transB); y1 = y2 = mathRound(cHeight - translatedValue - transB); if (isNaN(translatedValue)) { // no min or max skip = true; } else if (axis.horiz) { y1 = axisTop; y2 = cHeight - axis.bottom; if (x1 < axisLeft || x1 > axisLeft + axis.width) { skip = true; } } else { x1 = axisLeft; x2 = cWidth - axis.right; if (y1 < axisTop || y1 > axisTop + axis.height) { skip = true; } } return skip && !force ? null : chart.renderer.crispLine([M, x1, y1, L, x2, y2], lineWidth || 1); }, /** * Set the tick positions of a linear axis to round values like whole tens or every five. */ getLinearTickPositions: function (tickInterval, min, max) { var pos, lastPos, roundedMin = correctFloat(mathFloor(min / tickInterval) * tickInterval), roundedMax = correctFloat(mathCeil(max / tickInterval) * tickInterval), tickPositions = []; // For single points, add a tick regardless of the relative position (#2662) if (min === max && isNumber(min)) { return [min]; } // Populate the intermediate values pos = roundedMin; while (pos <= roundedMax) { // Place the tick on the rounded value tickPositions.push(pos); // Always add the raw tickInterval, not the corrected one. pos = correctFloat(pos + tickInterval); // If the interval is not big enough in the current min - max range to actually increase // the loop variable, we need to break out to prevent endless loop. Issue #619 if (pos === lastPos) { break; } // Record the last value lastPos = pos; } return tickPositions; }, /** * Return the minor tick positions. For logarithmic axes, reuse the same logic * as for major ticks. */ getMinorTickPositions: function () { var axis = this, options = axis.options, tickPositions = axis.tickPositions, minorTickInterval = axis.minorTickInterval, minorTickPositions = [], pos, i, len; if (axis.isLog) { len = tickPositions.length; for (i = 1; i < len; i++) { minorTickPositions = minorTickPositions.concat( axis.getLogTickPositions(minorTickInterval, tickPositions[i - 1], tickPositions[i], true) ); } } else if (axis.isDatetimeAxis && options.minorTickInterval === 'auto') { // #1314 minorTickPositions = minorTickPositions.concat( axis.getTimeTicks( axis.normalizeTimeTickInterval(minorTickInterval), axis.min, axis.max, options.startOfWeek ) ); if (minorTickPositions[0] < axis.min) { minorTickPositions.shift(); } } else { for (pos = axis.min + (tickPositions[0] - axis.min) % minorTickInterval; pos <= axis.max; pos += minorTickInterval) { minorTickPositions.push(pos); } } return minorTickPositions; }, /** * Adjust the min and max for the minimum range. Keep in mind that the series data is * not yet processed, so we don't have information on data cropping and grouping, or * updated axis.pointRange or series.pointRange. The data can't be processed until * we have finally established min and max. */ adjustForMinRange: function () { var axis = this, options = axis.options, min = axis.min, max = axis.max, zoomOffset, spaceAvailable = axis.dataMax - axis.dataMin >= axis.minRange, closestDataRange, i, distance, xData, loopLength, minArgs, maxArgs; // Set the automatic minimum range based on the closest point distance if (axis.isXAxis && axis.minRange === UNDEFINED && !axis.isLog) { if (defined(options.min) || defined(options.max)) { axis.minRange = null; // don't do this again } else { // Find the closest distance between raw data points, as opposed to // closestPointRange that applies to processed points (cropped and grouped) each(axis.series, function (series) { xData = series.xData; loopLength = series.xIncrement ? 1 : xData.length - 1; for (i = loopLength; i > 0; i--) { distance = xData[i] - xData[i - 1]; if (closestDataRange === UNDEFINED || distance < closestDataRange) { closestDataRange = distance; } } }); axis.minRange = mathMin(closestDataRange * 5, axis.dataMax - axis.dataMin); } } // if minRange is exceeded, adjust if (max - min < axis.minRange) { var minRange = axis.minRange; zoomOffset = (minRange - max + min) / 2; // if min and max options have been set, don't go beyond it minArgs = [min - zoomOffset, pick(options.min, min - zoomOffset)]; if (spaceAvailable) { // if space is available, stay within the data range minArgs[2] = axis.dataMin; } min = arrayMax(minArgs); maxArgs = [min + minRange, pick(options.max, min + minRange)]; if (spaceAvailable) { // if space is availabe, stay within the data range maxArgs[2] = axis.dataMax; } max = arrayMin(maxArgs); // now if the max is adjusted, adjust the min back if (max - min < minRange) { minArgs[0] = max - minRange; minArgs[1] = pick(options.min, max - minRange); min = arrayMax(minArgs); } } // Record modified extremes axis.min = min; axis.max = max; }, /** * Update translation information */ setAxisTranslation: function (saveOld) { var axis = this, range = axis.max - axis.min, pointRange = axis.axisPointRange || 0, closestPointRange, minPointOffset = 0, pointRangePadding = 0, linkedParent = axis.linkedParent, ordinalCorrection, hasCategories = !!axis.categories, transA = axis.transA; // Adjust translation for padding. Y axis with categories need to go through the same (#1784). if (axis.isXAxis || hasCategories || pointRange) { if (linkedParent) { minPointOffset = linkedParent.minPointOffset; pointRangePadding = linkedParent.pointRangePadding; } else { each(axis.series, function (series) { var seriesPointRange = hasCategories ? 1 : (axis.isXAxis ? series.pointRange : (axis.axisPointRange || 0)), // #2806 pointPlacement = series.options.pointPlacement, seriesClosestPointRange = series.closestPointRange; if (seriesPointRange > range) { // #1446 seriesPointRange = 0; } pointRange = mathMax(pointRange, seriesPointRange); // minPointOffset is the value padding to the left of the axis in order to make // room for points with a pointRange, typically columns. When the pointPlacement option // is 'between' or 'on', this padding does not apply. minPointOffset = mathMax( minPointOffset, isString(pointPlacement) ? 0 : seriesPointRange / 2 ); // Determine the total padding needed to the length of the axis to make room for the // pointRange. If the series' pointPlacement is 'on', no padding is added. pointRangePadding = mathMax( pointRangePadding, pointPlacement === 'on' ? 0 : seriesPointRange ); // Set the closestPointRange if (!series.noSharedTooltip && defined(seriesClosestPointRange)) { closestPointRange = defined(closestPointRange) ? mathMin(closestPointRange, seriesClosestPointRange) : seriesClosestPointRange; } }); } // Record minPointOffset and pointRangePadding ordinalCorrection = axis.ordinalSlope && closestPointRange ? axis.ordinalSlope / closestPointRange : 1; // #988, #1853 axis.minPointOffset = minPointOffset = minPointOffset * ordinalCorrection; axis.pointRangePadding = pointRangePadding = pointRangePadding * ordinalCorrection; // pointRange means the width reserved for each point, like in a column chart axis.pointRange = mathMin(pointRange, range); // closestPointRange means the closest distance between points. In columns // it is mostly equal to pointRange, but in lines pointRange is 0 while closestPointRange // is some other value axis.closestPointRange = closestPointRange; } // Secondary values if (saveOld) { axis.oldTransA = transA; } axis.translationSlope = axis.transA = transA = axis.len / ((range + pointRangePadding) || 1); axis.transB = axis.horiz ? axis.left : axis.bottom; // translation addend axis.minPixelPadding = transA * minPointOffset; }, /** * Set the tick positions to round values and optionally extend the extremes * to the nearest tick */ setTickPositions: function (secondPass) { var axis = this, chart = axis.chart, options = axis.options, startOnTick = options.startOnTick, endOnTick = options.endOnTick, isLog = axis.isLog, isDatetimeAxis = axis.isDatetimeAxis, isXAxis = axis.isXAxis, isLinked = axis.isLinked, tickPositioner = axis.options.tickPositioner, maxPadding = options.maxPadding, minPadding = options.minPadding, length, linkedParentExtremes, tickIntervalOption = options.tickInterval, minTickIntervalOption = options.minTickInterval, tickPixelIntervalOption = options.tickPixelInterval, tickPositions, keepTwoTicksOnly, categories = axis.categories; // linked axis gets the extremes from the parent axis if (isLinked) { axis.linkedParent = chart[axis.coll][options.linkedTo]; linkedParentExtremes = axis.linkedParent.getExtremes(); axis.min = pick(linkedParentExtremes.min, linkedParentExtremes.dataMin); axis.max = pick(linkedParentExtremes.max, linkedParentExtremes.dataMax); if (options.type !== axis.linkedParent.options.type) { error(11, 1); // Can't link axes of different type } } else { // initial min and max from the extreme data values axis.min = pick(axis.userMin, options.min, axis.dataMin); axis.max = pick(axis.userMax, options.max, axis.dataMax); } if (isLog) { if (!secondPass && mathMin(axis.min, pick(axis.dataMin, axis.min)) <= 0) { // #978 error(10, 1); // Can't plot negative values on log axis } axis.min = correctFloat(log2lin(axis.min)); // correctFloat cures #934 axis.max = correctFloat(log2lin(axis.max)); } // handle zoomed range if (axis.range && defined(axis.max)) { axis.userMin = axis.min = mathMax(axis.min, axis.max - axis.range); // #618 axis.userMax = axis.max; axis.range = null; // don't use it when running setExtremes } // Hook for adjusting this.min and this.max. Used by bubble series. if (axis.beforePadding) { axis.beforePadding(); } // adjust min and max for the minimum range axis.adjustForMinRange(); // Pad the values to get clear of the chart's edges. To avoid tickInterval taking the padding // into account, we do this after computing tick interval (#1337). if (!categories && !axis.axisPointRange && !axis.usePercentage && !isLinked && defined(axis.min) && defined(axis.max)) { length = axis.max - axis.min; if (length) { if (!defined(options.min) && !defined(axis.userMin) && minPadding && (axis.dataMin < 0 || !axis.ignoreMinPadding)) { axis.min -= length * minPadding; } if (!defined(options.max) && !defined(axis.userMax) && maxPadding && (axis.dataMax > 0 || !axis.ignoreMaxPadding)) { axis.max += length * maxPadding; } } } // Stay within floor and ceiling if (isNumber(options.floor)) { axis.min = mathMax(axis.min, options.floor); } if (isNumber(options.ceiling)) { axis.max = mathMin(axis.max, options.ceiling); } // get tickInterval if (axis.min === axis.max || axis.min === undefined || axis.max === undefined) { axis.tickInterval = 1; } else if (isLinked && !tickIntervalOption && tickPixelIntervalOption === axis.linkedParent.options.tickPixelInterval) { axis.tickInterval = axis.linkedParent.tickInterval; } else { axis.tickInterval = pick( tickIntervalOption, categories ? // for categoried axis, 1 is default, for linear axis use tickPix 1 : // don't let it be more than the data range (axis.max - axis.min) * tickPixelIntervalOption / mathMax(axis.len, tickPixelIntervalOption) ); // For squished axes, set only two ticks if (!defined(tickIntervalOption) && axis.len < tickPixelIntervalOption && !this.isRadial && !this.isLog && !categories && startOnTick && endOnTick) { keepTwoTicksOnly = true; axis.tickInterval /= 4; // tick extremes closer to the real values } } // Now we're finished detecting min and max, crop and group series data. This // is in turn needed in order to find tick positions in ordinal axes. if (isXAxis && !secondPass) { each(axis.series, function (series) { series.processData(axis.min !== axis.oldMin || axis.max !== axis.oldMax); }); } // set the translation factor used in translate function axis.setAxisTranslation(true); // hook for ordinal axes and radial axes if (axis.beforeSetTickPositions) { axis.beforeSetTickPositions(); } // hook for extensions, used in Highstock ordinal axes if (axis.postProcessTickInterval) { axis.tickInterval = axis.postProcessTickInterval(axis.tickInterval); } // In column-like charts, don't cramp in more ticks than there are points (#1943) if (axis.pointRange) { axis.tickInterval = mathMax(axis.pointRange, axis.tickInterval); } // Before normalizing the tick interval, handle minimum tick interval. This applies only if tickInterval is not defined. if (!tickIntervalOption && axis.tickInterval < minTickIntervalOption) { axis.tickInterval = minTickIntervalOption; } // for linear axes, get magnitude and normalize the interval if (!isDatetimeAxis && !isLog) { // linear if (!tickIntervalOption) { axis.tickInterval = normalizeTickInterval( axis.tickInterval, null, getMagnitude(axis.tickInterval), // If the tick interval is between 1 and 5 and the axis max is in the order of // thousands, chances are we are dealing with years. Don't allow decimals. #3363. pick(options.allowDecimals, !(axis.tickInterval > 1 && axis.tickInterval < 5 && axis.max > 1000 && axis.max < 9999)) ); } } // get minorTickInterval axis.minorTickInterval = options.minorTickInterval === 'auto' && axis.tickInterval ? axis.tickInterval / 5 : options.minorTickInterval; // find the tick positions axis.tickPositions = tickPositions = options.tickPositions ? [].concat(options.tickPositions) : // Work on a copy (#1565) (tickPositioner && tickPositioner.apply(axis, [axis.min, axis.max])); if (!tickPositions) { // Too many ticks if (!axis.ordinalPositions && (axis.max - axis.min) / axis.tickInterval > mathMax(2 * axis.len, 200)) { error(19, true); } if (isDatetimeAxis) { tickPositions = axis.getTimeTicks( axis.normalizeTimeTickInterval(axis.tickInterval, options.units), axis.min, axis.max, options.startOfWeek, axis.ordinalPositions, axis.closestPointRange, true ); } else if (isLog) { tickPositions = axis.getLogTickPositions(axis.tickInterval, axis.min, axis.max); } else { tickPositions = axis.getLinearTickPositions(axis.tickInterval, axis.min, axis.max); } if (keepTwoTicksOnly) { tickPositions.splice(1, tickPositions.length - 2); } axis.tickPositions = tickPositions; } if (!isLinked) { // reset min/max or remove extremes based on start/end on tick var roundedMin = tickPositions[0], roundedMax = tickPositions[tickPositions.length - 1], minPointOffset = axis.minPointOffset || 0, singlePad; if (startOnTick) { axis.min = roundedMin; } else if (axis.min - minPointOffset > roundedMin) { tickPositions.shift(); } if (endOnTick) { axis.max = roundedMax; } else if (axis.max + minPointOffset < roundedMax) { tickPositions.pop(); } // If no tick are left, set one tick in the middle (#3195) if (tickPositions.length === 0 && defined(roundedMin)) { tickPositions.push((roundedMax + roundedMin) / 2); } // When there is only one point, or all points have the same value on this axis, then min // and max are equal and tickPositions.length is 0 or 1. In this case, add some padding // in order to center the point, but leave it with one tick. #1337. if (tickPositions.length === 1) { singlePad = mathAbs(axis.max) > 10e12 ? 1 : 0.001; // The lowest possible number to avoid extra padding on columns (#2619, #2846) axis.min -= singlePad; axis.max += singlePad; } } }, /** * Set the max ticks of either the x and y axis collection */ setMaxTicks: function () { var chart = this.chart, maxTicks = chart.maxTicks || {}, tickPositions = this.tickPositions, key = this._maxTicksKey = [this.coll, this.pos, this.len].join('-'); if (!this.isLinked && !this.isDatetimeAxis && tickPositions && tickPositions.length > (maxTicks[key] || 0) && this.options.alignTicks !== false) { maxTicks[key] = tickPositions.length; } chart.maxTicks = maxTicks; }, /** * When using multiple axes, adjust the number of ticks to match the highest * number of ticks in that group */ adjustTickAmount: function () { var axis = this, chart = axis.chart, key = axis._maxTicksKey, tickPositions = axis.tickPositions, maxTicks = chart.maxTicks; if (maxTicks && maxTicks[key] && !axis.isDatetimeAxis && !axis.categories && !axis.isLinked && axis.options.alignTicks !== false && this.min !== UNDEFINED) { var oldTickAmount = axis.tickAmount, calculatedTickAmount = tickPositions.length, tickAmount; // set the axis-level tickAmount to use below axis.tickAmount = tickAmount = maxTicks[key]; if (calculatedTickAmount < tickAmount) { while (tickPositions.length < tickAmount) { tickPositions.push(correctFloat( tickPositions[tickPositions.length - 1] + axis.tickInterval )); } axis.transA *= (calculatedTickAmount - 1) / (tickAmount - 1); axis.max = tickPositions[tickPositions.length - 1]; } if (defined(oldTickAmount) && tickAmount !== oldTickAmount) { axis.isDirty = true; } } }, /** * Set the scale based on data min and max, user set min and max or options * */ setScale: function () { var axis = this, stacks = axis.stacks, type, i, isDirtyData, isDirtyAxisLength; axis.oldMin = axis.min; axis.oldMax = axis.max; axis.oldAxisLength = axis.len; // set the new axisLength axis.setAxisSize(); //axisLength = horiz ? axisWidth : axisHeight; isDirtyAxisLength = axis.len !== axis.oldAxisLength; // is there new data? each(axis.series, function (series) { if (series.isDirtyData || series.isDirty || series.xAxis.isDirty) { // when x axis is dirty, we need new data extremes for y as well isDirtyData = true; } }); // do we really need to go through all this? if (isDirtyAxisLength || isDirtyData || axis.isLinked || axis.forceRedraw || axis.userMin !== axis.oldUserMin || axis.userMax !== axis.oldUserMax) { // reset stacks if (!axis.isXAxis) { for (type in stacks) { for (i in stacks[type]) { stacks[type][i].total = null; stacks[type][i].cum = 0; } } } axis.forceRedraw = false; // get data extremes if needed axis.getSeriesExtremes(); // get fixed positions based on tickInterval axis.setTickPositions(); // record old values to decide whether a rescale is necessary later on (#540) axis.oldUserMin = axis.userMin; axis.oldUserMax = axis.userMax; // Mark as dirty if it is not already set to dirty and extremes have changed. #595. if (!axis.isDirty) { axis.isDirty = isDirtyAxisLength || axis.min !== axis.oldMin || axis.max !== axis.oldMax; } } else if (!axis.isXAxis) { if (axis.oldStacks) { stacks = axis.stacks = axis.oldStacks; } // reset stacks for (type in stacks) { for (i in stacks[type]) { stacks[type][i].cum = stacks[type][i].total; } } } // Set the maximum tick amount axis.setMaxTicks(); }, /** * Set the extremes and optionally redraw * @param {Number} newMin * @param {Number} newMax * @param {Boolean} redraw * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration * @param {Object} eventArguments * */ setExtremes: function (newMin, newMax, redraw, animation, eventArguments) { var axis = this, chart = axis.chart; redraw = pick(redraw, true); // defaults to true // Extend the arguments with min and max eventArguments = extend(eventArguments, { min: newMin, max: newMax }); // Fire the event fireEvent(axis, 'setExtremes', eventArguments, function () { // the default event handler axis.userMin = newMin; axis.userMax = newMax; axis.eventArgs = eventArguments; // Mark for running afterSetExtremes axis.isDirtyExtremes = true; // redraw if (redraw) { chart.redraw(animation); } }); }, /** * Overridable method for zooming chart. Pulled out in a separate method to allow overriding * in stock charts. */ zoom: function (newMin, newMax) { var dataMin = this.dataMin, dataMax = this.dataMax, options = this.options; // Prevent pinch zooming out of range. Check for defined is for #1946. #1734. if (!this.allowZoomOutside) { if (defined(dataMin) && newMin <= mathMin(dataMin, pick(options.min, dataMin))) { newMin = UNDEFINED; } if (defined(dataMax) && newMax >= mathMax(dataMax, pick(options.max, dataMax))) { newMax = UNDEFINED; } } // In full view, displaying the reset zoom button is not required this.displayBtn = newMin !== UNDEFINED || newMax !== UNDEFINED; // Do it this.setExtremes( newMin, newMax, false, UNDEFINED, { trigger: 'zoom' } ); return true; }, /** * Update the axis metrics */ setAxisSize: function () { var chart = this.chart, options = this.options, offsetLeft = options.offsetLeft || 0, offsetRight = options.offsetRight || 0, horiz = this.horiz, width = pick(options.width, chart.plotWidth - offsetLeft + offsetRight), height = pick(options.height, chart.plotHeight), top = pick(options.top, chart.plotTop), left = pick(options.left, chart.plotLeft + offsetLeft), percentRegex = /%$/; // Check for percentage based input values if (percentRegex.test(height)) { height = parseInt(height, 10) / 100 * chart.plotHeight; } if (percentRegex.test(top)) { top = parseInt(top, 10) / 100 * chart.plotHeight + chart.plotTop; } // Expose basic values to use in Series object and navigator this.left = left; this.top = top; this.width = width; this.height = height; this.bottom = chart.chartHeight - height - top; this.right = chart.chartWidth - width - left; // Direction agnostic properties this.len = mathMax(horiz ? width : height, 0); // mathMax fixes #905 this.pos = horiz ? left : top; // distance from SVG origin }, /** * Get the actual axis extremes */ getExtremes: function () { var axis = this, isLog = axis.isLog; return { min: isLog ? correctFloat(lin2log(axis.min)) : axis.min, max: isLog ? correctFloat(lin2log(axis.max)) : axis.max, dataMin: axis.dataMin, dataMax: axis.dataMax, userMin: axis.userMin, userMax: axis.userMax }; }, /** * Get the zero plane either based on zero or on the min or max value. * Used in bar and area plots */ getThreshold: function (threshold) { var axis = this, isLog = axis.isLog; var realMin = isLog ? lin2log(axis.min) : axis.min, realMax = isLog ? lin2log(axis.max) : axis.max; if (realMin > threshold || threshold === null) { threshold = realMin; } else if (realMax < threshold) { threshold = realMax; } return axis.translate(threshold, 0, 1, 0, 1); }, /** * Compute auto alignment for the axis label based on which side the axis is on * and the given rotation for the label */ autoLabelAlign: function (rotation) { var ret, angle = (pick(rotation, 0) - (this.side * 90) + 720) % 360; if (angle > 15 && angle < 165) { ret = 'right'; } else if (angle > 195 && angle < 345) { ret = 'left'; } else { ret = 'center'; } return ret; }, /** * Render the tick labels to a preliminary position to get their sizes */ getOffset: function () { var axis = this, chart = axis.chart, renderer = chart.renderer, options = axis.options, tickPositions = axis.tickPositions, ticks = axis.ticks, horiz = axis.horiz, side = axis.side, invertedSide = chart.inverted ? [1, 0, 3, 2][side] : side, hasData, showAxis, titleOffset = 0, titleOffsetOption, titleMargin = 0, axisTitleOptions = options.title, labelOptions = options.labels, labelOffset = 0, // reset labelOffsetPadded, axisOffset = chart.axisOffset, clipOffset = chart.clipOffset, directionFactor = [-1, 1, 1, -1][side], n, i, autoStaggerLines = 1, maxStaggerLines = pick(labelOptions.maxStaggerLines, 5), sortedPositions, lastRight, overlap, pos, bBox, x, w, lineNo, lineHeightCorrection; // For reuse in Axis.render axis.hasData = hasData = (axis.hasVisibleSeries || (defined(axis.min) && defined(axis.max) && !!tickPositions)); axis.showAxis = showAxis = hasData || pick(options.showEmpty, true); // Set/reset staggerLines axis.staggerLines = axis.horiz && labelOptions.staggerLines; // Create the axisGroup and gridGroup elements on first iteration if (!axis.axisGroup) { axis.gridGroup = renderer.g('grid') .attr({ zIndex: options.gridZIndex || 1 }) .add(); axis.axisGroup = renderer.g('axis') .attr({ zIndex: options.zIndex || 2 }) .add(); axis.labelGroup = renderer.g('axis-labels') .attr({ zIndex: labelOptions.zIndex || 7 }) .addClass(PREFIX + axis.coll.toLowerCase() + '-labels') .add(); } if (hasData || axis.isLinked) { // Set the explicit or automatic label alignment axis.labelAlign = pick(labelOptions.align || axis.autoLabelAlign(labelOptions.rotation)); // Generate ticks each(tickPositions, function (pos) { if (!ticks[pos]) { ticks[pos] = new Tick(axis, pos); } else { ticks[pos].addLabel(); // update labels depending on tick interval } }); // Handle automatic stagger lines if (axis.horiz && !axis.staggerLines && maxStaggerLines && !labelOptions.rotation) { sortedPositions = axis.reversed ? [].concat(tickPositions).reverse() : tickPositions; while (autoStaggerLines < maxStaggerLines) { lastRight = []; overlap = false; for (i = 0; i < sortedPositions.length; i++) { pos = sortedPositions[i]; bBox = ticks[pos].label && ticks[pos].label.getBBox(); w = bBox ? bBox.width : 0; lineNo = i % autoStaggerLines; if (w) { x = axis.translate(pos); // don't handle log if (lastRight[lineNo] !== UNDEFINED && x < lastRight[lineNo]) { overlap = true; } lastRight[lineNo] = x + w; } } if (overlap) { autoStaggerLines++; } else { break; } } if (autoStaggerLines > 1) { axis.staggerLines = autoStaggerLines; } } each(tickPositions, function (pos) { // left side must be align: right and right side must have align: left for labels if (side === 0 || side === 2 || { 1: 'left', 3: 'right' }[side] === axis.labelAlign) { // get the highest offset labelOffset = mathMax( ticks[pos].getLabelSize(), labelOffset ); } }); if (axis.staggerLines) { labelOffset *= axis.staggerLines; axis.labelOffset = labelOffset; } } else { // doesn't have data for (n in ticks) { ticks[n].destroy(); delete ticks[n]; } } if (axisTitleOptions && axisTitleOptions.text && axisTitleOptions.enabled !== false) { if (!axis.axisTitle) { axis.axisTitle = renderer.text( axisTitleOptions.text, 0, 0, axisTitleOptions.useHTML ) .attr({ zIndex: 7, rotation: axisTitleOptions.rotation || 0, align: axisTitleOptions.textAlign || { low: 'left', middle: 'center', high: 'right' }[axisTitleOptions.align] }) .addClass(PREFIX + this.coll.toLowerCase() + '-title') .css(axisTitleOptions.style) .add(axis.axisGroup); axis.axisTitle.isNew = true; } if (showAxis) { titleOffset = axis.axisTitle.getBBox()[horiz ? 'height' : 'width']; titleOffsetOption = axisTitleOptions.offset; titleMargin = defined(titleOffsetOption) ? 0 : pick(axisTitleOptions.margin, horiz ? 5 : 10); } // hide or show the title depending on whether showEmpty is set axis.axisTitle[showAxis ? 'show' : 'hide'](); } // handle automatic or user set offset axis.offset = directionFactor * pick(options.offset, axisOffset[side]); lineHeightCorrection = side === 2 ? axis.tickBaseline : 0; labelOffsetPadded = labelOffset + titleMargin + (labelOffset && (directionFactor * (horiz ? pick(labelOptions.y, axis.tickBaseline + 8) : labelOptions.x) - lineHeightCorrection)); axis.axisTitleMargin = pick(titleOffsetOption, labelOffsetPadded); axisOffset[side] = mathMax( axisOffset[side], axis.axisTitleMargin + titleOffset + directionFactor * axis.offset, labelOffsetPadded // #3027 ); clipOffset[invertedSide] = mathMax(clipOffset[invertedSide], mathFloor(options.lineWidth / 2) * 2); }, /** * Get the path for the axis line */ getLinePath: function (lineWidth) { var chart = this.chart, opposite = this.opposite, offset = this.offset, horiz = this.horiz, lineLeft = this.left + (opposite ? this.width : 0) + offset, lineTop = chart.chartHeight - this.bottom - (opposite ? this.height : 0) + offset; if (opposite) { lineWidth *= -1; // crispify the other way - #1480, #1687 } return chart.renderer.crispLine([ M, horiz ? this.left : lineLeft, horiz ? lineTop : this.top, L, horiz ? chart.chartWidth - this.right : lineLeft, horiz ? lineTop : chart.chartHeight - this.bottom ], lineWidth); }, /** * Position the title */ getTitlePosition: function () { // compute anchor points for each of the title align options var horiz = this.horiz, axisLeft = this.left, axisTop = this.top, axisLength = this.len, axisTitleOptions = this.options.title, margin = horiz ? axisLeft : axisTop, opposite = this.opposite, offset = this.offset, fontSize = pInt(axisTitleOptions.style.fontSize || 12), // the position in the length direction of the axis alongAxis = { low: margin + (horiz ? 0 : axisLength), middle: margin + axisLength / 2, high: margin + (horiz ? axisLength : 0) }[axisTitleOptions.align], // the position in the perpendicular direction of the axis offAxis = (horiz ? axisTop + this.height : axisLeft) + (horiz ? 1 : -1) * // horizontal axis reverses the margin (opposite ? -1 : 1) * // so does opposite axes this.axisTitleMargin + (this.side === 2 ? fontSize : 0); return { x: horiz ? alongAxis : offAxis + (opposite ? this.width : 0) + offset + (axisTitleOptions.x || 0), // x y: horiz ? offAxis - (opposite ? this.height : 0) + offset : alongAxis + (axisTitleOptions.y || 0) // y }; }, /** * Render the axis */ render: function () { var axis = this, horiz = axis.horiz, reversed = axis.reversed, chart = axis.chart, renderer = chart.renderer, options = axis.options, isLog = axis.isLog, isLinked = axis.isLinked, tickPositions = axis.tickPositions, sortedPositions, axisTitle = axis.axisTitle, ticks = axis.ticks, minorTicks = axis.minorTicks, alternateBands = axis.alternateBands, stackLabelOptions = options.stackLabels, alternateGridColor = options.alternateGridColor, tickmarkOffset = axis.tickmarkOffset, lineWidth = options.lineWidth, linePath, hasRendered = chart.hasRendered, slideInTicks = hasRendered && defined(axis.oldMin) && !isNaN(axis.oldMin), hasData = axis.hasData, showAxis = axis.showAxis, from, overflow = options.labels.overflow, justifyLabels = axis.justifyLabels = horiz && overflow !== false, to; // Reset axis.labelEdge.length = 0; axis.justifyToPlot = overflow === 'justify'; // Mark all elements inActive before we go over and mark the active ones each([ticks, minorTicks, alternateBands], function (coll) { var pos; for (pos in coll) { coll[pos].isActive = false; } }); // If the series has data draw the ticks. Else only the line and title if (hasData || isLinked) { // minor ticks if (axis.minorTickInterval && !axis.categories) { each(axis.getMinorTickPositions(), function (pos) { if (!minorTicks[pos]) { minorTicks[pos] = new Tick(axis, pos, 'minor'); } // render new ticks in old position if (slideInTicks && minorTicks[pos].isNew) { minorTicks[pos].render(null, true); } minorTicks[pos].render(null, false, 1); }); } // Major ticks. Pull out the first item and render it last so that // we can get the position of the neighbour label. #808. if (tickPositions.length) { // #1300 sortedPositions = tickPositions.slice(); if ((horiz && reversed) || (!horiz && !reversed)) { sortedPositions.reverse(); } if (justifyLabels) { sortedPositions = sortedPositions.slice(1).concat([sortedPositions[0]]); } each(sortedPositions, function (pos, i) { // Reorganize the indices if (justifyLabels) { i = (i === sortedPositions.length - 1) ? 0 : i + 1; } // linked axes need an extra check to find out if if (!isLinked || (pos >= axis.min && pos <= axis.max)) { if (!ticks[pos]) { ticks[pos] = new Tick(axis, pos); } // render new ticks in old position if (slideInTicks && ticks[pos].isNew) { ticks[pos].render(i, true, 0.1); } ticks[pos].render(i); } }); // In a categorized axis, the tick marks are displayed between labels. So // we need to add a tick mark and grid line at the left edge of the X axis. if (tickmarkOffset && axis.min === 0) { if (!ticks[-1]) { ticks[-1] = new Tick(axis, -1, null, true); } ticks[-1].render(-1); } } // alternate grid color if (alternateGridColor) { each(tickPositions, function (pos, i) { if (i % 2 === 0 && pos < axis.max) { if (!alternateBands[pos]) { alternateBands[pos] = new Highcharts.PlotLineOrBand(axis); } from = pos + tickmarkOffset; // #949 to = tickPositions[i + 1] !== UNDEFINED ? tickPositions[i + 1] + tickmarkOffset : axis.max; alternateBands[pos].options = { from: isLog ? lin2log(from) : from, to: isLog ? lin2log(to) : to, color: alternateGridColor }; alternateBands[pos].render(); alternateBands[pos].isActive = true; } }); } // custom plot lines and bands if (!axis._addedPlotLB) { // only first time each((options.plotLines || []).concat(options.plotBands || []), function (plotLineOptions) { axis.addPlotBandOrLine(plotLineOptions); }); axis._addedPlotLB = true; } } // end if hasData // Remove inactive ticks each([ticks, minorTicks, alternateBands], function (coll) { var pos, i, forDestruction = [], delay = globalAnimation ? globalAnimation.duration || 500 : 0, destroyInactiveItems = function () { i = forDestruction.length; while (i--) { // When resizing rapidly, the same items may be destroyed in different timeouts, // or the may be reactivated if (coll[forDestruction[i]] && !coll[forDestruction[i]].isActive) { coll[forDestruction[i]].destroy(); delete coll[forDestruction[i]]; } } }; for (pos in coll) { if (!coll[pos].isActive) { // Render to zero opacity coll[pos].render(pos, false, 0); coll[pos].isActive = false; forDestruction.push(pos); } } // When the objects are finished fading out, destroy them if (coll === alternateBands || !chart.hasRendered || !delay) { destroyInactiveItems(); } else if (delay) { setTimeout(destroyInactiveItems, delay); } }); // Static items. As the axis group is cleared on subsequent calls // to render, these items are added outside the group. // axis line if (lineWidth) { linePath = axis.getLinePath(lineWidth); if (!axis.axisLine) { axis.axisLine = renderer.path(linePath) .attr({ stroke: options.lineColor, 'stroke-width': lineWidth, zIndex: 7 }) .add(axis.axisGroup); } else { axis.axisLine.animate({ d: linePath }); } // show or hide the line depending on options.showEmpty axis.axisLine[showAxis ? 'show' : 'hide'](); } if (axisTitle && showAxis) { axisTitle[axisTitle.isNew ? 'attr' : 'animate']( axis.getTitlePosition() ); axisTitle.isNew = false; } // Stacked totals: if (stackLabelOptions && stackLabelOptions.enabled) { axis.renderStackTotals(); } // End stacked totals axis.isDirty = false; }, /** * Redraw the axis to reflect changes in the data or axis extremes */ redraw: function () { // render the axis this.render(); // move plot lines and bands each(this.plotLinesAndBands, function (plotLine) { plotLine.render(); }); // mark associated series as dirty and ready for redraw each(this.series, function (series) { series.isDirty = true; }); }, /** * Destroys an Axis instance. */ destroy: function (keepEvents) { var axis = this, stacks = axis.stacks, stackKey, plotLinesAndBands = axis.plotLinesAndBands, i; // Remove the events if (!keepEvents) { removeEvent(axis); } // Destroy each stack total for (stackKey in stacks) { destroyObjectProperties(stacks[stackKey]); stacks[stackKey] = null; } // Destroy collections each([axis.ticks, axis.minorTicks, axis.alternateBands], function (coll) { destroyObjectProperties(coll); }); i = plotLinesAndBands.length; while (i--) { // #1975 plotLinesAndBands[i].destroy(); } // Destroy local variables each(['stackTotalGroup', 'axisLine', 'axisTitle', 'axisGroup', 'cross', 'gridGroup', 'labelGroup'], function (prop) { if (axis[prop]) { axis[prop] = axis[prop].destroy(); } }); // Destroy crosshair if (this.cross) { this.cross.destroy(); } }, /** * Draw the crosshair */ drawCrosshair: function (e, point) { if (!this.crosshair) { return; }// Do not draw crosshairs if you don't have too. if ((defined(point) || !pick(this.crosshair.snap, true)) === false) { this.hideCrosshair(); return; } var path, options = this.crosshair, animation = options.animation, pos; // Get the path if (!pick(options.snap, true)) { pos = (this.horiz ? e.chartX - this.pos : this.len - e.chartY + this.pos); } else if (defined(point)) { /*jslint eqeq: true*/ pos = (this.chart.inverted != this.horiz) ? point.plotX : this.len - point.plotY; /*jslint eqeq: false*/ } if (this.isRadial) { path = this.getPlotLinePath(this.isXAxis ? point.x : pick(point.stackY, point.y)); } else { path = this.getPlotLinePath(null, null, null, null, pos); } if (path === null) { this.hideCrosshair(); return; } // Draw the cross if (this.cross) { this.cross .attr({ visibility: VISIBLE })[animation ? 'animate' : 'attr']({ d: path }, animation); } else { var attribs = { 'stroke-width': options.width || 1, stroke: options.color || '#C0C0C0', zIndex: options.zIndex || 2 }; if (options.dashStyle) { attribs.dashstyle = options.dashStyle; } this.cross = this.chart.renderer.path(path).attr(attribs).add(); } }, /** * Hide the crosshair. */ hideCrosshair: function () { if (this.cross) { this.cross.hide(); } } }; // end Axis extend(Axis.prototype, AxisPlotLineOrBandExtension); /** * Methods defined on the Axis prototype */ /** * Set the tick positions of a logarithmic axis */ Axis.prototype.getLogTickPositions = function (interval, min, max, minor) { var axis = this, options = axis.options, axisLength = axis.len, // Since we use this method for both major and minor ticks, // use a local variable and return the result positions = []; // Reset if (!minor) { axis._minorAutoInterval = null; } // First case: All ticks fall on whole logarithms: 1, 10, 100 etc. if (interval >= 0.5) { interval = mathRound(interval); positions = axis.getLinearTickPositions(interval, min, max); // Second case: We need intermediary ticks. For example // 1, 2, 4, 6, 8, 10, 20, 40 etc. } else if (interval >= 0.08) { var roundedMin = mathFloor(min), intermediate, i, j, len, pos, lastPos, break2; if (interval > 0.3) { intermediate = [1, 2, 4]; } else if (interval > 0.15) { // 0.2 equals five minor ticks per 1, 10, 100 etc intermediate = [1, 2, 4, 6, 8]; } else { // 0.1 equals ten minor ticks per 1, 10, 100 etc intermediate = [1, 2, 3, 4, 5, 6, 7, 8, 9]; } for (i = roundedMin; i < max + 1 && !break2; i++) { len = intermediate.length; for (j = 0; j < len && !break2; j++) { pos = log2lin(lin2log(i) * intermediate[j]); if (pos > min && (!minor || lastPos <= max) && lastPos !== UNDEFINED) { // #1670, lastPos is #3113 positions.push(lastPos); } if (lastPos > max) { break2 = true; } lastPos = pos; } } // Third case: We are so deep in between whole logarithmic values that // we might as well handle the tick positions like a linear axis. For // example 1.01, 1.02, 1.03, 1.04. } else { var realMin = lin2log(min), realMax = lin2log(max), tickIntervalOption = options[minor ? 'minorTickInterval' : 'tickInterval'], filteredTickIntervalOption = tickIntervalOption === 'auto' ? null : tickIntervalOption, tickPixelIntervalOption = options.tickPixelInterval / (minor ? 5 : 1), totalPixelLength = minor ? axisLength / axis.tickPositions.length : axisLength; interval = pick( filteredTickIntervalOption, axis._minorAutoInterval, (realMax - realMin) * tickPixelIntervalOption / (totalPixelLength || 1) ); interval = normalizeTickInterval( interval, null, getMagnitude(interval) ); positions = map(axis.getLinearTickPositions( interval, realMin, realMax ), log2lin); if (!minor) { axis._minorAutoInterval = interval / 5; } } // Set the axis-level tickInterval variable if (!minor) { axis.tickInterval = interval; } return positions; };/** * The tooltip object * @param {Object} chart The chart instance * @param {Object} options Tooltip options */ var Tooltip = Highcharts.Tooltip = function () { this.init.apply(this, arguments); }; Tooltip.prototype = { init: function (chart, options) { var borderWidth = options.borderWidth, style = options.style, padding = pInt(style.padding); // Save the chart and options this.chart = chart; this.options = options; // Keep track of the current series //this.currentSeries = UNDEFINED; // List of crosshairs this.crosshairs = []; // Current values of x and y when animating this.now = { x: 0, y: 0 }; // The tooltip is initially hidden this.isHidden = true; // create the label this.label = chart.renderer.label('', 0, 0, options.shape || 'callout', null, null, options.useHTML, null, 'tooltip') .attr({ padding: padding, fill: options.backgroundColor, 'stroke-width': borderWidth, r: options.borderRadius, zIndex: 8 }) .css(style) .css({ padding: 0 }) // Remove it from VML, the padding is applied as an attribute instead (#1117) .add() .attr({ y: -9999 }); // #2301, #2657 // When using canVG the shadow shows up as a gray circle // even if the tooltip is hidden. if (!useCanVG) { this.label.shadow(options.shadow); } // Public property for getting the shared state. this.shared = options.shared; }, /** * Destroy the tooltip and its elements. */ destroy: function () { // Destroy and clear local variables if (this.label) { this.label = this.label.destroy(); } clearTimeout(this.hideTimer); clearTimeout(this.tooltipTimeout); }, /** * Provide a soft movement for the tooltip * * @param {Number} x * @param {Number} y * @private */ move: function (x, y, anchorX, anchorY) { var tooltip = this, now = tooltip.now, animate = tooltip.options.animation !== false && !tooltip.isHidden && // When we get close to the target position, abort animation and land on the right place (#3056) (mathAbs(x - now.x) > 1 || mathAbs(y - now.y) > 1), skipAnchor = tooltip.followPointer || tooltip.len > 1; // Get intermediate values for animation extend(now, { x: animate ? (2 * now.x + x) / 3 : x, y: animate ? (now.y + y) / 2 : y, anchorX: skipAnchor ? UNDEFINED : animate ? (2 * now.anchorX + anchorX) / 3 : anchorX, anchorY: skipAnchor ? UNDEFINED : animate ? (now.anchorY + anchorY) / 2 : anchorY }); // Move to the intermediate value tooltip.label.attr(now); // Run on next tick of the mouse tracker if (animate) { // Never allow two timeouts clearTimeout(this.tooltipTimeout); // Set the fixed interval ticking for the smooth tooltip this.tooltipTimeout = setTimeout(function () { // The interval function may still be running during destroy, so check that the chart is really there before calling. if (tooltip) { tooltip.move(x, y, anchorX, anchorY); } }, 32); } }, /** * Hide the tooltip */ hide: function (delay) { var tooltip = this, hoverPoints; clearTimeout(this.hideTimer); // disallow duplicate timers (#1728, #1766) if (!this.isHidden) { hoverPoints = this.chart.hoverPoints; this.hideTimer = setTimeout(function () { tooltip.label.fadeOut(); tooltip.isHidden = true; }, pick(delay, this.options.hideDelay, 500)); // hide previous hoverPoints and set new if (hoverPoints) { each(hoverPoints, function (point) { point.setState(); }); } this.chart.hoverPoints = null; } }, /** * Extendable method to get the anchor position of the tooltip * from a point or set of points */ getAnchor: function (points, mouseEvent) { var ret, chart = this.chart, inverted = chart.inverted, plotTop = chart.plotTop, plotX = 0, plotY = 0, yAxis; points = splat(points); // Pie uses a special tooltipPos ret = points[0].tooltipPos; // When tooltip follows mouse, relate the position to the mouse if (this.followPointer && mouseEvent) { if (mouseEvent.chartX === UNDEFINED) { mouseEvent = chart.pointer.normalize(mouseEvent); } ret = [ mouseEvent.chartX - chart.plotLeft, mouseEvent.chartY - plotTop ]; } // When shared, use the average position if (!ret) { each(points, function (point) { yAxis = point.series.yAxis; plotX += point.plotX; plotY += (point.plotLow ? (point.plotLow + point.plotHigh) / 2 : point.plotY) + (!inverted && yAxis ? yAxis.top - plotTop : 0); // #1151 }); plotX /= points.length; plotY /= points.length; ret = [ inverted ? chart.plotWidth - plotY : plotX, this.shared && !inverted && points.length > 1 && mouseEvent ? mouseEvent.chartY - plotTop : // place shared tooltip next to the mouse (#424) inverted ? chart.plotHeight - plotX : plotY ]; } return map(ret, mathRound); }, /** * Place the tooltip in a chart without spilling over * and not covering the point it self. */ getPosition: function (boxWidth, boxHeight, point) { var chart = this.chart, distance = this.distance, ret = {}, swapped, first = ['y', chart.chartHeight, boxHeight, point.plotY + chart.plotTop], second = ['x', chart.chartWidth, boxWidth, point.plotX + chart.plotLeft], // The far side is right or bottom preferFarSide = point.ttBelow || (chart.inverted && !point.negative) || (!chart.inverted && point.negative), /** * Handle the preferred dimension. When the preferred dimension is tooltip * on top or bottom of the point, it will look for space there. */ firstDimension = function (dim, outerSize, innerSize, point) { var roomLeft = innerSize < point - distance, roomRight = point + distance + innerSize < outerSize, alignedLeft = point - distance - innerSize, alignedRight = point + distance; if (preferFarSide && roomRight) { ret[dim] = alignedRight; } else if (!preferFarSide && roomLeft) { ret[dim] = alignedLeft; } else if (roomLeft) { ret[dim] = alignedLeft; } else if (roomRight) { ret[dim] = alignedRight; } else { return false; } }, /** * Handle the secondary dimension. If the preferred dimension is tooltip * on top or bottom of the point, the second dimension is to align the tooltip * above the point, trying to align center but allowing left or right * align within the chart box. */ secondDimension = function (dim, outerSize, innerSize, point) { // Too close to the edge, return false and swap dimensions if (point < distance || point > outerSize - distance) { return false; // Align left/top } else if (point < innerSize / 2) { ret[dim] = 1; // Align right/bottom } else if (point > outerSize - innerSize / 2) { ret[dim] = outerSize - innerSize - 2; // Align center } else { ret[dim] = point - innerSize / 2; } }, /** * Swap the dimensions */ swap = function (count) { var temp = first; first = second; second = temp; swapped = count; }, run = function () { if (firstDimension.apply(0, first) !== false) { if (secondDimension.apply(0, second) === false && !swapped) { swap(true); run(); } } else if (!swapped) { swap(true); run(); } else { ret.x = ret.y = 0; } }; // Under these conditions, prefer the tooltip on the side of the point if (chart.inverted || this.len > 1) { swap(); } run(); return ret; }, /** * In case no user defined formatter is given, this will be used. Note that the context * here is an object holding point, series, x, y etc. */ defaultFormatter: function (tooltip) { var items = this.points || splat(this), series = items[0].series, s; // build the header s = [tooltip.tooltipHeaderFormatter(items[0])]; // build the values each(items, function (item) { series = item.series; s.push((series.tooltipFormatter && series.tooltipFormatter(item)) || item.point.tooltipFormatter(series.tooltipOptions.pointFormat)); }); // footer s.push(tooltip.options.footerFormat || ''); return s.join(''); }, /** * Refresh the tooltip's text and position. * @param {Object} point */ refresh: function (point, mouseEvent) { var tooltip = this, chart = tooltip.chart, label = tooltip.label, options = tooltip.options, x, y, anchor, textConfig = {}, text, pointConfig = [], formatter = options.formatter || tooltip.defaultFormatter, hoverPoints = chart.hoverPoints, borderColor, shared = tooltip.shared, currentSeries; clearTimeout(this.hideTimer); // get the reference point coordinates (pie charts use tooltipPos) tooltip.followPointer = splat(point)[0].series.tooltipOptions.followPointer; anchor = tooltip.getAnchor(point, mouseEvent); x = anchor[0]; y = anchor[1]; // shared tooltip, array is sent over if (shared && !(point.series && point.series.noSharedTooltip)) { // hide previous hoverPoints and set new chart.hoverPoints = point; if (hoverPoints) { each(hoverPoints, function (point) { point.setState(); }); } each(point, function (item) { item.setState(HOVER_STATE); pointConfig.push(item.getLabelConfig()); }); textConfig = { x: point[0].category, y: point[0].y }; textConfig.points = pointConfig; this.len = pointConfig.length; point = point[0]; // single point tooltip } else { textConfig = point.getLabelConfig(); } text = formatter.call(textConfig, tooltip); // register the current series currentSeries = point.series; this.distance = pick(currentSeries.tooltipOptions.distance, 16); // update the inner HTML if (text === false) { this.hide(); } else { // show it if (tooltip.isHidden) { stop(label); label.attr('opacity', 1).show(); } // update text label.attr({ text: text }); // set the stroke color of the box borderColor = options.borderColor || point.color || currentSeries.color || '#606060'; label.attr({ stroke: borderColor }); tooltip.updatePosition({ plotX: x, plotY: y, negative: point.negative, ttBelow: point.ttBelow }); this.isHidden = false; } fireEvent(chart, 'tooltipRefresh', { text: text, x: x + chart.plotLeft, y: y + chart.plotTop, borderColor: borderColor }); }, /** * Find the new position and perform the move */ updatePosition: function (point) { var chart = this.chart, label = this.label, pos = (this.options.positioner || this.getPosition).call( this, label.width, label.height, point ); // do the move this.move( mathRound(pos.x), mathRound(pos.y), point.plotX + chart.plotLeft, point.plotY + chart.plotTop ); }, /** * Format the header of the tooltip */ tooltipHeaderFormatter: function (point) { var series = point.series, tooltipOptions = series.tooltipOptions, dateTimeLabelFormats = tooltipOptions.dateTimeLabelFormats, xDateFormat = tooltipOptions.xDateFormat, xAxis = series.xAxis, isDateTime = xAxis && xAxis.options.type === 'datetime' && isNumber(point.key), headerFormat = tooltipOptions.headerFormat, closestPointRange = xAxis && xAxis.closestPointRange, n; // Guess the best date format based on the closest point distance (#568) if (isDateTime && !xDateFormat) { if (closestPointRange) { for (n in timeUnits) { if (timeUnits[n] >= closestPointRange || // If the point is placed every day at 23:59, we need to show // the minutes as well. This logic only works for time units less than // a day, since all higher time units are dividable by those. #2637. (timeUnits[n] <= timeUnits.day && point.key % timeUnits[n] > 0)) { xDateFormat = dateTimeLabelFormats[n]; break; } } } else { xDateFormat = dateTimeLabelFormats.day; } xDateFormat = xDateFormat || dateTimeLabelFormats.year; // #2546, 2581 } // Insert the header date format if any if (isDateTime && xDateFormat) { headerFormat = headerFormat.replace('{point.key}', '{point.key:' + xDateFormat + '}'); } return format(headerFormat, { point: point, series: series }); } }; var hoverChartIndex; // Global flag for touch support hasTouch = doc.documentElement.ontouchstart !== UNDEFINED; /** * The mouse tracker object. All methods starting with "on" are primary DOM event handlers. * Subsequent methods should be named differently from what they are doing. * @param {Object} chart The Chart instance * @param {Object} options The root options object */ var Pointer = Highcharts.Pointer = function (chart, options) { this.init(chart, options); }; Pointer.prototype = { /** * Initialize Pointer */ init: function (chart, options) { var chartOptions = options.chart, chartEvents = chartOptions.events, zoomType = useCanVG ? '' : chartOptions.zoomType, inverted = chart.inverted, zoomX, zoomY; // Store references this.options = options; this.chart = chart; // Zoom status this.zoomX = zoomX = /x/.test(zoomType); this.zoomY = zoomY = /y/.test(zoomType); this.zoomHor = (zoomX && !inverted) || (zoomY && inverted); this.zoomVert = (zoomY && !inverted) || (zoomX && inverted); this.hasZoom = zoomX || zoomY; // Do we need to handle click on a touch device? this.runChartClick = chartEvents && !!chartEvents.click; this.pinchDown = []; this.lastValidTouch = {}; if (Highcharts.Tooltip && options.tooltip.enabled) { chart.tooltip = new Tooltip(chart, options.tooltip); this.followTouchMove = options.tooltip.followTouchMove; } this.setDOMEvents(); }, /** * Add crossbrowser support for chartX and chartY * @param {Object} e The event object in standard browsers */ normalize: function (e, chartPosition) { var chartX, chartY, ePos; // common IE normalizing e = e || window.event; // Framework specific normalizing (#1165) e = washMouseEvent(e); // More IE normalizing, needs to go after washMouseEvent if (!e.target) { e.target = e.srcElement; } // iOS (#2757) ePos = e.touches ? (e.touches.length ? e.touches.item(0) : e.changedTouches[0]) : e; // Get mouse position if (!chartPosition) { this.chartPosition = chartPosition = offset(this.chart.container); } // chartX and chartY if (ePos.pageX === UNDEFINED) { // IE < 9. #886. chartX = mathMax(e.x, e.clientX - chartPosition.left); // #2005, #2129: the second case is // for IE10 quirks mode within framesets chartY = e.y; } else { chartX = ePos.pageX - chartPosition.left; chartY = ePos.pageY - chartPosition.top; } return extend(e, { chartX: mathRound(chartX), chartY: mathRound(chartY) }); }, /** * Get the click position in terms of axis values. * * @param {Object} e A pointer event */ getCoordinates: function (e) { var coordinates = { xAxis: [], yAxis: [] }; each(this.chart.axes, function (axis) { coordinates[axis.isXAxis ? 'xAxis' : 'yAxis'].push({ axis: axis, value: axis.toValue(e[axis.horiz ? 'chartX' : 'chartY']) }); }); return coordinates; }, /** * Return the index in the tooltipPoints array, corresponding to pixel position in * the plot area. */ getIndex: function (e) { var chart = this.chart; return chart.inverted ? chart.plotHeight + chart.plotTop - e.chartY : e.chartX - chart.plotLeft; }, /** * With line type charts with a single tracker, get the point closest to the mouse. * Run Point.onMouseOver and display tooltip for the point or points. */ runPointActions: function (e) { var pointer = this, chart = pointer.chart, series = chart.series, tooltip = chart.tooltip, followPointer, point, points, hoverPoint = chart.hoverPoint, hoverSeries = chart.hoverSeries, i, j, distance = chart.chartWidth, index = pointer.getIndex(e), anchor; // shared tooltip if (tooltip && pointer.options.tooltip.shared && !(hoverSeries && hoverSeries.noSharedTooltip)) { points = []; // loop over all series and find the ones with points closest to the mouse i = series.length; for (j = 0; j < i; j++) { if (series[j].visible && series[j].options.enableMouseTracking !== false && !series[j].noSharedTooltip && series[j].singularTooltips !== true && series[j].tooltipPoints.length) { point = series[j].tooltipPoints[index]; if (point && point.series) { // not a dummy point, #1544 point._dist = mathAbs(index - point.clientX); distance = mathMin(distance, point._dist); points.push(point); } } } // remove furthest points i = points.length; while (i--) { if (points[i]._dist > distance) { points.splice(i, 1); } } // refresh the tooltip if necessary if (points.length && (points[0].clientX !== pointer.hoverX)) { tooltip.refresh(points, e); pointer.hoverX = points[0].clientX; } } // Separate tooltip and general mouse events followPointer = hoverSeries && hoverSeries.tooltipOptions.followPointer; if (hoverSeries && hoverSeries.tracker && !followPointer) { // #2584, #2830 // get the point point = hoverSeries.tooltipPoints[index]; // a new point is hovered, refresh the tooltip if (point && point !== hoverPoint) { // trigger the events point.onMouseOver(e); } } else if (tooltip && followPointer && !tooltip.isHidden) { anchor = tooltip.getAnchor([{}], e); tooltip.updatePosition({ plotX: anchor[0], plotY: anchor[1] }); } // Start the event listener to pick up the tooltip if (tooltip && !pointer._onDocumentMouseMove) { pointer._onDocumentMouseMove = function (e) { if (charts[hoverChartIndex]) { charts[hoverChartIndex].pointer.onDocumentMouseMove(e); } }; addEvent(doc, 'mousemove', pointer._onDocumentMouseMove); } // Draw independent crosshairs each(chart.axes, function (axis) { axis.drawCrosshair(e, pick(point, hoverPoint)); }); }, /** * Reset the tracking by hiding the tooltip, the hover series state and the hover point * * @param allowMove {Boolean} Instead of destroying the tooltip altogether, allow moving it if possible */ reset: function (allowMove, delay) { var pointer = this, chart = pointer.chart, hoverSeries = chart.hoverSeries, hoverPoint = chart.hoverPoint, tooltip = chart.tooltip, tooltipPoints = tooltip && tooltip.shared ? chart.hoverPoints : hoverPoint; // Narrow in allowMove allowMove = allowMove && tooltip && tooltipPoints; // Check if the points have moved outside the plot area, #1003 if (allowMove && splat(tooltipPoints)[0].plotX === UNDEFINED) { allowMove = false; } // Just move the tooltip, #349 if (allowMove) { tooltip.refresh(tooltipPoints); if (hoverPoint) { // #2500 hoverPoint.setState(hoverPoint.state, true); } // Full reset } else { if (hoverPoint) { hoverPoint.onMouseOut(); } if (hoverSeries) { hoverSeries.onMouseOut(); } if (tooltip) { tooltip.hide(delay); } if (pointer._onDocumentMouseMove) { removeEvent(doc, 'mousemove', pointer._onDocumentMouseMove); pointer._onDocumentMouseMove = null; } // Remove crosshairs each(chart.axes, function (axis) { axis.hideCrosshair(); }); pointer.hoverX = null; } }, /** * Scale series groups to a certain scale and translation */ scaleGroups: function (attribs, clip) { var chart = this.chart, seriesAttribs; // Scale each series each(chart.series, function (series) { seriesAttribs = attribs || series.getPlotBox(); // #1701 if (series.xAxis && series.xAxis.zoomEnabled) { series.group.attr(seriesAttribs); if (series.markerGroup) { series.markerGroup.attr(seriesAttribs); series.markerGroup.clip(clip ? chart.clipRect : null); } if (series.dataLabelsGroup) { series.dataLabelsGroup.attr(seriesAttribs); } } }); // Clip chart.clipRect.attr(clip || chart.clipBox); }, /** * Start a drag operation */ dragStart: function (e) { var chart = this.chart; // Record the start position chart.mouseIsDown = e.type; chart.cancelClick = false; chart.mouseDownX = this.mouseDownX = e.chartX; chart.mouseDownY = this.mouseDownY = e.chartY; }, /** * Perform a drag operation in response to a mousemove event while the mouse is down */ drag: function (e) { var chart = this.chart, chartOptions = chart.options.chart, chartX = e.chartX, chartY = e.chartY, zoomHor = this.zoomHor, zoomVert = this.zoomVert, plotLeft = chart.plotLeft, plotTop = chart.plotTop, plotWidth = chart.plotWidth, plotHeight = chart.plotHeight, clickedInside, size, mouseDownX = this.mouseDownX, mouseDownY = this.mouseDownY, panKey = chartOptions.panKey && e[chartOptions.panKey + 'Key']; // If the mouse is outside the plot area, adjust to cooordinates // inside to prevent the selection marker from going outside if (chartX < plotLeft) { chartX = plotLeft; } else if (chartX > plotLeft + plotWidth) { chartX = plotLeft + plotWidth; } if (chartY < plotTop) { chartY = plotTop; } else if (chartY > plotTop + plotHeight) { chartY = plotTop + plotHeight; } // determine if the mouse has moved more than 10px this.hasDragged = Math.sqrt( Math.pow(mouseDownX - chartX, 2) + Math.pow(mouseDownY - chartY, 2) ); if (this.hasDragged > 10) { clickedInside = chart.isInsidePlot(mouseDownX - plotLeft, mouseDownY - plotTop); // make a selection if (chart.hasCartesianSeries && (this.zoomX || this.zoomY) && clickedInside && !panKey) { if (!this.selectionMarker) { this.selectionMarker = chart.renderer.rect( plotLeft, plotTop, zoomHor ? 1 : plotWidth, zoomVert ? 1 : plotHeight, 0 ) .attr({ fill: chartOptions.selectionMarkerFill || 'rgba(69,114,167,0.25)', zIndex: 7 }) .add(); } } // adjust the width of the selection marker if (this.selectionMarker && zoomHor) { size = chartX - mouseDownX; this.selectionMarker.attr({ width: mathAbs(size), x: (size > 0 ? 0 : size) + mouseDownX }); } // adjust the height of the selection marker if (this.selectionMarker && zoomVert) { size = chartY - mouseDownY; this.selectionMarker.attr({ height: mathAbs(size), y: (size > 0 ? 0 : size) + mouseDownY }); } // panning if (clickedInside && !this.selectionMarker && chartOptions.panning) { chart.pan(e, chartOptions.panning); } } }, /** * On mouse up or touch end across the entire document, drop the selection. */ drop: function (e) { var chart = this.chart, hasPinched = this.hasPinched; if (this.selectionMarker) { var selectionData = { xAxis: [], yAxis: [], originalEvent: e.originalEvent || e }, selectionBox = this.selectionMarker, selectionLeft = selectionBox.attr ? selectionBox.attr('x') : selectionBox.x, selectionTop = selectionBox.attr ? selectionBox.attr('y') : selectionBox.y, selectionWidth = selectionBox.attr ? selectionBox.attr('width') : selectionBox.width, selectionHeight = selectionBox.attr ? selectionBox.attr('height') : selectionBox.height, runZoom; // a selection has been made if (this.hasDragged || hasPinched) { // record each axis' min and max each(chart.axes, function (axis) { if (axis.zoomEnabled) { var horiz = axis.horiz, minPixelPadding = e.type === 'touchend' ? axis.minPixelPadding: 0, // #1207, #3075 selectionMin = axis.toValue((horiz ? selectionLeft : selectionTop) + minPixelPadding), selectionMax = axis.toValue((horiz ? selectionLeft + selectionWidth : selectionTop + selectionHeight) - minPixelPadding); if (!isNaN(selectionMin) && !isNaN(selectionMax)) { // #859 selectionData[axis.coll].push({ axis: axis, min: mathMin(selectionMin, selectionMax), // for reversed axes, max: mathMax(selectionMin, selectionMax) }); runZoom = true; } } }); if (runZoom) { fireEvent(chart, 'selection', selectionData, function (args) { chart.zoom(extend(args, hasPinched ? { animation: false } : null)); }); } } this.selectionMarker = this.selectionMarker.destroy(); // Reset scaling preview if (hasPinched) { this.scaleGroups(); } } // Reset all if (chart) { // it may be destroyed on mouse up - #877 css(chart.container, { cursor: chart._cursor }); chart.cancelClick = this.hasDragged > 10; // #370 chart.mouseIsDown = this.hasDragged = this.hasPinched = false; this.pinchDown = []; } }, onContainerMouseDown: function (e) { e = this.normalize(e); // issue #295, dragging not always working in Firefox if (e.preventDefault) { e.preventDefault(); } this.dragStart(e); }, onDocumentMouseUp: function (e) { if (charts[hoverChartIndex]) { charts[hoverChartIndex].pointer.drop(e); } }, /** * Special handler for mouse move that will hide the tooltip when the mouse leaves the plotarea. * Issue #149 workaround. The mouseleave event does not always fire. */ onDocumentMouseMove: function (e) { var chart = this.chart, chartPosition = this.chartPosition, hoverSeries = chart.hoverSeries; e = this.normalize(e, chartPosition); // If we're outside, hide the tooltip if (chartPosition && hoverSeries && !this.inClass(e.target, 'highcharts-tracker') && !chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) { this.reset(); } }, /** * When mouse leaves the container, hide the tooltip. */ onContainerMouseLeave: function () { var chart = charts[hoverChartIndex]; if (chart) { chart.pointer.reset(); chart.pointer.chartPosition = null; // also reset the chart position, used in #149 fix } }, // The mousemove, touchmove and touchstart event handler onContainerMouseMove: function (e) { var chart = this.chart; hoverChartIndex = chart.index; e = this.normalize(e); e.returnValue = false; // #2251, #3224 if (chart.mouseIsDown === 'mousedown') { this.drag(e); } // Show the tooltip and run mouse over events (#977) if ((this.inClass(e.target, 'highcharts-tracker') || chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) && !chart.openMenu) { this.runPointActions(e); } }, /** * Utility to detect whether an element has, or has a parent with, a specific * class name. Used on detection of tracker objects and on deciding whether * hovering the tooltip should cause the active series to mouse out. */ inClass: function (element, className) { var elemClassName; while (element) { elemClassName = attr(element, 'class'); if (elemClassName) { if (elemClassName.indexOf(className) !== -1) { return true; } else if (elemClassName.indexOf(PREFIX + 'container') !== -1) { return false; } } element = element.parentNode; } }, onTrackerMouseOut: function (e) { var series = this.chart.hoverSeries, relatedTarget = e.relatedTarget || e.toElement, relatedSeries = relatedTarget && relatedTarget.point && relatedTarget.point.series; // #2499 if (series && !series.options.stickyTracking && !this.inClass(relatedTarget, PREFIX + 'tooltip') && relatedSeries !== series) { series.onMouseOut(); } }, onContainerClick: function (e) { var chart = this.chart, hoverPoint = chart.hoverPoint, plotLeft = chart.plotLeft, plotTop = chart.plotTop; e = this.normalize(e); e.cancelBubble = true; // IE specific if (!chart.cancelClick) { // On tracker click, fire the series and point events. #783, #1583 if (hoverPoint && this.inClass(e.target, PREFIX + 'tracker')) { // the series click event fireEvent(hoverPoint.series, 'click', extend(e, { point: hoverPoint })); // the point click event if (chart.hoverPoint) { // it may be destroyed (#1844) hoverPoint.firePointEvent('click', e); } // When clicking outside a tracker, fire a chart event } else { extend(e, this.getCoordinates(e)); // fire a click event in the chart if (chart.isInsidePlot(e.chartX - plotLeft, e.chartY - plotTop)) { fireEvent(chart, 'click', e); } } } }, /** * Set the JS DOM events on the container and document. This method should contain * a one-to-one assignment between methods and their handlers. Any advanced logic should * be moved to the handler reflecting the event's name. */ setDOMEvents: function () { var pointer = this, container = pointer.chart.container; container.onmousedown = function (e) { pointer.onContainerMouseDown(e); }; container.onmousemove = function (e) { pointer.onContainerMouseMove(e); }; container.onclick = function (e) { pointer.onContainerClick(e); }; addEvent(container, 'mouseleave', pointer.onContainerMouseLeave); if (chartCount === 1) { addEvent(doc, 'mouseup', pointer.onDocumentMouseUp); } if (hasTouch) { container.ontouchstart = function (e) { pointer.onContainerTouchStart(e); }; container.ontouchmove = function (e) { pointer.onContainerTouchMove(e); }; if (chartCount === 1) { addEvent(doc, 'touchend', pointer.onDocumentTouchEnd); } } }, /** * Destroys the Pointer object and disconnects DOM events. */ destroy: function () { var prop; removeEvent(this.chart.container, 'mouseleave', this.onContainerMouseLeave); if (!chartCount) { removeEvent(doc, 'mouseup', this.onDocumentMouseUp); removeEvent(doc, 'touchend', this.onDocumentTouchEnd); } // memory and CPU leak clearInterval(this.tooltipTimeout); for (prop in this) { this[prop] = null; } } }; /* Support for touch devices */ extend(Highcharts.Pointer.prototype, { /** * Run translation operations */ pinchTranslate: function (pinchDown, touches, transform, selectionMarker, clip, lastValidTouch) { if (this.zoomHor || this.pinchHor) { this.pinchTranslateDirection(true, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch); } if (this.zoomVert || this.pinchVert) { this.pinchTranslateDirection(false, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch); } }, /** * Run translation operations for each direction (horizontal and vertical) independently */ pinchTranslateDirection: function (horiz, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch, forcedScale) { var chart = this.chart, xy = horiz ? 'x' : 'y', XY = horiz ? 'X' : 'Y', sChartXY = 'chart' + XY, wh = horiz ? 'width' : 'height', plotLeftTop = chart['plot' + (horiz ? 'Left' : 'Top')], selectionWH, selectionXY, clipXY, scale = forcedScale || 1, inverted = chart.inverted, bounds = chart.bounds[horiz ? 'h' : 'v'], singleTouch = pinchDown.length === 1, touch0Start = pinchDown[0][sChartXY], touch0Now = touches[0][sChartXY], touch1Start = !singleTouch && pinchDown[1][sChartXY], touch1Now = !singleTouch && touches[1][sChartXY], outOfBounds, transformScale, scaleKey, setScale = function () { if (!singleTouch && mathAbs(touch0Start - touch1Start) > 20) { // Don't zoom if fingers are too close on this axis scale = forcedScale || mathAbs(touch0Now - touch1Now) / mathAbs(touch0Start - touch1Start); } clipXY = ((plotLeftTop - touch0Now) / scale) + touch0Start; selectionWH = chart['plot' + (horiz ? 'Width' : 'Height')] / scale; }; // Set the scale, first pass setScale(); selectionXY = clipXY; // the clip position (x or y) is altered if out of bounds, the selection position is not // Out of bounds if (selectionXY < bounds.min) { selectionXY = bounds.min; outOfBounds = true; } else if (selectionXY + selectionWH > bounds.max) { selectionXY = bounds.max - selectionWH; outOfBounds = true; } // Is the chart dragged off its bounds, determined by dataMin and dataMax? if (outOfBounds) { // Modify the touchNow position in order to create an elastic drag movement. This indicates // to the user that the chart is responsive but can't be dragged further. touch0Now -= 0.8 * (touch0Now - lastValidTouch[xy][0]); if (!singleTouch) { touch1Now -= 0.8 * (touch1Now - lastValidTouch[xy][1]); } // Set the scale, second pass to adapt to the modified touchNow positions setScale(); } else { lastValidTouch[xy] = [touch0Now, touch1Now]; } // Set geometry for clipping, selection and transformation if (!inverted) { // TODO: implement clipping for inverted charts clip[xy] = clipXY - plotLeftTop; clip[wh] = selectionWH; } scaleKey = inverted ? (horiz ? 'scaleY' : 'scaleX') : 'scale' + XY; transformScale = inverted ? 1 / scale : scale; selectionMarker[wh] = selectionWH; selectionMarker[xy] = selectionXY; transform[scaleKey] = scale; transform['translate' + XY] = (transformScale * plotLeftTop) + (touch0Now - (transformScale * touch0Start)); }, /** * Handle touch events with two touches */ pinch: function (e) { var self = this, chart = self.chart, pinchDown = self.pinchDown, followTouchMove = self.followTouchMove, touches = e.touches, touchesLength = touches.length, lastValidTouch = self.lastValidTouch, hasZoom = self.hasZoom, selectionMarker = self.selectionMarker, transform = {}, fireClickEvent = touchesLength === 1 && ((self.inClass(e.target, PREFIX + 'tracker') && chart.runTrackerClick) || self.runChartClick), clip = {}; // On touch devices, only proceed to trigger click if a handler is defined if ((hasZoom || followTouchMove) && !fireClickEvent) { e.preventDefault(); } // Normalize each touch map(touches, function (e) { return self.normalize(e); }); // Register the touch start position if (e.type === 'touchstart') { each(touches, function (e, i) { pinchDown[i] = { chartX: e.chartX, chartY: e.chartY }; }); lastValidTouch.x = [pinchDown[0].chartX, pinchDown[1] && pinchDown[1].chartX]; lastValidTouch.y = [pinchDown[0].chartY, pinchDown[1] && pinchDown[1].chartY]; // Identify the data bounds in pixels each(chart.axes, function (axis) { if (axis.zoomEnabled) { var bounds = chart.bounds[axis.horiz ? 'h' : 'v'], minPixelPadding = axis.minPixelPadding, min = axis.toPixels(pick(axis.options.min, axis.dataMin)), max = axis.toPixels(pick(axis.options.max, axis.dataMax)), absMin = mathMin(min, max), absMax = mathMax(min, max); // Store the bounds for use in the touchmove handler bounds.min = mathMin(axis.pos, absMin - minPixelPadding); bounds.max = mathMax(axis.pos + axis.len, absMax + minPixelPadding); } }); self.res = true; // reset on next move // Event type is touchmove, handle panning and pinching } else if (pinchDown.length) { // can be 0 when releasing, if touchend fires first // Set the marker if (!selectionMarker) { self.selectionMarker = selectionMarker = extend({ destroy: noop }, chart.plotBox); } self.pinchTranslate(pinchDown, touches, transform, selectionMarker, clip, lastValidTouch); self.hasPinched = hasZoom; // Scale and translate the groups to provide visual feedback during pinching self.scaleGroups(transform, clip); // Optionally move the tooltip on touchmove if (!hasZoom && followTouchMove && touchesLength === 1) { this.runPointActions(self.normalize(e)); } else if (self.res) { self.res = false; this.reset(false, 0); } } }, onContainerTouchStart: function (e) { var chart = this.chart; hoverChartIndex = chart.index; if (e.touches.length === 1) { e = this.normalize(e); if (chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) { // Run mouse events and display tooltip etc this.runPointActions(e); this.pinch(e); } else { // Hide the tooltip on touching outside the plot area (#1203) this.reset(); } } else if (e.touches.length === 2) { this.pinch(e); } }, onContainerTouchMove: function (e) { if (e.touches.length === 1 || e.touches.length === 2) { this.pinch(e); } }, onDocumentTouchEnd: function (e) { if (charts[hoverChartIndex]) { charts[hoverChartIndex].pointer.drop(e); } } }); if (win.PointerEvent || win.MSPointerEvent) { // The touches object keeps track of the points being touched at all times var touches = {}, hasPointerEvent = !!win.PointerEvent, getWebkitTouches = function () { var key, fake = []; fake.item = function (i) { return this[i]; }; for (key in touches) { if (touches.hasOwnProperty(key)) { fake.push({ pageX: touches[key].pageX, pageY: touches[key].pageY, target: touches[key].target }); } } return fake; }, translateMSPointer = function (e, method, wktype, callback) { var p; e = e.originalEvent || e; if ((e.pointerType === 'touch' || e.pointerType === e.MSPOINTER_TYPE_TOUCH) && charts[hoverChartIndex]) { callback(e); p = charts[hoverChartIndex].pointer; p[method]({ type: wktype, target: e.currentTarget, preventDefault: noop, touches: getWebkitTouches() }); } }; /** * Extend the Pointer prototype with methods for each event handler and more */ extend(Pointer.prototype, { onContainerPointerDown: function (e) { translateMSPointer(e, 'onContainerTouchStart', 'touchstart', function (e) { touches[e.pointerId] = { pageX: e.pageX, pageY: e.pageY, target: e.currentTarget }; }); }, onContainerPointerMove: function (e) { translateMSPointer(e, 'onContainerTouchMove', 'touchmove', function (e) { touches[e.pointerId] = { pageX: e.pageX, pageY: e.pageY }; if (!touches[e.pointerId].target) { touches[e.pointerId].target = e.currentTarget; } }); }, onDocumentPointerUp: function (e) { translateMSPointer(e, 'onContainerTouchEnd', 'touchend', function (e) { delete touches[e.pointerId]; }); }, /** * Add or remove the MS Pointer specific events */ batchMSEvents: function (fn) { fn(this.chart.container, hasPointerEvent ? 'pointerdown' : 'MSPointerDown', this.onContainerPointerDown); fn(this.chart.container, hasPointerEvent ? 'pointermove' : 'MSPointerMove', this.onContainerPointerMove); fn(doc, hasPointerEvent ? 'pointerup' : 'MSPointerUp', this.onDocumentPointerUp); } }); // Disable default IE actions for pinch and such on chart element wrap(Pointer.prototype, 'init', function (proceed, chart, options) { proceed.call(this, chart, options); if (this.hasZoom || this.followTouchMove) { css(chart.container, { '-ms-touch-action': NONE, 'touch-action': NONE }); } }); // Add IE specific touch events to chart wrap(Pointer.prototype, 'setDOMEvents', function (proceed) { proceed.apply(this); if (this.hasZoom || this.followTouchMove) { this.batchMSEvents(addEvent); } }); // Destroy MS events also wrap(Pointer.prototype, 'destroy', function (proceed) { this.batchMSEvents(removeEvent); proceed.call(this); }); } /** * The overview of the chart's series */ var Legend = Highcharts.Legend = function (chart, options) { this.init(chart, options); }; Legend.prototype = { /** * Initialize the legend */ init: function (chart, options) { var legend = this, itemStyle = options.itemStyle, padding = pick(options.padding, 8), itemMarginTop = options.itemMarginTop || 0; this.options = options; if (!options.enabled) { return; } legend.itemStyle = itemStyle; legend.itemHiddenStyle = merge(itemStyle, options.itemHiddenStyle); legend.itemMarginTop = itemMarginTop; legend.padding = padding; legend.initialItemX = padding; legend.initialItemY = padding - 5; // 5 is the number of pixels above the text legend.maxItemWidth = 0; legend.chart = chart; legend.itemHeight = 0; legend.lastLineHeight = 0; legend.symbolWidth = pick(options.symbolWidth, 16); legend.pages = []; // Render it legend.render(); // move checkboxes addEvent(legend.chart, 'endResize', function () { legend.positionCheckboxes(); }); }, /** * Set the colors for the legend item * @param {Object} item A Series or Point instance * @param {Object} visible Dimmed or colored */ colorizeItem: function (item, visible) { var legend = this, options = legend.options, legendItem = item.legendItem, legendLine = item.legendLine, legendSymbol = item.legendSymbol, hiddenColor = legend.itemHiddenStyle.color, textColor = visible ? options.itemStyle.color : hiddenColor, symbolColor = visible ? (item.legendColor || item.color || '#CCC') : hiddenColor, markerOptions = item.options && item.options.marker, symbolAttr = { fill: symbolColor }, key, val; if (legendItem) { legendItem.css({ fill: textColor, color: textColor }); // color for #1553, oldIE } if (legendLine) { legendLine.attr({ stroke: symbolColor }); } if (legendSymbol) { // Apply marker options if (markerOptions && legendSymbol.isMarker) { // #585 symbolAttr.stroke = symbolColor; markerOptions = item.convertAttribs(markerOptions); for (key in markerOptions) { val = markerOptions[key]; if (val !== UNDEFINED) { symbolAttr[key] = val; } } } legendSymbol.attr(symbolAttr); } }, /** * Position the legend item * @param {Object} item A Series or Point instance */ positionItem: function (item) { var legend = this, options = legend.options, symbolPadding = options.symbolPadding, ltr = !options.rtl, legendItemPos = item._legendItemPos, itemX = legendItemPos[0], itemY = legendItemPos[1], checkbox = item.checkbox; if (item.legendGroup) { item.legendGroup.translate( ltr ? itemX : legend.legendWidth - itemX - 2 * symbolPadding - 4, itemY ); } if (checkbox) { checkbox.x = itemX; checkbox.y = itemY; } }, /** * Destroy a single legend item * @param {Object} item The series or point */ destroyItem: function (item) { var checkbox = item.checkbox; // destroy SVG elements each(['legendItem', 'legendLine', 'legendSymbol', 'legendGroup'], function (key) { if (item[key]) { item[key] = item[key].destroy(); } }); if (checkbox) { discardElement(item.checkbox); } }, /** * Destroys the legend. */ destroy: function () { var legend = this, legendGroup = legend.group, box = legend.box; if (box) { legend.box = box.destroy(); } if (legendGroup) { legend.group = legendGroup.destroy(); } }, /** * Position the checkboxes after the width is determined */ positionCheckboxes: function (scrollOffset) { var alignAttr = this.group.alignAttr, translateY, clipHeight = this.clipHeight || this.legendHeight; if (alignAttr) { translateY = alignAttr.translateY; each(this.allItems, function (item) { var checkbox = item.checkbox, top; if (checkbox) { top = (translateY + checkbox.y + (scrollOffset || 0) + 3); css(checkbox, { left: (alignAttr.translateX + item.checkboxOffset + checkbox.x - 20) + PX, top: top + PX, display: top > translateY - 6 && top < translateY + clipHeight - 6 ? '' : NONE }); } }); } }, /** * Render the legend title on top of the legend */ renderTitle: function () { var options = this.options, padding = this.padding, titleOptions = options.title, titleHeight = 0, bBox; if (titleOptions.text) { if (!this.title) { this.title = this.chart.renderer.label(titleOptions.text, padding - 3, padding - 4, null, null, null, null, null, 'legend-title') .attr({ zIndex: 1 }) .css(titleOptions.style) .add(this.group); } bBox = this.title.getBBox(); titleHeight = bBox.height; this.offsetWidth = bBox.width; // #1717 this.contentGroup.attr({ translateY: titleHeight }); } this.titleHeight = titleHeight; }, /** * Render a single specific legend item * @param {Object} item A series or point */ renderItem: function (item) { var legend = this, chart = legend.chart, renderer = chart.renderer, options = legend.options, horizontal = options.layout === 'horizontal', symbolWidth = legend.symbolWidth, symbolPadding = options.symbolPadding, itemStyle = legend.itemStyle, itemHiddenStyle = legend.itemHiddenStyle, padding = legend.padding, itemDistance = horizontal ? pick(options.itemDistance, 20) : 0, ltr = !options.rtl, itemHeight, widthOption = options.width, itemMarginBottom = options.itemMarginBottom || 0, itemMarginTop = legend.itemMarginTop, initialItemX = legend.initialItemX, bBox, itemWidth, li = item.legendItem, series = item.series && item.series.drawLegendSymbol ? item.series : item, seriesOptions = series.options, showCheckbox = legend.createCheckboxForItem && seriesOptions && seriesOptions.showCheckbox, useHTML = options.useHTML; if (!li) { // generate it once, later move it // Generate the group box // A group to hold the symbol and text. Text is to be appended in Legend class. item.legendGroup = renderer.g('legend-item') .attr({ zIndex: 1 }) .add(legend.scrollGroup); // Generate the list item text and add it to the group item.legendItem = li = renderer.text( options.labelFormat ? format(options.labelFormat, item) : options.labelFormatter.call(item), ltr ? symbolWidth + symbolPadding : -symbolPadding, legend.baseline || 0, useHTML ) .css(merge(item.visible ? itemStyle : itemHiddenStyle)) // merge to prevent modifying original (#1021) .attr({ align: ltr ? 'left' : 'right', zIndex: 2 }) .add(item.legendGroup); // Get the baseline for the first item - the font size is equal for all if (!legend.baseline) { legend.baseline = renderer.fontMetrics(itemStyle.fontSize, li).f + 3 + itemMarginTop; li.attr('y', legend.baseline); } // Draw the legend symbol inside the group box series.drawLegendSymbol(legend, item); if (legend.setItemEvents) { legend.setItemEvents(item, li, useHTML, itemStyle, itemHiddenStyle); } // Colorize the items legend.colorizeItem(item, item.visible); // add the HTML checkbox on top if (showCheckbox) { legend.createCheckboxForItem(item); } } // calculate the positions for the next line bBox = li.getBBox(); itemWidth = item.checkboxOffset = options.itemWidth || item.legendItemWidth || symbolWidth + symbolPadding + bBox.width + itemDistance + (showCheckbox ? 20 : 0); legend.itemHeight = itemHeight = mathRound(item.legendItemHeight || bBox.height); // if the item exceeds the width, start a new line if (horizontal && legend.itemX - initialItemX + itemWidth > (widthOption || (chart.chartWidth - 2 * padding - initialItemX - options.x))) { legend.itemX = initialItemX; legend.itemY += itemMarginTop + legend.lastLineHeight + itemMarginBottom; legend.lastLineHeight = 0; // reset for next line } // If the item exceeds the height, start a new column /*if (!horizontal && legend.itemY + options.y + itemHeight > chart.chartHeight - spacingTop - spacingBottom) { legend.itemY = legend.initialItemY; legend.itemX += legend.maxItemWidth; legend.maxItemWidth = 0; }*/ // Set the edge positions legend.maxItemWidth = mathMax(legend.maxItemWidth, itemWidth); legend.lastItemY = itemMarginTop + legend.itemY + itemMarginBottom; legend.lastLineHeight = mathMax(itemHeight, legend.lastLineHeight); // #915 // cache the position of the newly generated or reordered items item._legendItemPos = [legend.itemX, legend.itemY]; // advance if (horizontal) { legend.itemX += itemWidth; } else { legend.itemY += itemMarginTop + itemHeight + itemMarginBottom; legend.lastLineHeight = itemHeight; } // the width of the widest item legend.offsetWidth = widthOption || mathMax( (horizontal ? legend.itemX - initialItemX - itemDistance : itemWidth) + padding, legend.offsetWidth ); }, /** * Get all items, which is one item per series for normal series and one item per point * for pie series. */ getAllItems: function () { var allItems = []; each(this.chart.series, function (series) { var seriesOptions = series.options; // Handle showInLegend. If the series is linked to another series, defaults to false. if (!pick(seriesOptions.showInLegend, !defined(seriesOptions.linkedTo) ? UNDEFINED : false, true)) { return; } // use points or series for the legend item depending on legendType allItems = allItems.concat( series.legendItems || (seriesOptions.legendType === 'point' ? series.data : series) ); }); return allItems; }, /** * Render the legend. This method can be called both before and after * chart.render. If called after, it will only rearrange items instead * of creating new ones. */ render: function () { var legend = this, chart = legend.chart, renderer = chart.renderer, legendGroup = legend.group, allItems, display, legendWidth, legendHeight, box = legend.box, options = legend.options, padding = legend.padding, legendBorderWidth = options.borderWidth, legendBackgroundColor = options.backgroundColor; legend.itemX = legend.initialItemX; legend.itemY = legend.initialItemY; legend.offsetWidth = 0; legend.lastItemY = 0; if (!legendGroup) { legend.group = legendGroup = renderer.g('legend') .attr({ zIndex: 7 }) .add(); legend.contentGroup = renderer.g() .attr({ zIndex: 1 }) // above background .add(legendGroup); legend.scrollGroup = renderer.g() .add(legend.contentGroup); } legend.renderTitle(); // add each series or point allItems = legend.getAllItems(); // sort by legendIndex stableSort(allItems, function (a, b) { return ((a.options && a.options.legendIndex) || 0) - ((b.options && b.options.legendIndex) || 0); }); // reversed legend if (options.reversed) { allItems.reverse(); } legend.allItems = allItems; legend.display = display = !!allItems.length; // render the items each(allItems, function (item) { legend.renderItem(item); }); // Draw the border legendWidth = options.width || legend.offsetWidth; legendHeight = legend.lastItemY + legend.lastLineHeight + legend.titleHeight; legendHeight = legend.handleOverflow(legendHeight); if (legendBorderWidth || legendBackgroundColor) { legendWidth += padding; legendHeight += padding; if (!box) { legend.box = box = renderer.rect( 0, 0, legendWidth, legendHeight, options.borderRadius, legendBorderWidth || 0 ).attr({ stroke: options.borderColor, 'stroke-width': legendBorderWidth || 0, fill: legendBackgroundColor || NONE }) .add(legendGroup) .shadow(options.shadow); box.isNew = true; } else if (legendWidth > 0 && legendHeight > 0) { box[box.isNew ? 'attr' : 'animate']( box.crisp({ width: legendWidth, height: legendHeight }) ); box.isNew = false; } // hide the border if no items box[display ? 'show' : 'hide'](); } legend.legendWidth = legendWidth; legend.legendHeight = legendHeight; // Now that the legend width and height are established, put the items in the // final position each(allItems, function (item) { legend.positionItem(item); }); // 1.x compatibility: positioning based on style /*var props = ['left', 'right', 'top', 'bottom'], prop, i = 4; while (i--) { prop = props[i]; if (options.style[prop] && options.style[prop] !== 'auto') { options[i < 2 ? 'align' : 'verticalAlign'] = prop; options[i < 2 ? 'x' : 'y'] = pInt(options.style[prop]) * (i % 2 ? -1 : 1); } }*/ if (display) { legendGroup.align(extend({ width: legendWidth, height: legendHeight }, options), true, 'spacingBox'); } if (!chart.isResizing) { this.positionCheckboxes(); } }, /** * Set up the overflow handling by adding navigation with up and down arrows below the * legend. */ handleOverflow: function (legendHeight) { var legend = this, chart = this.chart, renderer = chart.renderer, options = this.options, optionsY = options.y, alignTop = options.verticalAlign === 'top', spaceHeight = chart.spacingBox.height + (alignTop ? -optionsY : optionsY) - this.padding, maxHeight = options.maxHeight, clipHeight, clipRect = this.clipRect, navOptions = options.navigation, animation = pick(navOptions.animation, true), arrowSize = navOptions.arrowSize || 12, nav = this.nav, pages = this.pages, lastY, allItems = this.allItems; // Adjust the height if (options.layout === 'horizontal') { spaceHeight /= 2; } if (maxHeight) { spaceHeight = mathMin(spaceHeight, maxHeight); } // Reset the legend height and adjust the clipping rectangle pages.length = 0; if (legendHeight > spaceHeight && !options.useHTML) { this.clipHeight = clipHeight = mathMax(spaceHeight - 20 - this.titleHeight - this.padding, 0); this.currentPage = pick(this.currentPage, 1); this.fullHeight = legendHeight; // Fill pages with Y positions so that the top of each a legend item defines // the scroll top for each page (#2098) each(allItems, function (item, i) { var y = item._legendItemPos[1], h = mathRound(item.legendItem.getBBox().height), len = pages.length; if (!len || (y - pages[len - 1] > clipHeight && (lastY || y) !== pages[len - 1])) { pages.push(lastY || y); len++; } if (i === allItems.length - 1 && y + h - pages[len - 1] > clipHeight) { pages.push(y); } if (y !== lastY) { lastY = y; } }); // Only apply clipping if needed. Clipping causes blurred legend in PDF export (#1787) if (!clipRect) { clipRect = legend.clipRect = renderer.clipRect(0, this.padding, 9999, 0); legend.contentGroup.clip(clipRect); } clipRect.attr({ height: clipHeight }); // Add navigation elements if (!nav) { this.nav = nav = renderer.g().attr({ zIndex: 1 }).add(this.group); this.up = renderer.symbol('triangle', 0, 0, arrowSize, arrowSize) .on('click', function () { legend.scroll(-1, animation); }) .add(nav); this.pager = renderer.text('', 15, 10) .css(navOptions.style) .add(nav); this.down = renderer.symbol('triangle-down', 0, 0, arrowSize, arrowSize) .on('click', function () { legend.scroll(1, animation); }) .add(nav); } // Set initial position legend.scroll(0); legendHeight = spaceHeight; } else if (nav) { clipRect.attr({ height: chart.chartHeight }); nav.hide(); this.scrollGroup.attr({ translateY: 1 }); this.clipHeight = 0; // #1379 } return legendHeight; }, /** * Scroll the legend by a number of pages * @param {Object} scrollBy * @param {Object} animation */ scroll: function (scrollBy, animation) { var pages = this.pages, pageCount = pages.length, currentPage = this.currentPage + scrollBy, clipHeight = this.clipHeight, navOptions = this.options.navigation, activeColor = navOptions.activeColor, inactiveColor = navOptions.inactiveColor, pager = this.pager, padding = this.padding, scrollOffset; // When resizing while looking at the last page if (currentPage > pageCount) { currentPage = pageCount; } if (currentPage > 0) { if (animation !== UNDEFINED) { setAnimation(animation, this.chart); } this.nav.attr({ translateX: padding, translateY: clipHeight + this.padding + 7 + this.titleHeight, visibility: VISIBLE }); this.up.attr({ fill: currentPage === 1 ? inactiveColor : activeColor }) .css({ cursor: currentPage === 1 ? 'default' : 'pointer' }); pager.attr({ text: currentPage + '/' + pageCount }); this.down.attr({ x: 18 + this.pager.getBBox().width, // adjust to text width fill: currentPage === pageCount ? inactiveColor : activeColor }) .css({ cursor: currentPage === pageCount ? 'default' : 'pointer' }); scrollOffset = -pages[currentPage - 1] + this.initialItemY; this.scrollGroup.animate({ translateY: scrollOffset }); this.currentPage = currentPage; this.positionCheckboxes(scrollOffset); } } }; /* * LegendSymbolMixin */ var LegendSymbolMixin = Highcharts.LegendSymbolMixin = { /** * Get the series' symbol in the legend * * @param {Object} legend The legend object * @param {Object} item The series (this) or point */ drawRectangle: function (legend, item) { var symbolHeight = legend.options.symbolHeight || 12; item.legendSymbol = this.chart.renderer.rect( 0, legend.baseline - 5 - (symbolHeight / 2), legend.symbolWidth, symbolHeight, legend.options.symbolRadius || 0 ).attr({ zIndex: 3 }).add(item.legendGroup); }, /** * Get the series' symbol in the legend. This method should be overridable to create custom * symbols through Highcharts.seriesTypes[type].prototype.drawLegendSymbols. * * @param {Object} legend The legend object */ drawLineMarker: function (legend) { var options = this.options, markerOptions = options.marker, radius, legendOptions = legend.options, legendSymbol, symbolWidth = legend.symbolWidth, renderer = this.chart.renderer, legendItemGroup = this.legendGroup, verticalCenter = legend.baseline - mathRound(renderer.fontMetrics(legendOptions.itemStyle.fontSize, this.legendItem).b * 0.3), attr; // Draw the line if (options.lineWidth) { attr = { 'stroke-width': options.lineWidth }; if (options.dashStyle) { attr.dashstyle = options.dashStyle; } this.legendLine = renderer.path([ M, 0, verticalCenter, L, symbolWidth, verticalCenter ]) .attr(attr) .add(legendItemGroup); } // Draw the marker if (markerOptions && markerOptions.enabled !== false) { radius = markerOptions.radius; this.legendSymbol = legendSymbol = renderer.symbol( this.symbol, (symbolWidth / 2) - radius, verticalCenter - radius, 2 * radius, 2 * radius ) .add(legendItemGroup); legendSymbol.isMarker = true; } } }; // Workaround for #2030, horizontal legend items not displaying in IE11 Preview, // and for #2580, a similar drawing flaw in Firefox 26. // TODO: Explore if there's a general cause for this. The problem may be related // to nested group elements, as the legend item texts are within 4 group elements. if (/Trident\/7\.0/.test(userAgent) || isFirefox) { wrap(Legend.prototype, 'positionItem', function (proceed, item) { var legend = this, runPositionItem = function () { // If chart destroyed in sync, this is undefined (#2030) if (item._legendItemPos) { proceed.call(legend, item); } }; // Do it now, for export and to get checkbox placement runPositionItem(); // Do it after to work around the core issue setTimeout(runPositionItem); }); } /** * The chart class * @param {Object} options * @param {Function} callback Function to run when the chart has loaded */ function Chart() { this.init.apply(this, arguments); } Chart.prototype = { /** * Initialize the chart */ init: function (userOptions, callback) { // Handle regular options var options, seriesOptions = userOptions.series; // skip merging data points to increase performance userOptions.series = null; options = merge(defaultOptions, userOptions); // do the merge options.series = userOptions.series = seriesOptions; // set back the series data this.userOptions = userOptions; var optionsChart = options.chart; // Create margin & spacing array this.margin = this.splashArray('margin', optionsChart); this.spacing = this.splashArray('spacing', optionsChart); var chartEvents = optionsChart.events; //this.runChartClick = chartEvents && !!chartEvents.click; this.bounds = { h: {}, v: {} }; // Pixel data bounds for touch zoom this.callback = callback; this.isResizing = 0; this.options = options; //chartTitleOptions = UNDEFINED; //chartSubtitleOptions = UNDEFINED; this.axes = []; this.series = []; this.hasCartesianSeries = optionsChart.showAxes; //this.axisOffset = UNDEFINED; //this.maxTicks = UNDEFINED; // handle the greatest amount of ticks on grouped axes //this.inverted = UNDEFINED; //this.loadingShown = UNDEFINED; //this.container = UNDEFINED; //this.chartWidth = UNDEFINED; //this.chartHeight = UNDEFINED; //this.marginRight = UNDEFINED; //this.marginBottom = UNDEFINED; //this.containerWidth = UNDEFINED; //this.containerHeight = UNDEFINED; //this.oldChartWidth = UNDEFINED; //this.oldChartHeight = UNDEFINED; //this.renderTo = UNDEFINED; //this.renderToClone = UNDEFINED; //this.spacingBox = UNDEFINED //this.legend = UNDEFINED; // Elements //this.chartBackground = UNDEFINED; //this.plotBackground = UNDEFINED; //this.plotBGImage = UNDEFINED; //this.plotBorder = UNDEFINED; //this.loadingDiv = UNDEFINED; //this.loadingSpan = UNDEFINED; var chart = this, eventType; // Add the chart to the global lookup chart.index = charts.length; charts.push(chart); chartCount++; // Set up auto resize if (optionsChart.reflow !== false) { addEvent(chart, 'load', function () { chart.initReflow(); }); } // Chart event handlers if (chartEvents) { for (eventType in chartEvents) { addEvent(chart, eventType, chartEvents[eventType]); } } chart.xAxis = []; chart.yAxis = []; // Expose methods and variables chart.animation = useCanVG ? false : pick(optionsChart.animation, true); chart.pointCount = chart.colorCounter = chart.symbolCounter = 0; chart.firstRender(); }, /** * Initialize an individual series, called internally before render time */ initSeries: function (options) { var chart = this, optionsChart = chart.options.chart, type = options.type || optionsChart.type || optionsChart.defaultSeriesType, series, constr = seriesTypes[type]; // No such series type if (!constr) { error(17, true); } series = new constr(); series.init(this, options); return series; }, /** * Check whether a given point is within the plot area * * @param {Number} plotX Pixel x relative to the plot area * @param {Number} plotY Pixel y relative to the plot area * @param {Boolean} inverted Whether the chart is inverted */ isInsidePlot: function (plotX, plotY, inverted) { var x = inverted ? plotY : plotX, y = inverted ? plotX : plotY; return x >= 0 && x <= this.plotWidth && y >= 0 && y <= this.plotHeight; }, /** * Adjust all axes tick amounts */ adjustTickAmounts: function () { if (this.options.chart.alignTicks !== false) { each(this.axes, function (axis) { axis.adjustTickAmount(); }); } this.maxTicks = null; }, /** * Redraw legend, axes or series based on updated data * * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ redraw: function (animation) { var chart = this, axes = chart.axes, series = chart.series, pointer = chart.pointer, legend = chart.legend, redrawLegend = chart.isDirtyLegend, hasStackedSeries, hasDirtyStacks, hasCartesianSeries = chart.hasCartesianSeries, isDirtyBox = chart.isDirtyBox, // todo: check if it has actually changed? seriesLength = series.length, i = seriesLength, serie, renderer = chart.renderer, isHiddenChart = renderer.isHidden(), afterRedraw = []; setAnimation(animation, chart); if (isHiddenChart) { chart.cloneRenderTo(); } // Adjust title layout (reflow multiline text) chart.layOutTitles(); // link stacked series while (i--) { serie = series[i]; if (serie.options.stacking) { hasStackedSeries = true; if (serie.isDirty) { hasDirtyStacks = true; break; } } } if (hasDirtyStacks) { // mark others as dirty i = seriesLength; while (i--) { serie = series[i]; if (serie.options.stacking) { serie.isDirty = true; } } } // handle updated data in the series each(series, function (serie) { if (serie.isDirty) { // prepare the data so axis can read it if (serie.options.legendType === 'point') { redrawLegend = true; } } }); // handle added or removed series if (redrawLegend && legend.options.enabled) { // series or pie points are added or removed // draw legend graphics legend.render(); chart.isDirtyLegend = false; } // reset stacks if (hasStackedSeries) { chart.getStacks(); } if (hasCartesianSeries) { if (!chart.isResizing) { // reset maxTicks chart.maxTicks = null; // set axes scales each(axes, function (axis) { axis.setScale(); }); } chart.adjustTickAmounts(); } chart.getMargins(); // #3098 if (hasCartesianSeries) { // If one axis is dirty, all axes must be redrawn (#792, #2169) each(axes, function (axis) { if (axis.isDirty) { isDirtyBox = true; } }); // redraw axes each(axes, function (axis) { // Fire 'afterSetExtremes' only if extremes are set if (axis.isDirtyExtremes) { // #821 axis.isDirtyExtremes = false; afterRedraw.push(function () { // prevent a recursive call to chart.redraw() (#1119) fireEvent(axis, 'afterSetExtremes', extend(axis.eventArgs, axis.getExtremes())); // #747, #751 delete axis.eventArgs; }); } if (isDirtyBox || hasStackedSeries) { axis.redraw(); } }); } // the plot areas size has changed if (isDirtyBox) { chart.drawChartBox(); } // redraw affected series each(series, function (serie) { if (serie.isDirty && serie.visible && (!serie.isCartesian || serie.xAxis)) { // issue #153 serie.redraw(); } }); // move tooltip or reset if (pointer) { pointer.reset(true); } // redraw if canvas renderer.draw(); // fire the event fireEvent(chart, 'redraw'); // jQuery breaks this when calling it from addEvent. Overwrites chart.redraw if (isHiddenChart) { chart.cloneRenderTo(true); } // Fire callbacks that are put on hold until after the redraw each(afterRedraw, function (callback) { callback.call(); }); }, /** * Get an axis, series or point object by id. * @param id {String} The id as given in the configuration options */ get: function (id) { var chart = this, axes = chart.axes, series = chart.series; var i, j, points; // search axes for (i = 0; i < axes.length; i++) { if (axes[i].options.id === id) { return axes[i]; } } // search series for (i = 0; i < series.length; i++) { if (series[i].options.id === id) { return series[i]; } } // search points for (i = 0; i < series.length; i++) { points = series[i].points || []; for (j = 0; j < points.length; j++) { if (points[j].id === id) { return points[j]; } } } return null; }, /** * Create the Axis instances based on the config options */ getAxes: function () { var chart = this, options = this.options, xAxisOptions = options.xAxis = splat(options.xAxis || {}), yAxisOptions = options.yAxis = splat(options.yAxis || {}), optionsArray, axis; // make sure the options are arrays and add some members each(xAxisOptions, function (axis, i) { axis.index = i; axis.isX = true; }); each(yAxisOptions, function (axis, i) { axis.index = i; }); // concatenate all axis options into one array optionsArray = xAxisOptions.concat(yAxisOptions); each(optionsArray, function (axisOptions) { axis = new Axis(chart, axisOptions); }); chart.adjustTickAmounts(); }, /** * Get the currently selected points from all series */ getSelectedPoints: function () { var points = []; each(this.series, function (serie) { points = points.concat(grep(serie.points || [], function (point) { return point.selected; })); }); return points; }, /** * Get the currently selected series */ getSelectedSeries: function () { return grep(this.series, function (serie) { return serie.selected; }); }, /** * Generate stacks for each series and calculate stacks total values */ getStacks: function () { var chart = this; // reset stacks for each yAxis each(chart.yAxis, function (axis) { if (axis.stacks && axis.hasVisibleSeries) { axis.oldStacks = axis.stacks; } }); each(chart.series, function (series) { if (series.options.stacking && (series.visible === true || chart.options.chart.ignoreHiddenSeries === false)) { series.stackKey = series.type + pick(series.options.stack, ''); } }); }, /** * Show the title and subtitle of the chart * * @param titleOptions {Object} New title options * @param subtitleOptions {Object} New subtitle options * */ setTitle: function (titleOptions, subtitleOptions, redraw) { var chart = this, options = chart.options, chartTitleOptions, chartSubtitleOptions; chartTitleOptions = options.title = merge(options.title, titleOptions); chartSubtitleOptions = options.subtitle = merge(options.subtitle, subtitleOptions); // add title and subtitle each([ ['title', titleOptions, chartTitleOptions], ['subtitle', subtitleOptions, chartSubtitleOptions] ], function (arr) { var name = arr[0], title = chart[name], titleOptions = arr[1], chartTitleOptions = arr[2]; if (title && titleOptions) { chart[name] = title = title.destroy(); // remove old } if (chartTitleOptions && chartTitleOptions.text && !title) { chart[name] = chart.renderer.text( chartTitleOptions.text, 0, 0, chartTitleOptions.useHTML ) .attr({ align: chartTitleOptions.align, 'class': PREFIX + name, zIndex: chartTitleOptions.zIndex || 4 }) .css(chartTitleOptions.style) .add(); } }); chart.layOutTitles(redraw); }, /** * Lay out the chart titles and cache the full offset height for use in getMargins */ layOutTitles: function (redraw) { var titleOffset = 0, title = this.title, subtitle = this.subtitle, options = this.options, titleOptions = options.title, subtitleOptions = options.subtitle, requiresDirtyBox, renderer = this.renderer, autoWidth = this.spacingBox.width - 44; // 44 makes room for default context button if (title) { title .css({ width: (titleOptions.width || autoWidth) + PX }) .align(extend({ y: renderer.fontMetrics(titleOptions.style.fontSize, title).b - 3 }, titleOptions), false, 'spacingBox'); if (!titleOptions.floating && !titleOptions.verticalAlign) { titleOffset = title.getBBox().height; } } if (subtitle) { subtitle .css({ width: (subtitleOptions.width || autoWidth) + PX }) .align(extend({ y: titleOffset + (titleOptions.margin - 13) + renderer.fontMetrics(titleOptions.style.fontSize, subtitle).b }, subtitleOptions), false, 'spacingBox'); if (!subtitleOptions.floating && !subtitleOptions.verticalAlign) { titleOffset = mathCeil(titleOffset + subtitle.getBBox().height); } } requiresDirtyBox = this.titleOffset !== titleOffset; this.titleOffset = titleOffset; // used in getMargins if (!this.isDirtyBox && requiresDirtyBox) { this.isDirtyBox = requiresDirtyBox; // Redraw if necessary (#2719, #2744) if (this.hasRendered && pick(redraw, true) && this.isDirtyBox) { this.redraw(); } } }, /** * Get chart width and height according to options and container size */ getChartSize: function () { var chart = this, optionsChart = chart.options.chart, widthOption = optionsChart.width, heightOption = optionsChart.height, renderTo = chart.renderToClone || chart.renderTo; // get inner width and height from jQuery (#824) if (!defined(widthOption)) { chart.containerWidth = adapterRun(renderTo, 'width'); } if (!defined(heightOption)) { chart.containerHeight = adapterRun(renderTo, 'height'); } chart.chartWidth = mathMax(0, widthOption || chart.containerWidth || 600); // #1393, 1460 chart.chartHeight = mathMax(0, pick(heightOption, // the offsetHeight of an empty container is 0 in standard browsers, but 19 in IE7: chart.containerHeight > 19 ? chart.containerHeight : 400)); }, /** * Create a clone of the chart's renderTo div and place it outside the viewport to allow * size computation on chart.render and chart.redraw */ cloneRenderTo: function (revert) { var clone = this.renderToClone, container = this.container; // Destroy the clone and bring the container back to the real renderTo div if (revert) { if (clone) { this.renderTo.appendChild(container); discardElement(clone); delete this.renderToClone; } // Set up the clone } else { if (container && container.parentNode === this.renderTo) { this.renderTo.removeChild(container); // do not clone this } this.renderToClone = clone = this.renderTo.cloneNode(0); css(clone, { position: ABSOLUTE, top: '-9999px', display: 'block' // #833 }); if (clone.style.setProperty) { // #2631 clone.style.setProperty('display', 'block', 'important'); } doc.body.appendChild(clone); if (container) { clone.appendChild(container); } } }, /** * Get the containing element, determine the size and create the inner container * div to hold the chart */ getContainer: function () { var chart = this, container, optionsChart = chart.options.chart, chartWidth, chartHeight, renderTo, indexAttrName = 'data-highcharts-chart', oldChartIndex, containerId; chart.renderTo = renderTo = optionsChart.renderTo; containerId = PREFIX + idCounter++; if (isString(renderTo)) { chart.renderTo = renderTo = doc.getElementById(renderTo); } // Display an error if the renderTo is wrong if (!renderTo) { error(13, true); } // If the container already holds a chart, destroy it. The check for hasRendered is there // because web pages that are saved to disk from the browser, will preserve the data-highcharts-chart // attribute and the SVG contents, but not an interactive chart. So in this case, // charts[oldChartIndex] will point to the wrong chart if any (#2609). oldChartIndex = pInt(attr(renderTo, indexAttrName)); if (!isNaN(oldChartIndex) && charts[oldChartIndex] && charts[oldChartIndex].hasRendered) { charts[oldChartIndex].destroy(); } // Make a reference to the chart from the div attr(renderTo, indexAttrName, chart.index); // remove previous chart renderTo.innerHTML = ''; // If the container doesn't have an offsetWidth, it has or is a child of a node // that has display:none. We need to temporarily move it out to a visible // state to determine the size, else the legend and tooltips won't render // properly. The allowClone option is used in sparklines as a micro optimization, // saving about 1-2 ms each chart. if (!optionsChart.skipClone && !renderTo.offsetWidth) { chart.cloneRenderTo(); } // get the width and height chart.getChartSize(); chartWidth = chart.chartWidth; chartHeight = chart.chartHeight; // create the inner container chart.container = container = createElement(DIV, { className: PREFIX + 'container' + (optionsChart.className ? ' ' + optionsChart.className : ''), id: containerId }, extend({ position: RELATIVE, overflow: HIDDEN, // needed for context menu (avoid scrollbars) and // content overflow in IE width: chartWidth + PX, height: chartHeight + PX, textAlign: 'left', lineHeight: 'normal', // #427 zIndex: 0, // #1072 '-webkit-tap-highlight-color': 'rgba(0,0,0,0)' }, optionsChart.style), chart.renderToClone || renderTo ); // cache the cursor (#1650) chart._cursor = container.style.cursor; // Initialize the renderer chart.renderer = optionsChart.forExport ? // force SVG, used for SVG export new SVGRenderer(container, chartWidth, chartHeight, optionsChart.style, true) : new Renderer(container, chartWidth, chartHeight, optionsChart.style); if (useCanVG) { // If we need canvg library, extend and configure the renderer // to get the tracker for translating mouse events chart.renderer.create(chart, container, chartWidth, chartHeight); } }, /** * Calculate margins by rendering axis labels in a preliminary position. Title, * subtitle and legend have already been rendered at this stage, but will be * moved into their final positions */ getMargins: function () { var chart = this, spacing = chart.spacing, axisOffset, legend = chart.legend, margin = chart.margin, legendOptions = chart.options.legend, legendMargin = pick(legendOptions.margin, 20), legendX = legendOptions.x, legendY = legendOptions.y, align = legendOptions.align, verticalAlign = legendOptions.verticalAlign, titleOffset = chart.titleOffset; chart.resetMargins(); axisOffset = chart.axisOffset; // Adjust for title and subtitle if (titleOffset && !defined(margin[0])) { chart.plotTop = mathMax(chart.plotTop, titleOffset + chart.options.title.margin + spacing[0]); } // Adjust for legend if (legend.display && !legendOptions.floating) { if (align === 'right') { // horizontal alignment handled first if (!defined(margin[1])) { chart.marginRight = mathMax( chart.marginRight, legend.legendWidth - legendX + legendMargin + spacing[1] ); } } else if (align === 'left') { if (!defined(margin[3])) { chart.plotLeft = mathMax( chart.plotLeft, legend.legendWidth + legendX + legendMargin + spacing[3] ); } } else if (verticalAlign === 'top') { if (!defined(margin[0])) { chart.plotTop = mathMax( chart.plotTop, legend.legendHeight + legendY + legendMargin + spacing[0] ); } } else if (verticalAlign === 'bottom') { if (!defined(margin[2])) { chart.marginBottom = mathMax( chart.marginBottom, legend.legendHeight - legendY + legendMargin + spacing[2] ); } } } // adjust for scroller if (chart.extraBottomMargin) { chart.marginBottom += chart.extraBottomMargin; } if (chart.extraTopMargin) { chart.plotTop += chart.extraTopMargin; } // pre-render axes to get labels offset width if (chart.hasCartesianSeries) { each(chart.axes, function (axis) { axis.getOffset(); }); } if (!defined(margin[3])) { chart.plotLeft += axisOffset[3]; } if (!defined(margin[0])) { chart.plotTop += axisOffset[0]; } if (!defined(margin[2])) { chart.marginBottom += axisOffset[2]; } if (!defined(margin[1])) { chart.marginRight += axisOffset[1]; } chart.setChartSize(); }, /** * Resize the chart to its container if size is not explicitly set */ reflow: function (e) { var chart = this, optionsChart = chart.options.chart, renderTo = chart.renderTo, width = optionsChart.width || adapterRun(renderTo, 'width'), height = optionsChart.height || adapterRun(renderTo, 'height'), target = e ? e.target : win, // #805 - MooTools doesn't supply e doReflow = function () { if (chart.container) { // It may have been destroyed in the meantime (#1257) chart.setSize(width, height, false); chart.hasUserSize = null; } }; // Width and height checks for display:none. Target is doc in IE8 and Opera, // win in Firefox, Chrome and IE9. if (!chart.hasUserSize && width && height && (target === win || target === doc)) { if (width !== chart.containerWidth || height !== chart.containerHeight) { clearTimeout(chart.reflowTimeout); if (e) { // Called from window.resize chart.reflowTimeout = setTimeout(doReflow, 100); } else { // Called directly (#2224) doReflow(); } } chart.containerWidth = width; chart.containerHeight = height; } }, /** * Add the event handlers necessary for auto resizing */ initReflow: function () { var chart = this, reflow = function (e) { chart.reflow(e); }; addEvent(win, 'resize', reflow); addEvent(chart, 'destroy', function () { removeEvent(win, 'resize', reflow); }); }, /** * Resize the chart to a given width and height * @param {Number} width * @param {Number} height * @param {Object|Boolean} animation */ setSize: function (width, height, animation) { var chart = this, chartWidth, chartHeight, fireEndResize; // Handle the isResizing counter chart.isResizing += 1; fireEndResize = function () { if (chart) { fireEvent(chart, 'endResize', null, function () { chart.isResizing -= 1; }); } }; // set the animation for the current process setAnimation(animation, chart); chart.oldChartHeight = chart.chartHeight; chart.oldChartWidth = chart.chartWidth; if (defined(width)) { chart.chartWidth = chartWidth = mathMax(0, mathRound(width)); chart.hasUserSize = !!chartWidth; } if (defined(height)) { chart.chartHeight = chartHeight = mathMax(0, mathRound(height)); } // Resize the container with the global animation applied if enabled (#2503) (globalAnimation ? animate : css)(chart.container, { width: chartWidth + PX, height: chartHeight + PX }, globalAnimation); chart.setChartSize(true); chart.renderer.setSize(chartWidth, chartHeight, animation); // handle axes chart.maxTicks = null; each(chart.axes, function (axis) { axis.isDirty = true; axis.setScale(); }); // make sure non-cartesian series are also handled each(chart.series, function (serie) { serie.isDirty = true; }); chart.isDirtyLegend = true; // force legend redraw chart.isDirtyBox = true; // force redraw of plot and chart border chart.layOutTitles(); // #2857 chart.getMargins(); chart.redraw(animation); chart.oldChartHeight = null; fireEvent(chart, 'resize'); // fire endResize and set isResizing back // If animation is disabled, fire without delay if (globalAnimation === false) { fireEndResize(); } else { // else set a timeout with the animation duration setTimeout(fireEndResize, (globalAnimation && globalAnimation.duration) || 500); } }, /** * Set the public chart properties. This is done before and after the pre-render * to determine margin sizes */ setChartSize: function (skipAxes) { var chart = this, inverted = chart.inverted, renderer = chart.renderer, chartWidth = chart.chartWidth, chartHeight = chart.chartHeight, optionsChart = chart.options.chart, spacing = chart.spacing, clipOffset = chart.clipOffset, clipX, clipY, plotLeft, plotTop, plotWidth, plotHeight, plotBorderWidth; chart.plotLeft = plotLeft = mathRound(chart.plotLeft); chart.plotTop = plotTop = mathRound(chart.plotTop); chart.plotWidth = plotWidth = mathMax(0, mathRound(chartWidth - plotLeft - chart.marginRight)); chart.plotHeight = plotHeight = mathMax(0, mathRound(chartHeight - plotTop - chart.marginBottom)); chart.plotSizeX = inverted ? plotHeight : plotWidth; chart.plotSizeY = inverted ? plotWidth : plotHeight; chart.plotBorderWidth = optionsChart.plotBorderWidth || 0; // Set boxes used for alignment chart.spacingBox = renderer.spacingBox = { x: spacing[3], y: spacing[0], width: chartWidth - spacing[3] - spacing[1], height: chartHeight - spacing[0] - spacing[2] }; chart.plotBox = renderer.plotBox = { x: plotLeft, y: plotTop, width: plotWidth, height: plotHeight }; plotBorderWidth = 2 * mathFloor(chart.plotBorderWidth / 2); clipX = mathCeil(mathMax(plotBorderWidth, clipOffset[3]) / 2); clipY = mathCeil(mathMax(plotBorderWidth, clipOffset[0]) / 2); chart.clipBox = { x: clipX, y: clipY, width: mathFloor(chart.plotSizeX - mathMax(plotBorderWidth, clipOffset[1]) / 2 - clipX), height: mathMax(0, mathFloor(chart.plotSizeY - mathMax(plotBorderWidth, clipOffset[2]) / 2 - clipY)) }; if (!skipAxes) { each(chart.axes, function (axis) { axis.setAxisSize(); axis.setAxisTranslation(); }); } }, /** * Initial margins before auto size margins are applied */ resetMargins: function () { var chart = this, spacing = chart.spacing, margin = chart.margin; chart.plotTop = pick(margin[0], spacing[0]); chart.marginRight = pick(margin[1], spacing[1]); chart.marginBottom = pick(margin[2], spacing[2]); chart.plotLeft = pick(margin[3], spacing[3]); chart.axisOffset = [0, 0, 0, 0]; // top, right, bottom, left chart.clipOffset = [0, 0, 0, 0]; }, /** * Draw the borders and backgrounds for chart and plot area */ drawChartBox: function () { var chart = this, optionsChart = chart.options.chart, renderer = chart.renderer, chartWidth = chart.chartWidth, chartHeight = chart.chartHeight, chartBackground = chart.chartBackground, plotBackground = chart.plotBackground, plotBorder = chart.plotBorder, plotBGImage = chart.plotBGImage, chartBorderWidth = optionsChart.borderWidth || 0, chartBackgroundColor = optionsChart.backgroundColor, plotBackgroundColor = optionsChart.plotBackgroundColor, plotBackgroundImage = optionsChart.plotBackgroundImage, plotBorderWidth = optionsChart.plotBorderWidth || 0, mgn, bgAttr, plotLeft = chart.plotLeft, plotTop = chart.plotTop, plotWidth = chart.plotWidth, plotHeight = chart.plotHeight, plotBox = chart.plotBox, clipRect = chart.clipRect, clipBox = chart.clipBox; // Chart area mgn = chartBorderWidth + (optionsChart.shadow ? 8 : 0); if (chartBorderWidth || chartBackgroundColor) { if (!chartBackground) { bgAttr = { fill: chartBackgroundColor || NONE }; if (chartBorderWidth) { // #980 bgAttr.stroke = optionsChart.borderColor; bgAttr['stroke-width'] = chartBorderWidth; } chart.chartBackground = renderer.rect(mgn / 2, mgn / 2, chartWidth - mgn, chartHeight - mgn, optionsChart.borderRadius, chartBorderWidth) .attr(bgAttr) .addClass(PREFIX + 'background') .add() .shadow(optionsChart.shadow); } else { // resize chartBackground.animate( chartBackground.crisp({ width: chartWidth - mgn, height: chartHeight - mgn }) ); } } // Plot background if (plotBackgroundColor) { if (!plotBackground) { chart.plotBackground = renderer.rect(plotLeft, plotTop, plotWidth, plotHeight, 0) .attr({ fill: plotBackgroundColor }) .add() .shadow(optionsChart.plotShadow); } else { plotBackground.animate(plotBox); } } if (plotBackgroundImage) { if (!plotBGImage) { chart.plotBGImage = renderer.image(plotBackgroundImage, plotLeft, plotTop, plotWidth, plotHeight) .add(); } else { plotBGImage.animate(plotBox); } } // Plot clip if (!clipRect) { chart.clipRect = renderer.clipRect(clipBox); } else { clipRect.animate({ width: clipBox.width, height: clipBox.height }); } // Plot area border if (plotBorderWidth) { if (!plotBorder) { chart.plotBorder = renderer.rect(plotLeft, plotTop, plotWidth, plotHeight, 0, -plotBorderWidth) .attr({ stroke: optionsChart.plotBorderColor, 'stroke-width': plotBorderWidth, fill: NONE, zIndex: 1 }) .add(); } else { plotBorder.animate( plotBorder.crisp({ x: plotLeft, y: plotTop, width: plotWidth, height: plotHeight, strokeWidth: -plotBorderWidth }) //#3282 plotBorder should be negative ); } } // reset chart.isDirtyBox = false; }, /** * Detect whether a certain chart property is needed based on inspecting its options * and series. This mainly applies to the chart.invert property, and in extensions to * the chart.angular and chart.polar properties. */ propFromSeries: function () { var chart = this, optionsChart = chart.options.chart, klass, seriesOptions = chart.options.series, i, value; each(['inverted', 'angular', 'polar'], function (key) { // The default series type's class klass = seriesTypes[optionsChart.type || optionsChart.defaultSeriesType]; // Get the value from available chart-wide properties value = ( chart[key] || // 1. it is set before optionsChart[key] || // 2. it is set in the options (klass && klass.prototype[key]) // 3. it's default series class requires it ); // 4. Check if any the chart's series require it i = seriesOptions && seriesOptions.length; while (!value && i--) { klass = seriesTypes[seriesOptions[i].type]; if (klass && klass.prototype[key]) { value = true; } } // Set the chart property chart[key] = value; }); }, /** * Link two or more series together. This is done initially from Chart.render, * and after Chart.addSeries and Series.remove. */ linkSeries: function () { var chart = this, chartSeries = chart.series; // Reset links each(chartSeries, function (series) { series.linkedSeries.length = 0; }); // Apply new links each(chartSeries, function (series) { var linkedTo = series.options.linkedTo; if (isString(linkedTo)) { if (linkedTo === ':previous') { linkedTo = chart.series[series.index - 1]; } else { linkedTo = chart.get(linkedTo); } if (linkedTo) { linkedTo.linkedSeries.push(series); series.linkedParent = linkedTo; } } }); }, /** * Render series for the chart */ renderSeries: function () { each(this.series, function (serie) { serie.translate(); if (serie.setTooltipPoints) { serie.setTooltipPoints(); } serie.render(); }); }, /** * Render labels for the chart */ renderLabels: function () { var chart = this, labels = chart.options.labels; if (labels.items) { each(labels.items, function (label) { var style = extend(labels.style, label.style), x = pInt(style.left) + chart.plotLeft, y = pInt(style.top) + chart.plotTop + 12; // delete to prevent rewriting in IE delete style.left; delete style.top; chart.renderer.text( label.html, x, y ) .attr({ zIndex: 2 }) .css(style) .add(); }); } }, /** * Render all graphics for the chart */ render: function () { var chart = this, axes = chart.axes, renderer = chart.renderer, options = chart.options; // Title chart.setTitle(); // Legend chart.legend = new Legend(chart, options.legend); chart.getStacks(); // render stacks // Get margins by pre-rendering axes // set axes scales each(axes, function (axis) { axis.setScale(); }); chart.getMargins(); chart.maxTicks = null; // reset for second pass each(axes, function (axis) { axis.setTickPositions(true); // update to reflect the new margins axis.setMaxTicks(); }); chart.adjustTickAmounts(); chart.getMargins(); // second pass to check for new labels // Draw the borders and backgrounds chart.drawChartBox(); // Axes if (chart.hasCartesianSeries) { each(axes, function (axis) { axis.render(); }); } // The series if (!chart.seriesGroup) { chart.seriesGroup = renderer.g('series-group') .attr({ zIndex: 3 }) .add(); } chart.renderSeries(); // Labels chart.renderLabels(); // Credits chart.showCredits(options.credits); // Set flag chart.hasRendered = true; }, /** * Show chart credits based on config options */ showCredits: function (credits) { if (credits.enabled && !this.credits) { this.credits = this.renderer.text( credits.text, 0, 0 ) .on('click', function () { if (credits.href) { location.href = credits.href; } }) .attr({ align: credits.position.align, zIndex: 8 }) .css(credits.style) .add() .align(credits.position); } }, /** * Clean up memory usage */ destroy: function () { var chart = this, axes = chart.axes, series = chart.series, container = chart.container, i, parentNode = container && container.parentNode; // fire the chart.destoy event fireEvent(chart, 'destroy'); // Delete the chart from charts lookup array charts[chart.index] = UNDEFINED; chartCount--; chart.renderTo.removeAttribute('data-highcharts-chart'); // remove events removeEvent(chart); // ==== Destroy collections: // Destroy axes i = axes.length; while (i--) { axes[i] = axes[i].destroy(); } // Destroy each series i = series.length; while (i--) { series[i] = series[i].destroy(); } // ==== Destroy chart properties: each(['title', 'subtitle', 'chartBackground', 'plotBackground', 'plotBGImage', 'plotBorder', 'seriesGroup', 'clipRect', 'credits', 'pointer', 'scroller', 'rangeSelector', 'legend', 'resetZoomButton', 'tooltip', 'renderer'], function (name) { var prop = chart[name]; if (prop && prop.destroy) { chart[name] = prop.destroy(); } }); // remove container and all SVG if (container) { // can break in IE when destroyed before finished loading container.innerHTML = ''; removeEvent(container); if (parentNode) { discardElement(container); } } // clean it all up for (i in chart) { delete chart[i]; } }, /** * VML namespaces can't be added until after complete. Listening * for Perini's doScroll hack is not enough. */ isReadyToRender: function () { var chart = this; // Note: in spite of JSLint's complaints, win == win.top is required /*jslint eqeq: true*/ if ((!hasSVG && (win == win.top && doc.readyState !== 'complete')) || (useCanVG && !win.canvg)) { /*jslint eqeq: false*/ if (useCanVG) { // Delay rendering until canvg library is downloaded and ready CanVGController.push(function () { chart.firstRender(); }, chart.options.global.canvasToolsURL); } else { doc.attachEvent('onreadystatechange', function () { doc.detachEvent('onreadystatechange', chart.firstRender); if (doc.readyState === 'complete') { chart.firstRender(); } }); } return false; } return true; }, /** * Prepare for first rendering after all data are loaded */ firstRender: function () { var chart = this, options = chart.options, callback = chart.callback; // Check whether the chart is ready to render if (!chart.isReadyToRender()) { return; } // Create the container chart.getContainer(); // Run an early event after the container and renderer are established fireEvent(chart, 'init'); chart.resetMargins(); chart.setChartSize(); // Set the common chart properties (mainly invert) from the given series chart.propFromSeries(); // get axes chart.getAxes(); // Initialize the series each(options.series || [], function (serieOptions) { chart.initSeries(serieOptions); }); chart.linkSeries(); // Run an event after axes and series are initialized, but before render. At this stage, // the series data is indexed and cached in the xData and yData arrays, so we can access // those before rendering. Used in Highstock. fireEvent(chart, 'beforeRender'); // depends on inverted and on margins being set if (Highcharts.Pointer) { chart.pointer = new Pointer(chart, options); } chart.render(); // add canvas chart.renderer.draw(); // run callbacks if (callback) { callback.apply(chart, [chart]); } each(chart.callbacks, function (fn) { fn.apply(chart, [chart]); }); // If the chart was rendered outside the top container, put it back in chart.cloneRenderTo(true); fireEvent(chart, 'load'); }, /** * Creates arrays for spacing and margin from given options. */ splashArray: function (target, options) { var oVar = options[target], tArray = isObject(oVar) ? oVar : [oVar, oVar, oVar, oVar]; return [pick(options[target + 'Top'], tArray[0]), pick(options[target + 'Right'], tArray[1]), pick(options[target + 'Bottom'], tArray[2]), pick(options[target + 'Left'], tArray[3])]; } }; // end Chart // Hook for exporting module Chart.prototype.callbacks = []; /** * The Point object and prototype. Inheritable and used as base for PiePoint */ var Point = function () {}; Point.prototype = { /** * Initialize the point * @param {Object} series The series object containing this point * @param {Object} options The data in either number, array or object format */ init: function (series, options, x) { var point = this, colors; point.series = series; point.applyOptions(options, x); point.pointAttr = {}; if (series.options.colorByPoint) { colors = series.options.colors || series.chart.options.colors; point.color = point.color || colors[series.colorCounter++]; // loop back to zero if (series.colorCounter === colors.length) { series.colorCounter = 0; } } series.chart.pointCount++; return point; }, /** * Apply the options containing the x and y data and possible some extra properties. * This is called on point init or from point.update. * * @param {Object} options */ applyOptions: function (options, x) { var point = this, series = point.series, pointValKey = series.options.pointValKey || series.pointValKey; options = Point.prototype.optionsToObject.call(this, options); // copy options directly to point extend(point, options); point.options = point.options ? extend(point.options, options) : options; // For higher dimension series types. For instance, for ranges, point.y is mapped to point.low. if (pointValKey) { point.y = point[pointValKey]; } // If no x is set by now, get auto incremented value. All points must have an // x value, however the y value can be null to create a gap in the series if (point.x === UNDEFINED && series) { point.x = x === UNDEFINED ? series.autoIncrement() : x; } return point; }, /** * Transform number or array configs into objects */ optionsToObject: function (options) { var ret = {}, series = this.series, pointArrayMap = series.pointArrayMap || ['y'], valueCount = pointArrayMap.length, firstItemType, i = 0, j = 0; if (typeof options === 'number' || options === null) { ret[pointArrayMap[0]] = options; } else if (isArray(options)) { // with leading x value if (options.length > valueCount) { firstItemType = typeof options[0]; if (firstItemType === 'string') { ret.name = options[0]; } else if (firstItemType === 'number') { ret.x = options[0]; } i++; } while (j < valueCount) { ret[pointArrayMap[j++]] = options[i++]; } } else if (typeof options === 'object') { ret = options; // This is the fastest way to detect if there are individual point dataLabels that need // to be considered in drawDataLabels. These can only occur in object configs. if (options.dataLabels) { series._hasPointLabels = true; } // Same approach as above for markers if (options.marker) { series._hasPointMarkers = true; } } return ret; }, /** * Destroy a point to clear memory. Its reference still stays in series.data. */ destroy: function () { var point = this, series = point.series, chart = series.chart, hoverPoints = chart.hoverPoints, prop; chart.pointCount--; if (hoverPoints) { point.setState(); erase(hoverPoints, point); if (!hoverPoints.length) { chart.hoverPoints = null; } } if (point === chart.hoverPoint) { point.onMouseOut(); } // remove all events if (point.graphic || point.dataLabel) { // removeEvent and destroyElements are performance expensive removeEvent(point); point.destroyElements(); } if (point.legendItem) { // pies have legend items chart.legend.destroyItem(point); } for (prop in point) { point[prop] = null; } }, /** * Destroy SVG elements associated with the point */ destroyElements: function () { var point = this, props = ['graphic', 'dataLabel', 'dataLabelUpper', 'group', 'connector', 'shadowGroup'], prop, i = 6; while (i--) { prop = props[i]; if (point[prop]) { point[prop] = point[prop].destroy(); } } }, /** * Return the configuration hash needed for the data label and tooltip formatters */ getLabelConfig: function () { var point = this; return { x: point.category, y: point.y, key: point.name || point.category, series: point.series, point: point, percentage: point.percentage, total: point.total || point.stackTotal }; }, /** * Extendable method for formatting each point's tooltip line * * @return {String} A string to be concatenated in to the common tooltip text */ tooltipFormatter: function (pointFormat) { // Insert options for valueDecimals, valuePrefix, and valueSuffix var series = this.series, seriesTooltipOptions = series.tooltipOptions, valueDecimals = pick(seriesTooltipOptions.valueDecimals, ''), valuePrefix = seriesTooltipOptions.valuePrefix || '', valueSuffix = seriesTooltipOptions.valueSuffix || ''; // Loop over the point array map and replace unformatted values with sprintf formatting markup each(series.pointArrayMap || ['y'], function (key) { key = '{point.' + key; // without the closing bracket if (valuePrefix || valueSuffix) { pointFormat = pointFormat.replace(key + '}', valuePrefix + key + '}' + valueSuffix); } pointFormat = pointFormat.replace(key + '}', key + ':,.' + valueDecimals + 'f}'); }); return format(pointFormat, { point: this, series: this.series }); }, /** * Fire an event on the Point object. Must not be renamed to fireEvent, as this * causes a name clash in MooTools * @param {String} eventType * @param {Object} eventArgs Additional event arguments * @param {Function} defaultFunction Default event handler */ firePointEvent: function (eventType, eventArgs, defaultFunction) { var point = this, series = this.series, seriesOptions = series.options; // load event handlers on demand to save time on mouseover/out if (seriesOptions.point.events[eventType] || (point.options && point.options.events && point.options.events[eventType])) { this.importEvents(); } // add default handler if in selection mode if (eventType === 'click' && seriesOptions.allowPointSelect) { defaultFunction = function (event) { // Control key is for Windows, meta (= Cmd key) for Mac, Shift for Opera point.select(null, event.ctrlKey || event.metaKey || event.shiftKey); }; } fireEvent(this, eventType, eventArgs, defaultFunction); } };/** * @classDescription The base function which all other series types inherit from. The data in the series is stored * in various arrays. * * - First, series.options.data contains all the original config options for * each point whether added by options or methods like series.addPoint. * - Next, series.data contains those values converted to points, but in case the series data length * exceeds the cropThreshold, or if the data is grouped, series.data doesn't contain all the points. It * only contains the points that have been created on demand. * - Then there's series.points that contains all currently visible point objects. In case of cropping, * the cropped-away points are not part of this array. The series.points array starts at series.cropStart * compared to series.data and series.options.data. If however the series data is grouped, these can't * be correlated one to one. * - series.xData and series.processedXData contain clean x values, equivalent to series.data and series.points. * - series.yData and series.processedYData contain clean x values, equivalent to series.data and series.points. * * @param {Object} chart * @param {Object} options */ var Series = function () {}; Series.prototype = { isCartesian: true, type: 'line', pointClass: Point, sorted: true, // requires the data to be sorted requireSorting: true, pointAttrToOptions: { // mapping between SVG attributes and the corresponding options stroke: 'lineColor', 'stroke-width': 'lineWidth', fill: 'fillColor', r: 'radius' }, axisTypes: ['xAxis', 'yAxis'], colorCounter: 0, parallelArrays: ['x', 'y'], // each point's x and y values are stored in this.xData and this.yData init: function (chart, options) { var series = this, eventType, events, chartSeries = chart.series, sortByIndex = function (a, b) { return pick(a.options.index, a._i) - pick(b.options.index, b._i); }; series.chart = chart; series.options = options = series.setOptions(options); // merge with plotOptions series.linkedSeries = []; // bind the axes series.bindAxes(); // set some variables extend(series, { name: options.name, state: NORMAL_STATE, pointAttr: {}, visible: options.visible !== false, // true by default selected: options.selected === true // false by default }); // special if (useCanVG) { options.animation = false; } // register event listeners events = options.events; for (eventType in events) { addEvent(series, eventType, events[eventType]); } if ( (events && events.click) || (options.point && options.point.events && options.point.events.click) || options.allowPointSelect ) { chart.runTrackerClick = true; } series.getColor(); series.getSymbol(); // Set the data each(series.parallelArrays, function (key) { series[key + 'Data'] = []; }); series.setData(options.data, false); // Mark cartesian if (series.isCartesian) { chart.hasCartesianSeries = true; } // Register it in the chart chartSeries.push(series); series._i = chartSeries.length - 1; // Sort series according to index option (#248, #1123, #2456) stableSort(chartSeries, sortByIndex); if (this.yAxis) { stableSort(this.yAxis.series, sortByIndex); } each(chartSeries, function (series, i) { series.index = i; series.name = series.name || 'Series ' + (i + 1); }); }, /** * Set the xAxis and yAxis properties of cartesian series, and register the series * in the axis.series array */ bindAxes: function () { var series = this, seriesOptions = series.options, chart = series.chart, axisOptions; each(series.axisTypes || [], function (AXIS) { // repeat for xAxis and yAxis each(chart[AXIS], function (axis) { // loop through the chart's axis objects axisOptions = axis.options; // apply if the series xAxis or yAxis option mathches the number of the // axis, or if undefined, use the first axis if ((seriesOptions[AXIS] === axisOptions.index) || (seriesOptions[AXIS] !== UNDEFINED && seriesOptions[AXIS] === axisOptions.id) || (seriesOptions[AXIS] === UNDEFINED && axisOptions.index === 0)) { // register this series in the axis.series lookup axis.series.push(series); // set this series.xAxis or series.yAxis reference series[AXIS] = axis; // mark dirty for redraw axis.isDirty = true; } }); // The series needs an X and an Y axis if (!series[AXIS] && series.optionalAxis !== AXIS) { error(18, true); } }); }, /** * For simple series types like line and column, the data values are held in arrays like * xData and yData for quick lookup to find extremes and more. For multidimensional series * like bubble and map, this can be extended with arrays like zData and valueData by * adding to the series.parallelArrays array. */ updateParallelArrays: function (point, i) { var series = point.series, args = arguments, fn = typeof i === 'number' ? // Insert the value in the given position function (key) { var val = key === 'y' && series.toYData ? series.toYData(point) : point[key]; series[key + 'Data'][i] = val; } : // Apply the method specified in i with the following arguments as arguments function (key) { Array.prototype[i].apply(series[key + 'Data'], Array.prototype.slice.call(args, 2)); }; each(series.parallelArrays, fn); }, /** * Return an auto incremented x value based on the pointStart and pointInterval options. * This is only used if an x value is not given for the point that calls autoIncrement. */ autoIncrement: function () { var series = this, options = series.options, xIncrement = series.xIncrement; xIncrement = pick(xIncrement, options.pointStart, 0); series.pointInterval = pick(series.pointInterval, options.pointInterval, 1); series.xIncrement = xIncrement + series.pointInterval; return xIncrement; }, /** * Divide the series data into segments divided by null values. */ getSegments: function () { var series = this, lastNull = -1, segments = [], i, points = series.points, pointsLength = points.length; if (pointsLength) { // no action required for [] // if connect nulls, just remove null points if (series.options.connectNulls) { i = pointsLength; while (i--) { if (points[i].y === null) { points.splice(i, 1); } } if (points.length) { segments = [points]; } // else, split on null points } else { each(points, function (point, i) { if (point.y === null) { if (i > lastNull + 1) { segments.push(points.slice(lastNull + 1, i)); } lastNull = i; } else if (i === pointsLength - 1) { // last value segments.push(points.slice(lastNull + 1, i + 1)); } }); } } // register it series.segments = segments; }, /** * Set the series options by merging from the options tree * @param {Object} itemOptions */ setOptions: function (itemOptions) { var chart = this.chart, chartOptions = chart.options, plotOptions = chartOptions.plotOptions, userOptions = chart.userOptions || {}, userPlotOptions = userOptions.plotOptions || {}, typeOptions = plotOptions[this.type], options; this.userOptions = itemOptions; options = merge( typeOptions, plotOptions.series, itemOptions ); // The tooltip options are merged between global and series specific options this.tooltipOptions = merge( defaultOptions.tooltip, defaultOptions.plotOptions[this.type].tooltip, userOptions.tooltip, userPlotOptions.series && userPlotOptions.series.tooltip, userPlotOptions[this.type] && userPlotOptions[this.type].tooltip, itemOptions.tooltip ); // Delete marker object if not allowed (#1125) if (typeOptions.marker === null) { delete options.marker; } return options; }, getCyclic: function (prop, value, defaults) { var i, userOptions = this.userOptions, indexName = '_' + prop + 'Index', counterName = prop + 'Counter'; if (!value) { if (defined(userOptions[indexName])) { // after Series.update() i = userOptions[indexName]; } else { userOptions[indexName] = i = this.chart[counterName] % defaults.length; this.chart[counterName] += 1; } value = defaults[i]; } this[prop] = value; }, /** * Get the series' color */ getColor: function () { if (!this.options.colorByPoint) { this.getCyclic('color', this.options.color || defaultPlotOptions[this.type].color, this.chart.options.colors); } }, /** * Get the series' symbol */ getSymbol: function () { var seriesMarkerOption = this.options.marker; this.getCyclic('symbol', seriesMarkerOption.symbol, this.chart.options.symbols); // don't substract radius in image symbols (#604) if (/^url/.test(this.symbol)) { seriesMarkerOption.radius = 0; } }, drawLegendSymbol: LegendSymbolMixin.drawLineMarker, /** * Replace the series data with a new set of data * @param {Object} data * @param {Object} redraw */ setData: function (data, redraw, animation, updatePoints) { var series = this, oldData = series.points, oldDataLength = (oldData && oldData.length) || 0, dataLength, options = series.options, chart = series.chart, firstPoint = null, xAxis = series.xAxis, hasCategories = xAxis && !!xAxis.categories, tooltipPoints = series.tooltipPoints, i, turboThreshold = options.turboThreshold, pt, xData = this.xData, yData = this.yData, pointArrayMap = series.pointArrayMap, valueCount = pointArrayMap && pointArrayMap.length; data = data || []; dataLength = data.length; redraw = pick(redraw, true); // If the point count is the same as is was, just run Point.update which is // cheaper, allows animation, and keeps references to points. if (updatePoints !== false && dataLength && oldDataLength === dataLength && !series.cropped && !series.hasGroupedData) { each(data, function (point, i) { oldData[i].update(point, false, null, false); }); } else { // Reset properties series.xIncrement = null; series.pointRange = hasCategories ? 1 : options.pointRange; series.colorCounter = 0; // for series with colorByPoint (#1547) // Update parallel arrays each(this.parallelArrays, function (key) { series[key + 'Data'].length = 0; }); // In turbo mode, only one- or twodimensional arrays of numbers are allowed. The // first value is tested, and we assume that all the rest are defined the same // way. Although the 'for' loops are similar, they are repeated inside each // if-else conditional for max performance. if (turboThreshold && dataLength > turboThreshold) { // find the first non-null point i = 0; while (firstPoint === null && i < dataLength) { firstPoint = data[i]; i++; } if (isNumber(firstPoint)) { // assume all points are numbers var x = pick(options.pointStart, 0), pointInterval = pick(options.pointInterval, 1); for (i = 0; i < dataLength; i++) { xData[i] = x; yData[i] = data[i]; x += pointInterval; } series.xIncrement = x; } else if (isArray(firstPoint)) { // assume all points are arrays if (valueCount) { // [x, low, high] or [x, o, h, l, c] for (i = 0; i < dataLength; i++) { pt = data[i]; xData[i] = pt[0]; yData[i] = pt.slice(1, valueCount + 1); } } else { // [x, y] for (i = 0; i < dataLength; i++) { pt = data[i]; xData[i] = pt[0]; yData[i] = pt[1]; } } } else { error(12); // Highcharts expects configs to be numbers or arrays in turbo mode } } else { for (i = 0; i < dataLength; i++) { if (data[i] !== UNDEFINED) { // stray commas in oldIE pt = { series: series }; series.pointClass.prototype.applyOptions.apply(pt, [data[i]]); series.updateParallelArrays(pt, i); if (hasCategories && pt.name) { xAxis.names[pt.x] = pt.name; // #2046 } } } } // Forgetting to cast strings to numbers is a common caveat when handling CSV or JSON if (isString(yData[0])) { error(14, true); } series.data = []; series.options.data = data; //series.zData = zData; // destroy old points i = oldDataLength; while (i--) { if (oldData[i] && oldData[i].destroy) { oldData[i].destroy(); } } if (tooltipPoints) { // #2594 tooltipPoints.length = 0; } // reset minRange (#878) if (xAxis) { xAxis.minRange = xAxis.userMinRange; } // redraw series.isDirty = series.isDirtyData = chart.isDirtyBox = true; animation = false; } if (redraw) { chart.redraw(animation); } }, /** * Process the data by cropping away unused data points if the series is longer * than the crop threshold. This saves computing time for lage series. */ processData: function (force) { var series = this, processedXData = series.xData, // copied during slice operation below processedYData = series.yData, dataLength = processedXData.length, croppedData, cropStart = 0, cropped, distance, closestPointRange, xAxis = series.xAxis, i, // loop variable options = series.options, cropThreshold = options.cropThreshold, activePointCount = 0, isCartesian = series.isCartesian, xExtremes, min, max; // If the series data or axes haven't changed, don't go through this. Return false to pass // the message on to override methods like in data grouping. if (isCartesian && !series.isDirty && !xAxis.isDirty && !series.yAxis.isDirty && !force) { return false; } if (xAxis) { xExtremes = xAxis.getExtremes(); // corrected for log axis (#3053) min = xExtremes.min; max = xExtremes.max; } // optionally filter out points outside the plot area if (isCartesian && series.sorted && (!cropThreshold || dataLength > cropThreshold || series.forceCrop)) { // it's outside current extremes if (processedXData[dataLength - 1] < min || processedXData[0] > max) { processedXData = []; processedYData = []; // only crop if it's actually spilling out } else if (processedXData[0] < min || processedXData[dataLength - 1] > max) { croppedData = this.cropData(series.xData, series.yData, min, max); processedXData = croppedData.xData; processedYData = croppedData.yData; cropStart = croppedData.start; cropped = true; activePointCount = processedXData.length; } } // Find the closest distance between processed points for (i = processedXData.length - 1; i >= 0; i--) { distance = processedXData[i] - processedXData[i - 1]; if (!cropped && processedXData[i] > min && processedXData[i] < max) { activePointCount++; } if (distance > 0 && (closestPointRange === UNDEFINED || distance < closestPointRange)) { closestPointRange = distance; // Unsorted data is not supported by the line tooltip, as well as data grouping and // navigation in Stock charts (#725) and width calculation of columns (#1900) } else if (distance < 0 && series.requireSorting) { error(15); } } // Record the properties series.cropped = cropped; // undefined or true series.cropStart = cropStart; series.processedXData = processedXData; series.processedYData = processedYData; series.activePointCount = activePointCount; if (options.pointRange === null) { // null means auto, as for columns, candlesticks and OHLC series.pointRange = closestPointRange || 1; } series.closestPointRange = closestPointRange; }, /** * Iterate over xData and crop values between min and max. Returns object containing crop start/end * cropped xData with corresponding part of yData, dataMin and dataMax within the cropped range */ cropData: function (xData, yData, min, max) { var dataLength = xData.length, cropStart = 0, cropEnd = dataLength, cropShoulder = pick(this.cropShoulder, 1), // line-type series need one point outside i; // iterate up to find slice start for (i = 0; i < dataLength; i++) { if (xData[i] >= min) { cropStart = mathMax(0, i - cropShoulder); break; } } // proceed to find slice end for (; i < dataLength; i++) { if (xData[i] > max) { cropEnd = i + cropShoulder; break; } } return { xData: xData.slice(cropStart, cropEnd), yData: yData.slice(cropStart, cropEnd), start: cropStart, end: cropEnd }; }, /** * Generate the data point after the data has been processed by cropping away * unused points and optionally grouped in Highcharts Stock. */ generatePoints: function () { var series = this, options = series.options, dataOptions = options.data, data = series.data, dataLength, processedXData = series.processedXData, processedYData = series.processedYData, pointClass = series.pointClass, processedDataLength = processedXData.length, cropStart = series.cropStart || 0, cursor, hasGroupedData = series.hasGroupedData, point, points = [], i; if (!data && !hasGroupedData) { var arr = []; arr.length = dataOptions.length; data = series.data = arr; } for (i = 0; i < processedDataLength; i++) { cursor = cropStart + i; if (!hasGroupedData) { if (data[cursor]) { point = data[cursor]; } else if (dataOptions[cursor] !== UNDEFINED) { // #970 data[cursor] = point = (new pointClass()).init(series, dataOptions[cursor], processedXData[i]); } points[i] = point; } else { // splat the y data in case of ohlc data array points[i] = (new pointClass()).init(series, [processedXData[i]].concat(splat(processedYData[i]))); } points[i].index = cursor; // For faster access in Point.update } // Hide cropped-away points - this only runs when the number of points is above cropThreshold, or when // swithching view from non-grouped data to grouped data (#637) if (data && (processedDataLength !== (dataLength = data.length) || hasGroupedData)) { for (i = 0; i < dataLength; i++) { if (i === cropStart && !hasGroupedData) { // when has grouped data, clear all points i += processedDataLength; } if (data[i]) { data[i].destroyElements(); data[i].plotX = UNDEFINED; // #1003 } } } series.data = data; series.points = points; }, /** * Calculate Y extremes for visible data */ getExtremes: function (yData) { var xAxis = this.xAxis, yAxis = this.yAxis, xData = this.processedXData, yDataLength, activeYData = [], activeCounter = 0, xExtremes = xAxis.getExtremes(), // #2117, need to compensate for log X axis xMin = xExtremes.min, xMax = xExtremes.max, validValue, withinRange, dataMin, dataMax, x, y, i, j; yData = yData || this.stackedYData || this.processedYData; yDataLength = yData.length; for (i = 0; i < yDataLength; i++) { x = xData[i]; y = yData[i]; // For points within the visible range, including the first point outside the // visible range, consider y extremes validValue = y !== null && y !== UNDEFINED && (!yAxis.isLog || (y.length || y > 0)); withinRange = this.getExtremesFromAll || this.cropped || ((xData[i + 1] || x) >= xMin && (xData[i - 1] || x) <= xMax); if (validValue && withinRange) { j = y.length; if (j) { // array, like ohlc or range data while (j--) { if (y[j] !== null) { activeYData[activeCounter++] = y[j]; } } } else { activeYData[activeCounter++] = y; } } } this.dataMin = pick(dataMin, arrayMin(activeYData)); this.dataMax = pick(dataMax, arrayMax(activeYData)); }, /** * Translate data points from raw data values to chart specific positioning data * needed later in drawPoints, drawGraph and drawTracker. */ translate: function () { if (!this.processedXData) { // hidden series this.processData(); } this.generatePoints(); var series = this, options = series.options, stacking = options.stacking, xAxis = series.xAxis, categories = xAxis.categories, yAxis = series.yAxis, points = series.points, dataLength = points.length, hasModifyValue = !!series.modifyValue, i, pointPlacement = options.pointPlacement, dynamicallyPlaced = pointPlacement === 'between' || isNumber(pointPlacement), threshold = options.threshold; // Translate each point for (i = 0; i < dataLength; i++) { var point = points[i], xValue = point.x, yValue = point.y, yBottom = point.low, stack = stacking && yAxis.stacks[(series.negStacks && yValue < threshold ? '-' : '') + series.stackKey], pointStack, stackValues; // Discard disallowed y values for log axes if (yAxis.isLog && yValue <= 0) { point.y = yValue = null; error(10); } // Get the plotX translation point.plotX = xAxis.translate(xValue, 0, 0, 0, 1, pointPlacement, this.type === 'flags'); // Math.round fixes #591 // Calculate the bottom y value for stacked series if (stacking && series.visible && stack && stack[xValue]) { pointStack = stack[xValue]; stackValues = pointStack.points[series.index + ',' + i]; yBottom = stackValues[0]; yValue = stackValues[1]; if (yBottom === 0) { yBottom = pick(threshold, yAxis.min); } if (yAxis.isLog && yBottom <= 0) { // #1200, #1232 yBottom = null; } point.total = point.stackTotal = pointStack.total; point.percentage = pointStack.total && (point.y / pointStack.total * 100); point.stackY = yValue; // Place the stack label pointStack.setOffset(series.pointXOffset || 0, series.barW || 0); } // Set translated yBottom or remove it point.yBottom = defined(yBottom) ? yAxis.translate(yBottom, 0, 1, 0, 1) : null; // general hook, used for Highstock compare mode if (hasModifyValue) { yValue = series.modifyValue(yValue, point); } // Set the the plotY value, reset it for redraws point.plotY = (typeof yValue === 'number' && yValue !== Infinity) ? //mathRound(yAxis.translate(yValue, 0, 1, 0, 1) * 10) / 10 : // Math.round fixes #591 yAxis.translate(yValue, 0, 1, 0, 1) : UNDEFINED; // Set client related positions for mouse tracking point.clientX = dynamicallyPlaced ? xAxis.translate(xValue, 0, 0, 0, 1) : point.plotX; // #1514 point.negative = point.y < (threshold || 0); // some API data point.category = categories && categories[point.x] !== UNDEFINED ? categories[point.x] : point.x; } // now that we have the cropped data, build the segments series.getSegments(); }, /** * Animate in the series */ animate: function (init) { var series = this, chart = series.chart, renderer = chart.renderer, clipRect, markerClipRect, animation = series.options.animation, clipBox = series.clipBox || chart.clipBox, inverted = chart.inverted, sharedClipKey; // Animation option is set to true if (animation && !isObject(animation)) { animation = defaultPlotOptions[series.type].animation; } sharedClipKey = ['_sharedClip', animation.duration, animation.easing, clipBox.height].join(','); // Initialize the animation. Set up the clipping rectangle. if (init) { // If a clipping rectangle with the same properties is currently present in the chart, use that. clipRect = chart[sharedClipKey]; markerClipRect = chart[sharedClipKey + 'm']; if (!clipRect) { chart[sharedClipKey] = clipRect = renderer.clipRect( extend(clipBox, { width: 0 }) ); chart[sharedClipKey + 'm'] = markerClipRect = renderer.clipRect( -99, // include the width of the first marker inverted ? -chart.plotLeft : -chart.plotTop, 99, inverted ? chart.chartWidth : chart.chartHeight ); } series.group.clip(clipRect); series.markerGroup.clip(markerClipRect); series.sharedClipKey = sharedClipKey; // Run the animation } else { clipRect = chart[sharedClipKey]; if (clipRect) { clipRect.animate({ width: chart.plotSizeX }, animation); } if (chart[sharedClipKey + 'm']) { chart[sharedClipKey + 'm'].animate({ width: chart.plotSizeX + 99 }, animation); } // Delete this function to allow it only once series.animate = null; } }, /** * This runs after animation to land on the final plot clipping */ afterAnimate: function () { var chart = this.chart, sharedClipKey = this.sharedClipKey, group = this.group, clipBox = this.clipBox; if (group && this.options.clip !== false) { if (!sharedClipKey || !clipBox) { group.clip(clipBox ? chart.renderer.clipRect(clipBox) : chart.clipRect); } this.markerGroup.clip(); // no clip } fireEvent(this, 'afterAnimate'); // Remove the shared clipping rectancgle when all series are shown setTimeout(function () { if (sharedClipKey && chart[sharedClipKey]) { if (!clipBox) { chart[sharedClipKey] = chart[sharedClipKey].destroy(); } if (chart[sharedClipKey + 'm']) { chart[sharedClipKey + 'm'] = chart[sharedClipKey + 'm'].destroy(); } } }, 100); }, /** * Draw the markers */ drawPoints: function () { var series = this, pointAttr, points = series.points, chart = series.chart, plotX, plotY, i, point, radius, symbol, isImage, graphic, options = series.options, seriesMarkerOptions = options.marker, seriesPointAttr = series.pointAttr[''], pointMarkerOptions, hasPointMarker, enabled, isInside, markerGroup = series.markerGroup, globallyEnabled = pick( seriesMarkerOptions.enabled, !series.requireSorting || series.activePointCount < (0.5 * series.xAxis.len / seriesMarkerOptions.radius) ); if (seriesMarkerOptions.enabled !== false || series._hasPointMarkers) { i = points.length; while (i--) { point = points[i]; plotX = mathFloor(point.plotX); // #1843 plotY = point.plotY; graphic = point.graphic; pointMarkerOptions = point.marker || {}; hasPointMarker = !!point.marker; enabled = (globallyEnabled && pointMarkerOptions.enabled === UNDEFINED) || pointMarkerOptions.enabled; isInside = chart.isInsidePlot(mathRound(plotX), plotY, chart.inverted); // #1858 // only draw the point if y is defined if (enabled && plotY !== UNDEFINED && !isNaN(plotY) && point.y !== null) { // shortcuts pointAttr = point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE] || seriesPointAttr; radius = pointAttr.r; symbol = pick(pointMarkerOptions.symbol, series.symbol); isImage = symbol.indexOf('url') === 0; if (graphic) { // update graphic[isInside ? 'show' : 'hide'](true) // Since the marker group isn't clipped, each individual marker must be toggled .animate(extend({ x: plotX - radius, y: plotY - radius }, graphic.symbolName ? { // don't apply to image symbols #507 width: 2 * radius, height: 2 * radius } : {})); } else if (isInside && (radius > 0 || isImage)) { point.graphic = graphic = chart.renderer.symbol( symbol, plotX - radius, plotY - radius, 2 * radius, 2 * radius, hasPointMarker ? pointMarkerOptions : seriesMarkerOptions ) .attr(pointAttr) .add(markerGroup); } } else if (graphic) { point.graphic = graphic.destroy(); // #1269 } } } }, /** * Convert state properties from API naming conventions to SVG attributes * * @param {Object} options API options object * @param {Object} base1 SVG attribute object to inherit from * @param {Object} base2 Second level SVG attribute object to inherit from */ convertAttribs: function (options, base1, base2, base3) { var conversion = this.pointAttrToOptions, attr, option, obj = {}; options = options || {}; base1 = base1 || {}; base2 = base2 || {}; base3 = base3 || {}; for (attr in conversion) { option = conversion[attr]; obj[attr] = pick(options[option], base1[attr], base2[attr], base3[attr]); } return obj; }, /** * Get the state attributes. Each series type has its own set of attributes * that are allowed to change on a point's state change. Series wide attributes are stored for * all series, and additionally point specific attributes are stored for all * points with individual marker options. If such options are not defined for the point, * a reference to the series wide attributes is stored in point.pointAttr. */ getAttribs: function () { var series = this, seriesOptions = series.options, normalOptions = defaultPlotOptions[series.type].marker ? seriesOptions.marker : seriesOptions, stateOptions = normalOptions.states, stateOptionsHover = stateOptions[HOVER_STATE], pointStateOptionsHover, seriesColor = series.color, normalDefaults = { stroke: seriesColor, fill: seriesColor }, points = series.points || [], // #927 i, point, seriesPointAttr = [], pointAttr, pointAttrToOptions = series.pointAttrToOptions, hasPointSpecificOptions = series.hasPointSpecificOptions, negativeColor = seriesOptions.negativeColor, defaultLineColor = normalOptions.lineColor, defaultFillColor = normalOptions.fillColor, turboThreshold = seriesOptions.turboThreshold, attr, key; // series type specific modifications if (seriesOptions.marker) { // line, spline, area, areaspline, scatter // if no hover radius is given, default to normal radius + 2 stateOptionsHover.radius = stateOptionsHover.radius || normalOptions.radius + stateOptionsHover.radiusPlus; stateOptionsHover.lineWidth = stateOptionsHover.lineWidth || normalOptions.lineWidth + stateOptionsHover.lineWidthPlus; } else { // column, bar, pie // if no hover color is given, brighten the normal color stateOptionsHover.color = stateOptionsHover.color || Color(stateOptionsHover.color || seriesColor) .brighten(stateOptionsHover.brightness).get(); } // general point attributes for the series normal state seriesPointAttr[NORMAL_STATE] = series.convertAttribs(normalOptions, normalDefaults); // HOVER_STATE and SELECT_STATE states inherit from normal state except the default radius each([HOVER_STATE, SELECT_STATE], function (state) { seriesPointAttr[state] = series.convertAttribs(stateOptions[state], seriesPointAttr[NORMAL_STATE]); }); // set it series.pointAttr = seriesPointAttr; // Generate the point-specific attribute collections if specific point // options are given. If not, create a referance to the series wide point // attributes i = points.length; if (!turboThreshold || i < turboThreshold || hasPointSpecificOptions) { while (i--) { point = points[i]; normalOptions = (point.options && point.options.marker) || point.options; if (normalOptions && normalOptions.enabled === false) { normalOptions.radius = 0; } if (point.negative && negativeColor) { point.color = point.fillColor = negativeColor; } hasPointSpecificOptions = seriesOptions.colorByPoint || point.color; // #868 // check if the point has specific visual options if (point.options) { for (key in pointAttrToOptions) { if (defined(normalOptions[pointAttrToOptions[key]])) { hasPointSpecificOptions = true; } } } // a specific marker config object is defined for the individual point: // create it's own attribute collection if (hasPointSpecificOptions) { normalOptions = normalOptions || {}; pointAttr = []; stateOptions = normalOptions.states || {}; // reassign for individual point pointStateOptionsHover = stateOptions[HOVER_STATE] = stateOptions[HOVER_STATE] || {}; // Handle colors for column and pies if (!seriesOptions.marker) { // column, bar, point // If no hover color is given, brighten the normal color. #1619, #2579 pointStateOptionsHover.color = pointStateOptionsHover.color || (!point.options.color && stateOptionsHover.color) || Color(point.color) .brighten(pointStateOptionsHover.brightness || stateOptionsHover.brightness) .get(); } // normal point state inherits series wide normal state attr = { color: point.color }; // #868 if (!defaultFillColor) { // Individual point color or negative color markers (#2219) attr.fillColor = point.color; } if (!defaultLineColor) { attr.lineColor = point.color; // Bubbles take point color, line markers use white } pointAttr[NORMAL_STATE] = series.convertAttribs(extend(attr, normalOptions), seriesPointAttr[NORMAL_STATE]); // inherit from point normal and series hover pointAttr[HOVER_STATE] = series.convertAttribs( stateOptions[HOVER_STATE], seriesPointAttr[HOVER_STATE], pointAttr[NORMAL_STATE] ); // inherit from point normal and series hover pointAttr[SELECT_STATE] = series.convertAttribs( stateOptions[SELECT_STATE], seriesPointAttr[SELECT_STATE], pointAttr[NORMAL_STATE] ); // no marker config object is created: copy a reference to the series-wide // attribute collection } else { pointAttr = seriesPointAttr; } point.pointAttr = pointAttr; } } }, /** * Clear DOM objects and free up memory */ destroy: function () { var series = this, chart = series.chart, issue134 = /AppleWebKit\/533/.test(userAgent), destroy, i, data = series.data || [], point, prop, axis; // add event hook fireEvent(series, 'destroy'); // remove all events removeEvent(series); // erase from axes each(series.axisTypes || [], function (AXIS) { axis = series[AXIS]; if (axis) { erase(axis.series, series); axis.isDirty = axis.forceRedraw = true; } }); // remove legend items if (series.legendItem) { series.chart.legend.destroyItem(series); } // destroy all points with their elements i = data.length; while (i--) { point = data[i]; if (point && point.destroy) { point.destroy(); } } series.points = null; // Clear the animation timeout if we are destroying the series during initial animation clearTimeout(series.animationTimeout); // destroy all SVGElements associated to the series each(['area', 'graph', 'dataLabelsGroup', 'group', 'markerGroup', 'tracker', 'graphNeg', 'areaNeg', 'posClip', 'negClip'], function (prop) { if (series[prop]) { // issue 134 workaround destroy = issue134 && prop === 'group' ? 'hide' : 'destroy'; series[prop][destroy](); } }); // remove from hoverSeries if (chart.hoverSeries === series) { chart.hoverSeries = null; } erase(chart.series, series); // clear all members for (prop in series) { delete series[prop]; } }, /** * Return the graph path of a segment */ getSegmentPath: function (segment) { var series = this, segmentPath = [], step = series.options.step; // build the segment line each(segment, function (point, i) { var plotX = point.plotX, plotY = point.plotY, lastPoint; if (series.getPointSpline) { // generate the spline as defined in the SplineSeries object segmentPath.push.apply(segmentPath, series.getPointSpline(segment, point, i)); } else { // moveTo or lineTo segmentPath.push(i ? L : M); // step line? if (step && i) { lastPoint = segment[i - 1]; if (step === 'right') { segmentPath.push( lastPoint.plotX, plotY ); } else if (step === 'center') { segmentPath.push( (lastPoint.plotX + plotX) / 2, lastPoint.plotY, (lastPoint.plotX + plotX) / 2, plotY ); } else { segmentPath.push( plotX, lastPoint.plotY ); } } // normal line to next point segmentPath.push( point.plotX, point.plotY ); } }); return segmentPath; }, /** * Get the graph path */ getGraphPath: function () { var series = this, graphPath = [], segmentPath, singlePoints = []; // used in drawTracker // Divide into segments and build graph and area paths each(series.segments, function (segment) { segmentPath = series.getSegmentPath(segment); // add the segment to the graph, or a single point for tracking if (segment.length > 1) { graphPath = graphPath.concat(segmentPath); } else { singlePoints.push(segment[0]); } }); // Record it for use in drawGraph and drawTracker, and return graphPath series.singlePoints = singlePoints; series.graphPath = graphPath; return graphPath; }, /** * Draw the actual graph */ drawGraph: function () { var series = this, options = this.options, props = [['graph', options.lineColor || this.color]], lineWidth = options.lineWidth, dashStyle = options.dashStyle, roundCap = options.linecap !== 'square', graphPath = this.getGraphPath(), negativeColor = options.negativeColor; if (negativeColor) { props.push(['graphNeg', negativeColor]); } // draw the graph each(props, function (prop, i) { var graphKey = prop[0], graph = series[graphKey], attribs; if (graph) { stop(graph); // cancel running animations, #459 graph.animate({ d: graphPath }); } else if (lineWidth && graphPath.length) { // #1487 attribs = { stroke: prop[1], 'stroke-width': lineWidth, fill: NONE, zIndex: 1 // #1069 }; if (dashStyle) { attribs.dashstyle = dashStyle; } else if (roundCap) { attribs['stroke-linecap'] = attribs['stroke-linejoin'] = 'round'; } series[graphKey] = series.chart.renderer.path(graphPath) .attr(attribs) .add(series.group) .shadow(!i && options.shadow); } }); }, /** * Clip the graphs into the positive and negative coloured graphs */ clipNeg: function () { var options = this.options, chart = this.chart, renderer = chart.renderer, negativeColor = options.negativeColor || options.negativeFillColor, translatedThreshold, posAttr, negAttr, graph = this.graph, area = this.area, posClip = this.posClip, negClip = this.negClip, chartWidth = chart.chartWidth, chartHeight = chart.chartHeight, chartSizeMax = mathMax(chartWidth, chartHeight), yAxis = this.yAxis, above, below; if (negativeColor && (graph || area)) { translatedThreshold = mathRound(yAxis.toPixels(options.threshold || 0, true)); if (translatedThreshold < 0) { chartSizeMax -= translatedThreshold; // #2534 } above = { x: 0, y: 0, width: chartSizeMax, height: translatedThreshold }; below = { x: 0, y: translatedThreshold, width: chartSizeMax, height: chartSizeMax }; if (chart.inverted) { above.height = below.y = chart.plotWidth - translatedThreshold; if (renderer.isVML) { above = { x: chart.plotWidth - translatedThreshold - chart.plotLeft, y: 0, width: chartWidth, height: chartHeight }; below = { x: translatedThreshold + chart.plotLeft - chartWidth, y: 0, width: chart.plotLeft + translatedThreshold, height: chartWidth }; } } if (yAxis.reversed) { posAttr = below; negAttr = above; } else { posAttr = above; negAttr = below; } if (posClip) { // update posClip.animate(posAttr); negClip.animate(negAttr); } else { this.posClip = posClip = renderer.clipRect(posAttr); this.negClip = negClip = renderer.clipRect(negAttr); if (graph && this.graphNeg) { graph.clip(posClip); this.graphNeg.clip(negClip); } if (area) { area.clip(posClip); this.areaNeg.clip(negClip); } } } }, /** * Initialize and perform group inversion on series.group and series.markerGroup */ invertGroups: function () { var series = this, chart = series.chart; // Pie, go away (#1736) if (!series.xAxis) { return; } // A fixed size is needed for inversion to work function setInvert() { var size = { width: series.yAxis.len, height: series.xAxis.len }; each(['group', 'markerGroup'], function (groupName) { if (series[groupName]) { series[groupName].attr(size).invert(); } }); } addEvent(chart, 'resize', setInvert); // do it on resize addEvent(series, 'destroy', function () { removeEvent(chart, 'resize', setInvert); }); // Do it now setInvert(); // do it now // On subsequent render and redraw, just do setInvert without setting up events again series.invertGroups = setInvert; }, /** * General abstraction for creating plot groups like series.group, series.dataLabelsGroup and * series.markerGroup. On subsequent calls, the group will only be adjusted to the updated plot size. */ plotGroup: function (prop, name, visibility, zIndex, parent) { var group = this[prop], isNew = !group; // Generate it on first call if (isNew) { this[prop] = group = this.chart.renderer.g(name) .attr({ visibility: visibility, zIndex: zIndex || 0.1 // IE8 needs this }) .add(parent); } // Place it on first and subsequent (redraw) calls group[isNew ? 'attr' : 'animate'](this.getPlotBox()); return group; }, /** * Get the translation and scale for the plot area of this series */ getPlotBox: function () { var chart = this.chart, xAxis = this.xAxis, yAxis = this.yAxis; // Swap axes for inverted (#2339) if (chart.inverted) { xAxis = yAxis; yAxis = this.xAxis; } return { translateX: xAxis ? xAxis.left : chart.plotLeft, translateY: yAxis ? yAxis.top : chart.plotTop, scaleX: 1, // #1623 scaleY: 1 }; }, /** * Render the graph and markers */ render: function () { var series = this, chart = series.chart, group, options = series.options, animation = options.animation, // Animation doesn't work in IE8 quirks when the group div is hidden, // and looks bad in other oldIE animDuration = (animation && !!series.animate && chart.renderer.isSVG && pick(animation.duration, 500)) || 0, visibility = series.visible ? VISIBLE : HIDDEN, zIndex = options.zIndex, hasRendered = series.hasRendered, chartSeriesGroup = chart.seriesGroup; // the group group = series.plotGroup( 'group', 'series', visibility, zIndex, chartSeriesGroup ); series.markerGroup = series.plotGroup( 'markerGroup', 'markers', visibility, zIndex, chartSeriesGroup ); // initiate the animation if (animDuration) { series.animate(true); } // cache attributes for shapes series.getAttribs(); // SVGRenderer needs to know this before drawing elements (#1089, #1795) group.inverted = series.isCartesian ? chart.inverted : false; // draw the graph if any if (series.drawGraph) { series.drawGraph(); series.clipNeg(); } each(series.points, function (point) { if (point.redraw) { point.redraw(); } }); // draw the data labels (inn pies they go before the points) if (series.drawDataLabels) { series.drawDataLabels(); } // draw the points if (series.visible) { series.drawPoints(); } // draw the mouse tracking area if (series.drawTracker && series.options.enableMouseTracking !== false) { series.drawTracker(); } // Handle inverted series and tracker groups if (chart.inverted) { series.invertGroups(); } // Initial clipping, must be defined after inverting groups for VML if (options.clip !== false && !series.sharedClipKey && !hasRendered) { group.clip(chart.clipRect); } // Run the animation if (animDuration) { series.animate(); } // Call the afterAnimate function on animation complete (but don't overwrite the animation.complete option // which should be available to the user). if (!hasRendered) { if (animDuration) { series.animationTimeout = setTimeout(function () { series.afterAnimate(); }, animDuration); } else { series.afterAnimate(); } } series.isDirty = series.isDirtyData = false; // means data is in accordance with what you see // (See #322) series.isDirty = series.isDirtyData = false; // means data is in accordance with what you see series.hasRendered = true; }, /** * Redraw the series after an update in the axes. */ redraw: function () { var series = this, chart = series.chart, wasDirtyData = series.isDirtyData, // cache it here as it is set to false in render, but used after group = series.group, xAxis = series.xAxis, yAxis = series.yAxis; // reposition on resize if (group) { if (chart.inverted) { group.attr({ width: chart.plotWidth, height: chart.plotHeight }); } group.animate({ translateX: pick(xAxis && xAxis.left, chart.plotLeft), translateY: pick(yAxis && yAxis.top, chart.plotTop) }); } series.translate(); if (series.setTooltipPoints) { series.setTooltipPoints(true); } series.render(); if (wasDirtyData) { fireEvent(series, 'updatedData'); } } }; // end Series prototype // Extend the Chart prototype for dynamic methods extend(Chart.prototype, { /** * Add a series dynamically after time * * @param {Object} options The config options * @param {Boolean} redraw Whether to redraw the chart after adding. Defaults to true. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration * * @return {Object} series The newly created series object */ addSeries: function (options, redraw, animation) { var series, chart = this; if (options) { redraw = pick(redraw, true); // defaults to true fireEvent(chart, 'addSeries', { options: options }, function () { series = chart.initSeries(options); chart.isDirtyLegend = true; // the series array is out of sync with the display chart.linkSeries(); if (redraw) { chart.redraw(animation); } }); } return series; }, /** * Add an axis to the chart * @param {Object} options The axis option * @param {Boolean} isX Whether it is an X axis or a value axis */ addAxis: function (options, isX, redraw, animation) { var key = isX ? 'xAxis' : 'yAxis', chartOptions = this.options, axis; /*jslint unused: false*/ axis = new Axis(this, merge(options, { index: this[key].length, isX: isX })); /*jslint unused: true*/ // Push the new axis options to the chart options chartOptions[key] = splat(chartOptions[key] || {}); chartOptions[key].push(options); if (pick(redraw, true)) { this.redraw(animation); } }, /** * Dim the chart and show a loading text or symbol * @param {String} str An optional text to show in the loading label instead of the default one */ showLoading: function (str) { var chart = this, options = chart.options, loadingDiv = chart.loadingDiv, loadingOptions = options.loading, setLoadingSize = function () { if (loadingDiv) { css(loadingDiv, { left: chart.plotLeft + PX, top: chart.plotTop + PX, width: chart.plotWidth + PX, height: chart.plotHeight + PX }); } }; // create the layer at the first call if (!loadingDiv) { chart.loadingDiv = loadingDiv = createElement(DIV, { className: PREFIX + 'loading' }, extend(loadingOptions.style, { zIndex: 10, display: NONE }), chart.container); chart.loadingSpan = createElement( 'span', null, loadingOptions.labelStyle, loadingDiv ); addEvent(chart, 'redraw', setLoadingSize); // #1080 } // update text chart.loadingSpan.innerHTML = str || options.lang.loading; // show it if (!chart.loadingShown) { css(loadingDiv, { opacity: 0, display: '' }); animate(loadingDiv, { opacity: loadingOptions.style.opacity }, { duration: loadingOptions.showDuration || 0 }); chart.loadingShown = true; } setLoadingSize(); }, /** * Hide the loading layer */ hideLoading: function () { var options = this.options, loadingDiv = this.loadingDiv; if (loadingDiv) { animate(loadingDiv, { opacity: 0 }, { duration: options.loading.hideDuration || 100, complete: function () { css(loadingDiv, { display: NONE }); } }); } this.loadingShown = false; } }); // extend the Point prototype for dynamic methods extend(Point.prototype, { /** * Update the point with new options (typically x/y data) and optionally redraw the series. * * @param {Object} options Point options as defined in the series.data array * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration * */ update: function (options, redraw, animation, runEvent) { var point = this, series = point.series, graphic = point.graphic, i, chart = series.chart, seriesOptions = series.options; redraw = pick(redraw, true); function update() { point.applyOptions(options); // Update visuals if (isObject(options) && !isArray(options)) { // Defer the actual redraw until getAttribs has been called (#3260) point.redraw = function () { if (graphic) { if (options && options.marker && options.marker.symbol) { point.graphic = graphic.destroy(); } else { graphic.attr(point.pointAttr[point.state || '']); } } if (options && options.dataLabels && point.dataLabel) { // #2468 point.dataLabel = point.dataLabel.destroy(); } point.redraw = null; }; } // record changes in the parallel arrays i = point.index; series.updateParallelArrays(point, i); seriesOptions.data[i] = point.options; // redraw series.isDirty = series.isDirtyData = true; if (!series.fixedBox && series.hasCartesianSeries) { // #1906, #2320 chart.isDirtyBox = true; } if (seriesOptions.legendType === 'point') { // #1831, #1885 chart.legend.destroyItem(point); } if (redraw) { chart.redraw(animation); } } // Fire the event with a default handler of doing the update if (runEvent === false) { // When called from setData update(); } else { point.firePointEvent('update', { options: options }, update); } }, /** * Remove a point and optionally redraw the series and if necessary the axes * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ remove: function (redraw, animation) { var point = this, series = point.series, points = series.points, chart = series.chart, i, data = series.data; setAnimation(animation, chart); redraw = pick(redraw, true); // fire the event with a default handler of removing the point point.firePointEvent('remove', null, function () { // splice all the parallel arrays i = inArray(point, data); if (data.length === points.length) { points.splice(i, 1); } data.splice(i, 1); series.options.data.splice(i, 1); series.updateParallelArrays(point, 'splice', i, 1); point.destroy(); // redraw series.isDirty = true; series.isDirtyData = true; if (redraw) { chart.redraw(); } }); } }); // Extend the series prototype for dynamic methods extend(Series.prototype, { /** * Add a point dynamically after chart load time * @param {Object} options Point options as given in series.data * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean} shift If shift is true, a point is shifted off the start * of the series as one is appended to the end. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ addPoint: function (options, redraw, shift, animation) { var series = this, seriesOptions = series.options, data = series.data, graph = series.graph, area = series.area, chart = series.chart, names = series.xAxis && series.xAxis.names, currentShift = (graph && graph.shift) || 0, dataOptions = seriesOptions.data, point, isInTheMiddle, xData = series.xData, x, i; setAnimation(animation, chart); // Make graph animate sideways if (shift) { each([graph, area, series.graphNeg, series.areaNeg], function (shape) { if (shape) { shape.shift = currentShift + 1; } }); } if (area) { area.isArea = true; // needed in animation, both with and without shift } // Optional redraw, defaults to true redraw = pick(redraw, true); // Get options and push the point to xData, yData and series.options. In series.generatePoints // the Point instance will be created on demand and pushed to the series.data array. point = { series: series }; series.pointClass.prototype.applyOptions.apply(point, [options]); x = point.x; // Get the insertion point i = xData.length; if (series.requireSorting && x < xData[i - 1]) { isInTheMiddle = true; while (i && xData[i - 1] > x) { i--; } } series.updateParallelArrays(point, 'splice', i, 0, 0); // insert undefined item series.updateParallelArrays(point, i); // update it if (names && point.name) { names[x] = point.name; } dataOptions.splice(i, 0, options); if (isInTheMiddle) { series.data.splice(i, 0, null); series.processData(); } // Generate points to be added to the legend (#1329) if (seriesOptions.legendType === 'point') { series.generatePoints(); } // Shift the first point off the parallel arrays // todo: consider series.removePoint(i) method if (shift) { if (data[0] && data[0].remove) { data[0].remove(false); } else { data.shift(); series.updateParallelArrays(point, 'shift'); dataOptions.shift(); } } // redraw series.isDirty = true; series.isDirtyData = true; if (redraw) { series.getAttribs(); // #1937 chart.redraw(); } }, /** * Remove a series and optionally redraw the chart * * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ remove: function (redraw, animation) { var series = this, chart = series.chart; redraw = pick(redraw, true); if (!series.isRemoving) { /* prevent triggering native event in jQuery (calling the remove function from the remove event) */ series.isRemoving = true; // fire the event with a default handler of removing the point fireEvent(series, 'remove', null, function () { // destroy elements series.destroy(); // redraw chart.isDirtyLegend = chart.isDirtyBox = true; chart.linkSeries(); if (redraw) { chart.redraw(animation); } }); } series.isRemoving = false; }, /** * Update the series with a new set of options */ update: function (newOptions, redraw) { var series = this, chart = this.chart, // must use user options when changing type because this.options is merged // in with type specific plotOptions oldOptions = this.userOptions, oldType = this.type, proto = seriesTypes[oldType].prototype, preserve = ['group', 'markerGroup', 'dataLabelsGroup'], n; // Make sure groups are not destroyed (#3094) each(preserve, function (prop) { preserve[prop] = series[prop]; delete series[prop]; }); // Do the merge, with some forced options newOptions = merge(oldOptions, { animation: false, index: this.index, pointStart: this.xData[0] // when updating after addPoint }, { data: this.options.data }, newOptions); // Destroy the series and reinsert methods from the type prototype this.remove(false); for (n in proto) { // Overwrite series-type specific methods (#2270) if (proto.hasOwnProperty(n)) { this[n] = UNDEFINED; } } extend(this, seriesTypes[newOptions.type || oldType].prototype); // Re-register groups (#3094) each(preserve, function (prop) { series[prop] = preserve[prop]; }); this.init(chart, newOptions); chart.linkSeries(); // Links are lost in this.remove (#3028) if (pick(redraw, true)) { chart.redraw(false); } } }); // Extend the Axis.prototype for dynamic methods extend(Axis.prototype, { /** * Update the axis with a new options structure */ update: function (newOptions, redraw) { var chart = this.chart; newOptions = chart.options[this.coll][this.options.index] = merge(this.userOptions, newOptions); this.destroy(true); this._addedPlotLB = UNDEFINED; // #1611, #2887 this.init(chart, extend(newOptions, { events: UNDEFINED })); chart.isDirtyBox = true; if (pick(redraw, true)) { chart.redraw(); } }, /** * Remove the axis from the chart */ remove: function (redraw) { var chart = this.chart, key = this.coll, // xAxis or yAxis axisSeries = this.series, i = axisSeries.length; // Remove associated series (#2687) while (i--) { if (axisSeries[i]) { axisSeries[i].remove(false); } } // Remove the axis erase(chart.axes, this); erase(chart[key], this); chart.options[key].splice(this.options.index, 1); each(chart[key], function (axis, i) { // Re-index, #1706 axis.options.index = i; }); this.destroy(); chart.isDirtyBox = true; if (pick(redraw, true)) { chart.redraw(); } }, /** * Update the axis title by options */ setTitle: function (newTitleOptions, redraw) { this.update({ title: newTitleOptions }, redraw); }, /** * Set new axis categories and optionally redraw * @param {Array} categories * @param {Boolean} redraw */ setCategories: function (categories, redraw) { this.update({ categories: categories }, redraw); } }); /** * LineSeries object */ var LineSeries = extendClass(Series); seriesTypes.line = LineSeries; /** * Set the default options for column */ defaultPlotOptions.column = merge(defaultSeriesOptions, { borderColor: '#FFFFFF', //borderWidth: 1, borderRadius: 0, //colorByPoint: undefined, groupPadding: 0.2, //grouping: true, marker: null, // point options are specified in the base options pointPadding: 0.1, //pointWidth: null, minPointLength: 0, cropThreshold: 50, // when there are more points, they will not animate out of the chart on xAxis.setExtremes pointRange: null, // null means auto, meaning 1 in a categorized axis and least distance between points if not categories states: { hover: { brightness: 0.1, shadow: false, halo: false }, select: { color: '#C0C0C0', borderColor: '#000000', shadow: false } }, dataLabels: { align: null, // auto verticalAlign: null, // auto y: null }, stickyTracking: false, tooltip: { distance: 6 }, threshold: 0 }); /** * ColumnSeries object */ var ColumnSeries = extendClass(Series, { type: 'column', pointAttrToOptions: { // mapping between SVG attributes and the corresponding options stroke: 'borderColor', fill: 'color', r: 'borderRadius' }, cropShoulder: 0, trackerGroups: ['group', 'dataLabelsGroup'], negStacks: true, // use separate negative stacks, unlike area stacks where a negative // point is substracted from previous (#1910) /** * Initialize the series */ init: function () { Series.prototype.init.apply(this, arguments); var series = this, chart = series.chart; // if the series is added dynamically, force redraw of other // series affected by a new column if (chart.hasRendered) { each(chart.series, function (otherSeries) { if (otherSeries.type === series.type) { otherSeries.isDirty = true; } }); } }, /** * Return the width and x offset of the columns adjusted for grouping, groupPadding, pointPadding, * pointWidth etc. */ getColumnMetrics: function () { var series = this, options = series.options, xAxis = series.xAxis, yAxis = series.yAxis, reversedXAxis = xAxis.reversed, stackKey, stackGroups = {}, columnIndex, columnCount = 0; // Get the total number of column type series. // This is called on every series. Consider moving this logic to a // chart.orderStacks() function and call it on init, addSeries and removeSeries if (options.grouping === false) { columnCount = 1; } else { each(series.chart.series, function (otherSeries) { var otherOptions = otherSeries.options, otherYAxis = otherSeries.yAxis; if (otherSeries.type === series.type && otherSeries.visible && yAxis.len === otherYAxis.len && yAxis.pos === otherYAxis.pos) { // #642, #2086 if (otherOptions.stacking) { stackKey = otherSeries.stackKey; if (stackGroups[stackKey] === UNDEFINED) { stackGroups[stackKey] = columnCount++; } columnIndex = stackGroups[stackKey]; } else if (otherOptions.grouping !== false) { // #1162 columnIndex = columnCount++; } otherSeries.columnIndex = columnIndex; } }); } var categoryWidth = mathMin( mathAbs(xAxis.transA) * (xAxis.ordinalSlope || options.pointRange || xAxis.closestPointRange || xAxis.tickInterval || 1), // #2610 xAxis.len // #1535 ), groupPadding = categoryWidth * options.groupPadding, groupWidth = categoryWidth - 2 * groupPadding, pointOffsetWidth = groupWidth / columnCount, optionPointWidth = options.pointWidth, pointPadding = defined(optionPointWidth) ? (pointOffsetWidth - optionPointWidth) / 2 : pointOffsetWidth * options.pointPadding, pointWidth = pick(optionPointWidth, pointOffsetWidth - 2 * pointPadding), // exact point width, used in polar charts colIndex = (reversedXAxis ? columnCount - (series.columnIndex || 0) : // #1251 series.columnIndex) || 0, pointXOffset = pointPadding + (groupPadding + colIndex * pointOffsetWidth - (categoryWidth / 2)) * (reversedXAxis ? -1 : 1); // Save it for reading in linked series (Error bars particularly) return (series.columnMetrics = { width: pointWidth, offset: pointXOffset }); }, /** * Translate each point to the plot area coordinate system and find shape positions */ translate: function () { var series = this, chart = series.chart, options = series.options, borderWidth = series.borderWidth = pick( options.borderWidth, series.activePointCount > 0.5 * series.xAxis.len ? 0 : 1 ), yAxis = series.yAxis, threshold = options.threshold, translatedThreshold = series.translatedThreshold = yAxis.getThreshold(threshold), minPointLength = pick(options.minPointLength, 5), metrics = series.getColumnMetrics(), pointWidth = metrics.width, seriesBarW = series.barW = mathMax(pointWidth, 1 + 2 * borderWidth), // postprocessed for border width pointXOffset = series.pointXOffset = metrics.offset, xCrisp = -(borderWidth % 2 ? 0.5 : 0), yCrisp = borderWidth % 2 ? 0.5 : 1; if (chart.renderer.isVML && chart.inverted) { yCrisp += 1; } // When the pointPadding is 0, we want the columns to be packed tightly, so we allow individual // columns to have individual sizes. When pointPadding is greater, we strive for equal-width // columns (#2694). if (options.pointPadding) { seriesBarW = mathCeil(seriesBarW); } Series.prototype.translate.apply(series); // Record the new values each(series.points, function (point) { var yBottom = pick(point.yBottom, translatedThreshold), plotY = mathMin(mathMax(-999 - yBottom, point.plotY), yAxis.len + 999 + yBottom), // Don't draw too far outside plot area (#1303, #2241) barX = point.plotX + pointXOffset, barW = seriesBarW, barY = mathMin(plotY, yBottom), right, bottom, fromTop, barH = mathMax(plotY, yBottom) - barY; // Handle options.minPointLength if (mathAbs(barH) < minPointLength) { if (minPointLength) { barH = minPointLength; barY = mathRound(mathAbs(barY - translatedThreshold) > minPointLength ? // stacked yBottom - minPointLength : // keep position translatedThreshold - (yAxis.translate(point.y, 0, 1, 0, 1) <= translatedThreshold ? minPointLength : 0)); // use exact yAxis.translation (#1485) } } // Cache for access in polar point.barX = barX; point.pointWidth = pointWidth; // Fix the tooltip on center of grouped columns (#1216, #424) point.tooltipPos = chart.inverted ? [yAxis.len - plotY, series.xAxis.len - barX - barW / 2] : [barX + barW / 2, plotY + yAxis.pos - chart.plotTop]; // Round off to obtain crisp edges and avoid overlapping with neighbours (#2694) right = mathRound(barX + barW) + xCrisp; barX = mathRound(barX) + xCrisp; barW = right - barX; fromTop = mathAbs(barY) < 0.5; bottom = mathRound(barY + barH) + yCrisp; barY = mathRound(barY) + yCrisp; barH = bottom - barY; // Top edges are exceptions if (fromTop) { barY -= 1; barH += 1; } // Register shape type and arguments to be used in drawPoints point.shapeType = 'rect'; point.shapeArgs = { x: barX, y: barY, width: barW, height: barH }; }); }, getSymbol: noop, /** * Use a solid rectangle like the area series types */ drawLegendSymbol: LegendSymbolMixin.drawRectangle, /** * Columns have no graph */ drawGraph: noop, /** * Draw the columns. For bars, the series.group is rotated, so the same coordinates * apply for columns and bars. This method is inherited by scatter series. * */ drawPoints: function () { var series = this, chart = this.chart, options = series.options, renderer = chart.renderer, animationLimit = options.animationLimit || 250, shapeArgs, pointAttr; // draw the columns each(series.points, function (point) { var plotY = point.plotY, graphic = point.graphic, borderAttr; if (plotY !== UNDEFINED && !isNaN(plotY) && point.y !== null) { shapeArgs = point.shapeArgs; borderAttr = defined(series.borderWidth) ? { 'stroke-width': series.borderWidth } : {}; pointAttr = point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE] || series.pointAttr[NORMAL_STATE]; if (graphic) { // update stop(graphic); graphic.attr(borderAttr)[chart.pointCount < animationLimit ? 'animate' : 'attr'](merge(shapeArgs)); } else { point.graphic = graphic = renderer[point.shapeType](shapeArgs) .attr(pointAttr) .attr(borderAttr) .add(series.group) .shadow(options.shadow, null, options.stacking && !options.borderRadius); } } else if (graphic) { point.graphic = graphic.destroy(); // #1269 } }); }, /** * Animate the column heights one by one from zero * @param {Boolean} init Whether to initialize the animation or run it */ animate: function (init) { var series = this, yAxis = this.yAxis, options = series.options, inverted = this.chart.inverted, attr = {}, translatedThreshold; if (hasSVG) { // VML is too slow anyway if (init) { attr.scaleY = 0.001; translatedThreshold = mathMin(yAxis.pos + yAxis.len, mathMax(yAxis.pos, yAxis.toPixels(options.threshold))); if (inverted) { attr.translateX = translatedThreshold - yAxis.len; } else { attr.translateY = translatedThreshold; } series.group.attr(attr); } else { // run the animation attr.scaleY = 1; attr[inverted ? 'translateX' : 'translateY'] = yAxis.pos; series.group.animate(attr, series.options.animation); // delete this function to allow it only once series.animate = null; } } }, /** * Remove this series from the chart */ remove: function () { var series = this, chart = series.chart; // column and bar series affects other series of the same type // as they are either stacked or grouped if (chart.hasRendered) { each(chart.series, function (otherSeries) { if (otherSeries.type === series.type) { otherSeries.isDirty = true; } }); } Series.prototype.remove.apply(series, arguments); } }); seriesTypes.column = ColumnSeries; /** * Set the default options for scatter */ defaultPlotOptions.scatter = merge(defaultSeriesOptions, { lineWidth: 0, tooltip: { headerFormat: '<span style="color:{series.color}">\u25CF</span> <span style="font-size: 10px;"> {series.name}</span><br/>', pointFormat: 'x: <b>{point.x}</b><br/>y: <b>{point.y}</b><br/>' }, stickyTracking: false }); /** * The scatter series class */ var ScatterSeries = extendClass(Series, { type: 'scatter', sorted: false, requireSorting: false, noSharedTooltip: true, trackerGroups: ['markerGroup', 'dataLabelsGroup'], takeOrdinalPosition: false, // #2342 singularTooltips: true, drawGraph: function () { if (this.options.lineWidth) { Series.prototype.drawGraph.call(this); } } }); seriesTypes.scatter = ScatterSeries; /** * Draw the data labels */ Series.prototype.drawDataLabels = function () { var series = this, seriesOptions = series.options, cursor = seriesOptions.cursor, options = seriesOptions.dataLabels, points = series.points, pointOptions, generalOptions, hasRendered = series.hasRendered || 0, str, dataLabelsGroup; if (options.enabled || series._hasPointLabels) { // Process default alignment of data labels for columns if (series.dlProcessOptions) { series.dlProcessOptions(options); } // Create a separate group for the data labels to avoid rotation dataLabelsGroup = series.plotGroup( 'dataLabelsGroup', 'data-labels', options.defer ? HIDDEN : VISIBLE, options.zIndex || 6 ); if (pick(options.defer, true)) { dataLabelsGroup.attr({ opacity: +hasRendered }); // #3300 if (!hasRendered) { addEvent(series, 'afterAnimate', function () { if (series.visible) { // #3023, #3024 dataLabelsGroup.show(); } dataLabelsGroup[seriesOptions.animation ? 'animate' : 'attr']({ opacity: 1 }, { duration: 200 }); }); } } // Make the labels for each point generalOptions = options; each(points, function (point) { var enabled, dataLabel = point.dataLabel, labelConfig, attr, name, rotation, connector = point.connector, isNew = true; // Determine if each data label is enabled pointOptions = point.options && point.options.dataLabels; enabled = pick(pointOptions && pointOptions.enabled, generalOptions.enabled); // #2282 // If the point is outside the plot area, destroy it. #678, #820 if (dataLabel && !enabled) { point.dataLabel = dataLabel.destroy(); // Individual labels are disabled if the are explicitly disabled // in the point options, or if they fall outside the plot area. } else if (enabled) { // Create individual options structure that can be extended without // affecting others options = merge(generalOptions, pointOptions); rotation = options.rotation; // Get the string labelConfig = point.getLabelConfig(); str = options.format ? format(options.format, labelConfig) : options.formatter.call(labelConfig, options); // Determine the color options.style.color = pick(options.color, options.style.color, series.color, 'black'); // update existing label if (dataLabel) { if (defined(str)) { dataLabel .attr({ text: str }); isNew = false; } else { // #1437 - the label is shown conditionally point.dataLabel = dataLabel = dataLabel.destroy(); if (connector) { point.connector = connector.destroy(); } } // create new label } else if (defined(str)) { attr = { //align: align, fill: options.backgroundColor, stroke: options.borderColor, 'stroke-width': options.borderWidth, r: options.borderRadius || 0, rotation: rotation, padding: options.padding, zIndex: 1 }; // Remove unused attributes (#947) for (name in attr) { if (attr[name] === UNDEFINED) { delete attr[name]; } } dataLabel = point.dataLabel = series.chart.renderer[rotation ? 'text' : 'label']( // labels don't support rotation str, 0, -999, null, null, null, options.useHTML ) .attr(attr) .css(extend(options.style, cursor && { cursor: cursor })) .add(dataLabelsGroup) .shadow(options.shadow); } if (dataLabel) { // Now the data label is created and placed at 0,0, so we need to align it series.alignDataLabel(point, dataLabel, options, null, isNew); } } }); } }; /** * Align each individual data label */ Series.prototype.alignDataLabel = function (point, dataLabel, options, alignTo, isNew) { var chart = this.chart, inverted = chart.inverted, plotX = pick(point.plotX, -999), plotY = pick(point.plotY, -999), bBox = dataLabel.getBBox(), // Math.round for rounding errors (#2683), alignTo to allow column labels (#2700) visible = this.visible && (point.series.forceDL || chart.isInsidePlot(plotX, mathRound(plotY), inverted) || (alignTo && chart.isInsidePlot(plotX, inverted ? alignTo.x + 1 : alignTo.y + alignTo.height - 1, inverted))), alignAttr; // the final position; if (visible) { // The alignment box is a singular point alignTo = extend({ x: inverted ? chart.plotWidth - plotY : plotX, y: mathRound(inverted ? chart.plotHeight - plotX : plotY), width: 0, height: 0 }, alignTo); // Add the text size for alignment calculation extend(options, { width: bBox.width, height: bBox.height }); // Allow a hook for changing alignment in the last moment, then do the alignment if (options.rotation) { // Fancy box alignment isn't supported for rotated text dataLabel[isNew ? 'attr' : 'animate']({ x: alignTo.x + options.x + alignTo.width / 2, y: alignTo.y + options.y + alignTo.height / 2 }) .attr({ // #3003 align: options.align }); } else { dataLabel.align(options, null, alignTo); alignAttr = dataLabel.alignAttr; // Handle justify or crop if (pick(options.overflow, 'justify') === 'justify') { this.justifyDataLabel(dataLabel, options, alignAttr, bBox, alignTo, isNew); } else if (pick(options.crop, true)) { // Now check that the data label is within the plot area visible = chart.isInsidePlot(alignAttr.x, alignAttr.y) && chart.isInsidePlot(alignAttr.x + bBox.width, alignAttr.y + bBox.height); } } } // Show or hide based on the final aligned position if (!visible) { dataLabel.attr({ y: -999 }); dataLabel.placed = false; // don't animate back in } }; /** * If data labels fall partly outside the plot area, align them back in, in a way that * doesn't hide the point. */ Series.prototype.justifyDataLabel = function (dataLabel, options, alignAttr, bBox, alignTo, isNew) { var chart = this.chart, align = options.align, verticalAlign = options.verticalAlign, off, justified; // Off left off = alignAttr.x; if (off < 0) { if (align === 'right') { options.align = 'left'; } else { options.x = -off; } justified = true; } // Off right off = alignAttr.x + bBox.width; if (off > chart.plotWidth) { if (align === 'left') { options.align = 'right'; } else { options.x = chart.plotWidth - off; } justified = true; } // Off top off = alignAttr.y; if (off < 0) { if (verticalAlign === 'bottom') { options.verticalAlign = 'top'; } else { options.y = -off; } justified = true; } // Off bottom off = alignAttr.y + bBox.height; if (off > chart.plotHeight) { if (verticalAlign === 'top') { options.verticalAlign = 'bottom'; } else { options.y = chart.plotHeight - off; } justified = true; } if (justified) { dataLabel.placed = !isNew; dataLabel.align(options, null, alignTo); } }; /** * Override the base drawDataLabels method by pie specific functionality */ if (seriesTypes.pie) { seriesTypes.pie.prototype.drawDataLabels = function () { var series = this, data = series.data, point, chart = series.chart, options = series.options.dataLabels, connectorPadding = pick(options.connectorPadding, 10), connectorWidth = pick(options.connectorWidth, 1), plotWidth = chart.plotWidth, plotHeight = chart.plotHeight, connector, connectorPath, softConnector = pick(options.softConnector, true), distanceOption = options.distance, seriesCenter = series.center, radius = seriesCenter[2] / 2, centerY = seriesCenter[1], outside = distanceOption > 0, dataLabel, dataLabelWidth, labelPos, labelHeight, halves = [// divide the points into right and left halves for anti collision [], // right [] // left ], x, y, visibility, rankArr, i, j, overflow = [0, 0, 0, 0], // top, right, bottom, left sort = function (a, b) { return b.y - a.y; }; // get out if not enabled if (!series.visible || (!options.enabled && !series._hasPointLabels)) { return; } // run parent method Series.prototype.drawDataLabels.apply(series); // arrange points for detection collision each(data, function (point) { if (point.dataLabel && point.visible) { // #407, #2510 halves[point.half].push(point); } }); /* Loop over the points in each half, starting from the top and bottom * of the pie to detect overlapping labels. */ i = 2; while (i--) { var slots = [], slotsLength, usedSlots = [], points = halves[i], pos, bottom, length = points.length, slotIndex; if (!length) { continue; } // Sort by angle series.sortByAngle(points, i - 0.5); // Assume equal label heights on either hemisphere (#2630) j = labelHeight = 0; while (!labelHeight && points[j]) { // #1569 labelHeight = points[j] && points[j].dataLabel && (points[j].dataLabel.getBBox().height || 21); // 21 is for #968 j++; } // Only do anti-collision when we are outside the pie and have connectors (#856) if (distanceOption > 0) { // Build the slots bottom = mathMin(centerY + radius + distanceOption, chart.plotHeight); for (pos = mathMax(0, centerY - radius - distanceOption); pos <= bottom; pos += labelHeight) { slots.push(pos); } slotsLength = slots.length; /* Visualize the slots if (!series.slotElements) { series.slotElements = []; } if (i === 1) { series.slotElements.forEach(function (elem) { elem.destroy(); }); series.slotElements.length = 0; } slots.forEach(function (pos, no) { var slotX = series.getX(pos, i) + chart.plotLeft - (i ? 100 : 0), slotY = pos + chart.plotTop; if (!isNaN(slotX)) { series.slotElements.push(chart.renderer.rect(slotX, slotY - 7, 100, labelHeight, 1) .attr({ 'stroke-width': 1, stroke: 'silver', fill: 'rgba(0,0,255,0.1)' }) .add()); series.slotElements.push(chart.renderer.text('Slot '+ no, slotX, slotY + 4) .attr({ fill: 'silver' }).add()); } }); // */ // if there are more values than available slots, remove lowest values if (length > slotsLength) { // create an array for sorting and ranking the points within each quarter rankArr = [].concat(points); rankArr.sort(sort); j = length; while (j--) { rankArr[j].rank = j; } j = length; while (j--) { if (points[j].rank >= slotsLength) { points.splice(j, 1); } } length = points.length; } // The label goes to the nearest open slot, but not closer to the edge than // the label's index. for (j = 0; j < length; j++) { point = points[j]; labelPos = point.labelPos; var closest = 9999, distance, slotI; // find the closest slot index for (slotI = 0; slotI < slotsLength; slotI++) { distance = mathAbs(slots[slotI] - labelPos[1]); if (distance < closest) { closest = distance; slotIndex = slotI; } } // if that slot index is closer to the edges of the slots, move it // to the closest appropriate slot if (slotIndex < j && slots[j] !== null) { // cluster at the top slotIndex = j; } else if (slotsLength < length - j + slotIndex && slots[j] !== null) { // cluster at the bottom slotIndex = slotsLength - length + j; while (slots[slotIndex] === null) { // make sure it is not taken slotIndex++; } } else { // Slot is taken, find next free slot below. In the next run, the next slice will find the // slot above these, because it is the closest one while (slots[slotIndex] === null) { // make sure it is not taken slotIndex++; } } usedSlots.push({ i: slotIndex, y: slots[slotIndex] }); slots[slotIndex] = null; // mark as taken } // sort them in order to fill in from the top usedSlots.sort(sort); } // now the used slots are sorted, fill them up sequentially for (j = 0; j < length; j++) { var slot, naturalY; point = points[j]; labelPos = point.labelPos; dataLabel = point.dataLabel; visibility = point.visible === false ? HIDDEN : VISIBLE; naturalY = labelPos[1]; if (distanceOption > 0) { slot = usedSlots.pop(); slotIndex = slot.i; // if the slot next to currrent slot is free, the y value is allowed // to fall back to the natural position y = slot.y; if ((naturalY > y && slots[slotIndex + 1] !== null) || (naturalY < y && slots[slotIndex - 1] !== null)) { y = mathMin(mathMax(0, naturalY), chart.plotHeight); } } else { y = naturalY; } // get the x - use the natural x position for first and last slot, to prevent the top // and botton slice connectors from touching each other on either side x = options.justify ? seriesCenter[0] + (i ? -1 : 1) * (radius + distanceOption) : series.getX(y === centerY - radius - distanceOption || y === centerY + radius + distanceOption ? naturalY : y, i); // Record the placement and visibility dataLabel._attr = { visibility: visibility, align: labelPos[6] }; dataLabel._pos = { x: x + options.x + ({ left: connectorPadding, right: -connectorPadding }[labelPos[6]] || 0), y: y + options.y - 10 // 10 is for the baseline (label vs text) }; dataLabel.connX = x; dataLabel.connY = y; // Detect overflowing data labels if (this.options.size === null) { dataLabelWidth = dataLabel.width; // Overflow left if (x - dataLabelWidth < connectorPadding) { overflow[3] = mathMax(mathRound(dataLabelWidth - x + connectorPadding), overflow[3]); // Overflow right } else if (x + dataLabelWidth > plotWidth - connectorPadding) { overflow[1] = mathMax(mathRound(x + dataLabelWidth - plotWidth + connectorPadding), overflow[1]); } // Overflow top if (y - labelHeight / 2 < 0) { overflow[0] = mathMax(mathRound(-y + labelHeight / 2), overflow[0]); // Overflow left } else if (y + labelHeight / 2 > plotHeight) { overflow[2] = mathMax(mathRound(y + labelHeight / 2 - plotHeight), overflow[2]); } } } // for each point } // for each half // Do not apply the final placement and draw the connectors until we have verified // that labels are not spilling over. if (arrayMax(overflow) === 0 || this.verifyDataLabelOverflow(overflow)) { // Place the labels in the final position this.placeDataLabels(); // Draw the connectors if (outside && connectorWidth) { each(this.points, function (point) { connector = point.connector; labelPos = point.labelPos; dataLabel = point.dataLabel; if (dataLabel && dataLabel._pos) { visibility = dataLabel._attr.visibility; x = dataLabel.connX; y = dataLabel.connY; connectorPath = softConnector ? [ M, x + (labelPos[6] === 'left' ? 5 : -5), y, // end of the string at the label 'C', x, y, // first break, next to the label 2 * labelPos[2] - labelPos[4], 2 * labelPos[3] - labelPos[5], labelPos[2], labelPos[3], // second break L, labelPos[4], labelPos[5] // base ] : [ M, x + (labelPos[6] === 'left' ? 5 : -5), y, // end of the string at the label L, labelPos[2], labelPos[3], // second break L, labelPos[4], labelPos[5] // base ]; if (connector) { connector.animate({ d: connectorPath }); connector.attr('visibility', visibility); } else { point.connector = connector = series.chart.renderer.path(connectorPath).attr({ 'stroke-width': connectorWidth, stroke: options.connectorColor || point.color || '#606060', visibility: visibility //zIndex: 0 // #2722 (reversed) }) .add(series.dataLabelsGroup); } } else if (connector) { point.connector = connector.destroy(); } }); } } }; /** * Perform the final placement of the data labels after we have verified that they * fall within the plot area. */ seriesTypes.pie.prototype.placeDataLabels = function () { each(this.points, function (point) { var dataLabel = point.dataLabel, _pos; if (dataLabel) { _pos = dataLabel._pos; if (_pos) { dataLabel.attr(dataLabel._attr); dataLabel[dataLabel.moved ? 'animate' : 'attr'](_pos); dataLabel.moved = true; } else if (dataLabel) { dataLabel.attr({ y: -999 }); } } }); }; seriesTypes.pie.prototype.alignDataLabel = noop; /** * Verify whether the data labels are allowed to draw, or we should run more translation and data * label positioning to keep them inside the plot area. Returns true when data labels are ready * to draw. */ seriesTypes.pie.prototype.verifyDataLabelOverflow = function (overflow) { var center = this.center, options = this.options, centerOption = options.center, minSize = options.minSize || 80, newSize = minSize, ret; // Handle horizontal size and center if (centerOption[0] !== null) { // Fixed center newSize = mathMax(center[2] - mathMax(overflow[1], overflow[3]), minSize); } else { // Auto center newSize = mathMax( center[2] - overflow[1] - overflow[3], // horizontal overflow minSize ); center[0] += (overflow[3] - overflow[1]) / 2; // horizontal center } // Handle vertical size and center if (centerOption[1] !== null) { // Fixed center newSize = mathMax(mathMin(newSize, center[2] - mathMax(overflow[0], overflow[2])), minSize); } else { // Auto center newSize = mathMax( mathMin( newSize, center[2] - overflow[0] - overflow[2] // vertical overflow ), minSize ); center[1] += (overflow[0] - overflow[2]) / 2; // vertical center } // If the size must be decreased, we need to run translate and drawDataLabels again if (newSize < center[2]) { center[2] = newSize; this.translate(center); each(this.points, function (point) { if (point.dataLabel) { point.dataLabel._pos = null; // reset } }); if (this.drawDataLabels) { this.drawDataLabels(); } // Else, return true to indicate that the pie and its labels is within the plot area } else { ret = true; } return ret; }; } if (seriesTypes.column) { /** * Override the basic data label alignment by adjusting for the position of the column */ seriesTypes.column.prototype.alignDataLabel = function (point, dataLabel, options, alignTo, isNew) { var chart = this.chart, inverted = chart.inverted, dlBox = point.dlBox || point.shapeArgs, // data label box for alignment below = point.below || (point.plotY > pick(this.translatedThreshold, chart.plotSizeY)), inside = pick(options.inside, !!this.options.stacking); // draw it inside the box? // Align to the column itself, or the top of it if (dlBox) { // Area range uses this method but not alignTo alignTo = merge(dlBox); if (inverted) { alignTo = { x: chart.plotWidth - alignTo.y - alignTo.height, y: chart.plotHeight - alignTo.x - alignTo.width, width: alignTo.height, height: alignTo.width }; } // Compute the alignment box if (!inside) { if (inverted) { alignTo.x += below ? 0 : alignTo.width; alignTo.width = 0; } else { alignTo.y += below ? alignTo.height : 0; alignTo.height = 0; } } } // When alignment is undefined (typically columns and bars), display the individual // point below or above the point depending on the threshold options.align = pick( options.align, !inverted || inside ? 'center' : below ? 'right' : 'left' ); options.verticalAlign = pick( options.verticalAlign, inverted || inside ? 'middle' : below ? 'top' : 'bottom' ); // Call the parent method Series.prototype.alignDataLabel.call(this, point, dataLabel, options, alignTo, isNew); }; } /** * Override to use the extreme coordinates from the SVG shape, not the * data values */ wrap(Axis.prototype, 'getSeriesExtremes', function (proceed) { var isXAxis = this.isXAxis, dataMin, dataMax, xData = [], useMapGeometry; // Remove the xData array and cache it locally so that the proceed method doesn't use it if (isXAxis) { each(this.series, function (series, i) { if (series.useMapGeometry) { xData[i] = series.xData; series.xData = []; } }); } // Call base to reach normal cartesian series (like mappoint) proceed.call(this); // Run extremes logic for map and mapline if (isXAxis) { dataMin = pick(this.dataMin, Number.MAX_VALUE); dataMax = pick(this.dataMax, Number.MIN_VALUE); each(this.series, function (series, i) { if (series.useMapGeometry) { dataMin = Math.min(dataMin, pick(series.minX, dataMin)); dataMax = Math.max(dataMax, pick(series.maxX, dataMin)); series.xData = xData[i]; // Reset xData array useMapGeometry = true; } }); if (useMapGeometry) { this.dataMin = dataMin; this.dataMax = dataMax; } } }); /** * Override axis translation to make sure the aspect ratio is always kept */ wrap(Axis.prototype, 'setAxisTranslation', function (proceed) { var chart = this.chart, mapRatio, plotRatio = chart.plotWidth / chart.plotHeight, adjustedAxisLength, xAxis = chart.xAxis[0], padAxis, fixTo, fixDiff; // Run the parent method proceed.call(this); // On Y axis, handle both if (chart.options.chart.preserveAspectRatio && this.coll === 'yAxis' && xAxis.transA !== UNDEFINED) { // Use the same translation for both axes this.transA = xAxis.transA = Math.min(this.transA, xAxis.transA); mapRatio = plotRatio / ((xAxis.max - xAxis.min) / (this.max - this.min)); // What axis to pad to put the map in the middle padAxis = mapRatio < 1 ? this : xAxis; // Pad it adjustedAxisLength = (padAxis.max - padAxis.min) * padAxis.transA; padAxis.pixelPadding = padAxis.len - adjustedAxisLength; padAxis.minPixelPadding = padAxis.pixelPadding / 2; fixTo = padAxis.fixTo; if (fixTo) { fixDiff = fixTo[1] - padAxis.toValue(fixTo[0], true); fixDiff *= padAxis.transA; if (Math.abs(fixDiff) > padAxis.minPixelPadding || (padAxis.min === padAxis.dataMin && padAxis.max === padAxis.dataMax)) { // zooming out again, keep within restricted area fixDiff = 0; } padAxis.minPixelPadding -= fixDiff; } } }); /** * Override Axis.render in order to delete the fixTo prop */ wrap(Axis.prototype, 'render', function (proceed) { proceed.call(this); this.fixTo = null; }); /** * The ColorAxis object for inclusion in gradient legends */ var ColorAxis = Highcharts.ColorAxis = function () { this.isColorAxis = true; this.init.apply(this, arguments); }; extend(ColorAxis.prototype, Axis.prototype); extend(ColorAxis.prototype, { defaultColorAxisOptions: { lineWidth: 0, gridLineWidth: 1, tickPixelInterval: 72, startOnTick: true, endOnTick: true, offset: 0, marker: { animation: { duration: 50 }, color: 'gray', width: 0.01 }, labels: { overflow: 'justify' }, minColor: '#EFEFFF', maxColor: '#003875', tickLength: 5 }, init: function (chart, userOptions) { var horiz = chart.options.legend.layout !== 'vertical', options; // Build the options options = merge(this.defaultColorAxisOptions, { side: horiz ? 2 : 1, reversed: !horiz }, userOptions, { isX: horiz, opposite: !horiz, showEmpty: false, title: null, isColor: true }); Axis.prototype.init.call(this, chart, options); // Base init() pushes it to the xAxis array, now pop it again //chart[this.isXAxis ? 'xAxis' : 'yAxis'].pop(); // Prepare data classes if (userOptions.dataClasses) { this.initDataClasses(userOptions); } this.initStops(userOptions); // Override original axis properties this.isXAxis = true; this.horiz = horiz; this.zoomEnabled = false; }, /* * Return an intermediate color between two colors, according to pos where 0 * is the from color and 1 is the to color */ tweenColors: function (from, to, pos) { // Check for has alpha, because rgba colors perform worse due to lack of // support in WebKit. var hasAlpha = (to.rgba[3] !== 1 || from.rgba[3] !== 1); return (hasAlpha ? 'rgba(' : 'rgb(') + Math.round(to.rgba[0] + (from.rgba[0] - to.rgba[0]) * (1 - pos)) + ',' + Math.round(to.rgba[1] + (from.rgba[1] - to.rgba[1]) * (1 - pos)) + ',' + Math.round(to.rgba[2] + (from.rgba[2] - to.rgba[2]) * (1 - pos)) + (hasAlpha ? (',' + (to.rgba[3] + (from.rgba[3] - to.rgba[3]) * (1 - pos))) : '') + ')'; }, initDataClasses: function (userOptions) { var axis = this, chart = this.chart, dataClasses, colorCounter = 0, options = this.options, len = userOptions.dataClasses.length; this.dataClasses = dataClasses = []; this.legendItems = []; each(userOptions.dataClasses, function (dataClass, i) { var colors; dataClass = merge(dataClass); dataClasses.push(dataClass); if (!dataClass.color) { if (options.dataClassColor === 'category') { colors = chart.options.colors; dataClass.color = colors[colorCounter++]; // loop back to zero if (colorCounter === colors.length) { colorCounter = 0; } } else { dataClass.color = axis.tweenColors( Color(options.minColor), Color(options.maxColor), len < 2 ? 0.5 : i / (len - 1) // #3219 ); } } }); }, initStops: function (userOptions) { this.stops = userOptions.stops || [ [0, this.options.minColor], [1, this.options.maxColor] ]; each(this.stops, function (stop) { stop.color = Color(stop[1]); }); }, /** * Extend the setOptions method to process extreme colors and color * stops. */ setOptions: function (userOptions) { Axis.prototype.setOptions.call(this, userOptions); this.options.crosshair = this.options.marker; this.coll = 'colorAxis'; }, setAxisSize: function () { var symbol = this.legendSymbol, chart = this.chart, x, y, width, height; if (symbol) { this.left = x = symbol.attr('x'); this.top = y = symbol.attr('y'); this.width = width = symbol.attr('width'); this.height = height = symbol.attr('height'); this.right = chart.chartWidth - x - width; this.bottom = chart.chartHeight - y - height; this.len = this.horiz ? width : height; this.pos = this.horiz ? x : y; } }, /** * Translate from a value to a color */ toColor: function (value, point) { var pos, stops = this.stops, from, to, color, dataClasses = this.dataClasses, dataClass, i; if (dataClasses) { i = dataClasses.length; while (i--) { dataClass = dataClasses[i]; from = dataClass.from; to = dataClass.to; if ((from === UNDEFINED || value >= from) && (to === UNDEFINED || value <= to)) { color = dataClass.color; if (point) { point.dataClass = i; } break; } } } else { if (this.isLog) { value = this.val2lin(value); } pos = 1 - ((this.max - value) / ((this.max - this.min) || 1)); i = stops.length; while (i--) { if (pos > stops[i][0]) { break; } } from = stops[i] || stops[i + 1]; to = stops[i + 1] || from; // The position within the gradient pos = 1 - (to[0] - pos) / ((to[0] - from[0]) || 1); color = this.tweenColors( from.color, to.color, pos ); } return color; }, getOffset: function () { var group = this.legendGroup, sideOffset = this.chart.axisOffset[this.side]; if (group) { Axis.prototype.getOffset.call(this); if (!this.axisGroup.parentGroup) { // Move the axis elements inside the legend group this.axisGroup.add(group); this.gridGroup.add(group); this.labelGroup.add(group); this.added = true; } // Reset it to avoid color axis reserving space this.chart.axisOffset[this.side] = sideOffset; } }, /** * Create the color gradient */ setLegendColor: function () { var grad, horiz = this.horiz, options = this.options; grad = horiz ? [0, 0, 1, 0] : [0, 0, 0, 1]; this.legendColor = { linearGradient: { x1: grad[0], y1: grad[1], x2: grad[2], y2: grad[3] }, stops: options.stops || [ [0, options.minColor], [1, options.maxColor] ] }; }, /** * The color axis appears inside the legend and has its own legend symbol */ drawLegendSymbol: function (legend, item) { var padding = legend.padding, legendOptions = legend.options, horiz = this.horiz, box, width = pick(legendOptions.symbolWidth, horiz ? 200 : 12), height = pick(legendOptions.symbolHeight, horiz ? 12 : 200), labelPadding = pick(legendOptions.labelPadding, horiz ? 16 : 30), itemDistance = pick(legendOptions.itemDistance, 10); this.setLegendColor(); // Create the gradient item.legendSymbol = this.chart.renderer.rect( 0, legend.baseline - 11, width, height ).attr({ zIndex: 1 }).add(item.legendGroup); box = item.legendSymbol.getBBox(); // Set how much space this legend item takes up this.legendItemWidth = width + padding + (horiz ? itemDistance : labelPadding); this.legendItemHeight = height + padding + (horiz ? labelPadding : 0); }, /** * Fool the legend */ setState: noop, visible: true, setVisible: noop, getSeriesExtremes: function () { var series; if (this.series.length) { series = this.series[0]; this.dataMin = series.valueMin; this.dataMax = series.valueMax; } }, drawCrosshair: function (e, point) { var newCross = !this.cross, plotX = point && point.plotX, plotY = point && point.plotY, crossPos, axisPos = this.pos, axisLen = this.len; if (point) { crossPos = this.toPixels(point.value); if (crossPos < axisPos) { crossPos = axisPos - 2; } else if (crossPos > axisPos + axisLen) { crossPos = axisPos + axisLen + 2; } point.plotX = crossPos; point.plotY = this.len - crossPos; Axis.prototype.drawCrosshair.call(this, e, point); point.plotX = plotX; point.plotY = plotY; if (!newCross && this.cross) { this.cross .attr({ fill: this.crosshair.color }) .add(this.labelGroup); } } }, getPlotLinePath: function (a, b, c, d, pos) { if (pos) { // crosshairs only return this.horiz ? ['M', pos - 4, this.top - 6, 'L', pos + 4, this.top - 6, pos, this.top, 'Z'] : ['M', this.left, pos, 'L', this.left - 6, pos + 6, this.left - 6, pos - 6, 'Z']; } else { return Axis.prototype.getPlotLinePath.call(this, a, b, c, d); } }, update: function (newOptions, redraw) { each(this.series, function (series) { series.isDirtyData = true; // Needed for Axis.update when choropleth colors change }); Axis.prototype.update.call(this, newOptions, redraw); if (this.legendItem) { this.setLegendColor(); this.chart.legend.colorizeItem(this, true); } }, /** * Get the legend item symbols for data classes */ getDataClassLegendSymbols: function () { var axis = this, chart = this.chart, legendItems = this.legendItems, legendOptions = chart.options.legend, valueDecimals = legendOptions.valueDecimals, valueSuffix = legendOptions.valueSuffix || '', name; if (!legendItems.length) { each(this.dataClasses, function (dataClass, i) { var vis = true, from = dataClass.from, to = dataClass.to; // Assemble the default name. This can be overridden by legend.options.labelFormatter name = ''; if (from === UNDEFINED) { name = '< '; } else if (to === UNDEFINED) { name = '> '; } if (from !== UNDEFINED) { name += numberFormat(from, valueDecimals) + valueSuffix; } if (from !== UNDEFINED && to !== UNDEFINED) { name += ' - '; } if (to !== UNDEFINED) { name += numberFormat(to, valueDecimals) + valueSuffix; } // Add a mock object to the legend items legendItems.push(extend({ chart: chart, name: name, options: {}, drawLegendSymbol: LegendSymbolMixin.drawRectangle, visible: true, setState: noop, setVisible: function () { vis = this.visible = !vis; each(axis.series, function (series) { each(series.points, function (point) { if (point.dataClass === i) { point.setVisible(vis); } }); }); chart.legend.colorizeItem(this, vis); } }, dataClass)); }); } return legendItems; }, name: '' // Prevents 'undefined' in legend in IE8 }); /** * Handle animation of the color attributes directly */ each(['fill', 'stroke'], function (prop) { HighchartsAdapter.addAnimSetter(prop, function (fx) { fx.elem.attr(prop, ColorAxis.prototype.tweenColors(Color(fx.start), Color(fx.end), fx.pos)); }); }); /** * Extend the chart getAxes method to also get the color axis */ wrap(Chart.prototype, 'getAxes', function (proceed) { var options = this.options, colorAxisOptions = options.colorAxis; proceed.call(this); this.colorAxis = []; if (colorAxisOptions) { proceed = new ColorAxis(this, colorAxisOptions); // Fake assignment for jsLint } }); /** * Wrap the legend getAllItems method to add the color axis. This also removes the * axis' own series to prevent them from showing up individually. */ wrap(Legend.prototype, 'getAllItems', function (proceed) { var allItems = [], colorAxis = this.chart.colorAxis[0]; if (colorAxis) { // Data classes if (colorAxis.options.dataClasses) { allItems = allItems.concat(colorAxis.getDataClassLegendSymbols()); // Gradient legend } else { // Add this axis on top allItems.push(colorAxis); } // Don't add the color axis' series each(colorAxis.series, function (series) { series.options.showInLegend = false; }); } return allItems.concat(proceed.call(this)); });/** * Mixin for maps and heatmaps */ var colorSeriesMixin = { pointAttrToOptions: { // mapping between SVG attributes and the corresponding options stroke: 'borderColor', 'stroke-width': 'borderWidth', fill: 'color', dashstyle: 'dashStyle' }, pointArrayMap: ['value'], axisTypes: ['xAxis', 'yAxis', 'colorAxis'], optionalAxis: 'colorAxis', trackerGroups: ['group', 'markerGroup', 'dataLabelsGroup'], getSymbol: noop, parallelArrays: ['x', 'y', 'value'], colorKey: 'value', /** * In choropleth maps, the color is a result of the value, so this needs translation too */ translateColors: function () { var series = this, nullColor = this.options.nullColor, colorAxis = this.colorAxis, colorKey = this.colorKey; each(this.data, function (point) { var value = point[colorKey], color; color = value === null ? nullColor : (colorAxis && value !== undefined) ? colorAxis.toColor(value, point) : point.color || series.color; if (color) { point.color = color; } }); } }; /** * Wrap the buildText method and add the hook for add text stroke */ wrap(SVGRenderer.prototype, 'buildText', function (proceed, wrapper) { var textStroke = wrapper.styles && wrapper.styles.HcTextStroke; proceed.call(this, wrapper); // Apply the text stroke if (textStroke && wrapper.applyTextStroke) { wrapper.applyTextStroke(textStroke); } }); /** * Apply an outside text stroke to data labels, based on the custom CSS property, HcTextStroke. * Consider moving this to Highcharts core, also makes sense on stacked columns etc. */ SVGRenderer.prototype.Element.prototype.applyTextStroke = function (textStroke) { var elem = this.element, tspans, firstChild; textStroke = textStroke.split(' '); tspans = elem.getElementsByTagName('tspan'); firstChild = elem.firstChild; // In order to get the right y position of the clones, // copy over the y setter this.ySetter = this.xSetter; each([].slice.call(tspans), function (tspan, y) { var clone; if (y === 0) { tspan.setAttribute('x', elem.getAttribute('x')); if ((y = elem.getAttribute('y')) !== null) { tspan.setAttribute('y', y); } } clone = tspan.cloneNode(1); clone.setAttribute('stroke', textStroke[1]); clone.setAttribute('stroke-width', textStroke[0]); clone.setAttribute('stroke-linejoin', 'round'); elem.insertBefore(clone, firstChild); }); }; /** * Extend the default options with map options */ defaultPlotOptions.map = merge(defaultPlotOptions.scatter, { allAreas: true, animation: false, // makes the complex shapes slow nullColor: '#F8F8F8', borderColor: 'silver', borderWidth: 1, marker: null, stickyTracking: false, dataLabels: { formatter: function () { // #2945 return this.point.value; }, verticalAlign: 'middle', crop: false, overflow: false, padding: 0, style: { color: 'white', fontWeight: 'bold', HcTextStroke: '3px rgba(0,0,0,0.5)' } }, turboThreshold: 0, tooltip: { followPointer: true, pointFormat: '{point.name}: {point.value}<br/>' }, states: { normal: { animation: true }, hover: { brightness: 0.2, halo: null } } }); /** * The MapAreaPoint object */ var MapAreaPoint = extendClass(Point, { /** * Extend the Point object to split paths */ applyOptions: function (options, x) { var point = Point.prototype.applyOptions.call(this, options, x), series = this.series, joinBy = series.joinBy, mapPoint; if (series.mapData) { mapPoint = point[joinBy[1]] !== undefined && series.mapMap[point[joinBy[1]]]; if (mapPoint) { // This applies only to bubbles if (series.xyFromShape) { point.x = mapPoint._midX; point.y = mapPoint._midY; } extend(point, mapPoint); // copy over properties } else { point.value = point.value || null; } } return point; }, /** * Set the visibility of a single map area */ setVisible: function (vis) { var point = this, method = vis ? 'show' : 'hide'; // Show and hide associated elements each(['graphic', 'dataLabel'], function (key) { if (point[key]) { point[key][method](); } }); }, /** * Stop the fade-out */ onMouseOver: function (e) { clearTimeout(this.colorInterval); if (this.value !== null) { Point.prototype.onMouseOver.call(this, e); } }, /** * Custom animation for tweening out the colors. Animation reduces blinking when hovering * over islands and coast lines. We run a custom implementation of animation becuase we * need to be able to run this independently from other animations like zoom redraw. Also, * adding color animation to the adapters would introduce almost the same amount of code. */ onMouseOut: function () { var point = this, start = +new Date(), normalColor = Color(point.color), hoverColor = Color(point.pointAttr.hover.fill), animation = point.series.options.states.normal.animation, duration = animation && (animation.duration || 500), fill; if (duration && normalColor.rgba.length === 4 && hoverColor.rgba.length === 4 && point.state !== 'select') { fill = point.pointAttr[''].fill; delete point.pointAttr[''].fill; // avoid resetting it in Point.setState clearTimeout(point.colorInterval); point.colorInterval = setInterval(function () { var pos = (new Date() - start) / duration, graphic = point.graphic; if (pos > 1) { pos = 1; } if (graphic) { graphic.attr('fill', ColorAxis.prototype.tweenColors.call(0, hoverColor, normalColor, pos)); } if (pos >= 1) { clearTimeout(point.colorInterval); } }, 13); } Point.prototype.onMouseOut.call(point); if (fill) { point.pointAttr[''].fill = fill; } }, /** * Zoom the chart to view a specific area point */ zoomTo: function () { var point = this, series = point.series; series.xAxis.setExtremes( point._minX, point._maxX, false ); series.yAxis.setExtremes( point._minY, point._maxY, false ); series.chart.redraw(); } }); /** * Add the series type */ seriesTypes.map = extendClass(seriesTypes.scatter, merge(colorSeriesMixin, { type: 'map', pointClass: MapAreaPoint, supportsDrilldown: true, getExtremesFromAll: true, useMapGeometry: true, // get axis extremes from paths, not values forceDL: true, /** * Get the bounding box of all paths in the map combined. */ getBox: function (paths) { var MAX_VALUE = Number.MAX_VALUE, maxX = -MAX_VALUE, minX = MAX_VALUE, maxY = -MAX_VALUE, minY = MAX_VALUE, minRange = MAX_VALUE, xAxis = this.xAxis, yAxis = this.yAxis, hasBox; // Find the bounding box each(paths || [], function (point) { if (point.path) { if (typeof point.path === 'string') { point.path = Highcharts.splitPath(point.path); } var path = point.path || [], i = path.length, even = false, // while loop reads from the end pointMaxX = -MAX_VALUE, pointMinX = MAX_VALUE, pointMaxY = -MAX_VALUE, pointMinY = MAX_VALUE, properties = point.properties; // The first time a map point is used, analyze its box if (!point._foundBox) { while (i--) { if (typeof path[i] === 'number' && !isNaN(path[i])) { if (even) { // even = x pointMaxX = Math.max(pointMaxX, path[i]); pointMinX = Math.min(pointMinX, path[i]); } else { // odd = Y pointMaxY = Math.max(pointMaxY, path[i]); pointMinY = Math.min(pointMinY, path[i]); } even = !even; } } // Cache point bounding box for use to position data labels, bubbles etc point._midX = pointMinX + (pointMaxX - pointMinX) * (point.middleX || (properties && properties['hc-middle-x']) || 0.5); // pick is slower and very marginally needed point._midY = pointMinY + (pointMaxY - pointMinY) * (point.middleY || (properties && properties['hc-middle-y']) || 0.5); point._maxX = pointMaxX; point._minX = pointMinX; point._maxY = pointMaxY; point._minY = pointMinY; point.labelrank = pick(point.labelrank, (pointMaxX - pointMinX) * (pointMaxY - pointMinY)); point._foundBox = true; } maxX = Math.max(maxX, point._maxX); minX = Math.min(minX, point._minX); maxY = Math.max(maxY, point._maxY); minY = Math.min(minY, point._minY); minRange = Math.min(point._maxX - point._minX, point._maxY - point._minY, minRange); hasBox = true; } }); // Set the box for the whole series if (hasBox) { this.minY = Math.min(minY, pick(this.minY, MAX_VALUE)); this.maxY = Math.max(maxY, pick(this.maxY, -MAX_VALUE)); this.minX = Math.min(minX, pick(this.minX, MAX_VALUE)); this.maxX = Math.max(maxX, pick(this.maxX, -MAX_VALUE)); // If no minRange option is set, set the default minimum zooming range to 5 times the // size of the smallest element if (xAxis && xAxis.options.minRange === undefined) { xAxis.minRange = Math.min(5 * minRange, (this.maxX - this.minX) / 5, xAxis.minRange || MAX_VALUE); } if (yAxis && yAxis.options.minRange === undefined) { yAxis.minRange = Math.min(5 * minRange, (this.maxY - this.minY) / 5, yAxis.minRange || MAX_VALUE); } } }, getExtremes: function () { // Get the actual value extremes for colors Series.prototype.getExtremes.call(this, this.valueData); // Recalculate box on updated data if (this.chart.hasRendered && this.isDirtyData) { this.getBox(this.options.data); } this.valueMin = this.dataMin; this.valueMax = this.dataMax; // Extremes for the mock Y axis this.dataMin = this.minY; this.dataMax = this.maxY; }, /** * Translate the path so that it automatically fits into the plot area box * @param {Object} path */ translatePath: function (path) { var series = this, even = false, // while loop reads from the end xAxis = series.xAxis, yAxis = series.yAxis, xMin = xAxis.min, xTransA = xAxis.transA, xMinPixelPadding = xAxis.minPixelPadding, yMin = yAxis.min, yTransA = yAxis.transA, yMinPixelPadding = yAxis.minPixelPadding, i, ret = []; // Preserve the original // Do the translation if (path) { i = path.length; while (i--) { if (typeof path[i] === 'number') { ret[i] = even ? (path[i] - xMin) * xTransA + xMinPixelPadding : (path[i] - yMin) * yTransA + yMinPixelPadding; even = !even; } else { ret[i] = path[i]; } } } return ret; }, /** * Extend setData to join in mapData. If the allAreas option is true, all areas * from the mapData are used, and those that don't correspond to a data value * are given null values. */ setData: function (data, redraw) { var options = this.options, mapData = options.mapData, joinBy = options.joinBy, joinByNull = joinBy === null, dataUsed = [], mapPoint, props, i; if (joinByNull) { joinBy = '_i'; } joinBy = this.joinBy = Highcharts.splat(joinBy); if (!joinBy[1]) { joinBy[1] = joinBy[0]; } // Pick up numeric values, add index if (data) { each(data, function (val, i) { if (typeof val === 'number') { data[i] = { value: val }; } if (joinByNull) { data[i]._i = i; } }); } this.getBox(data); if (mapData) { if (mapData.type === 'FeatureCollection') { mapData = Highcharts.geojson(mapData, this.type, this); } this.getBox(mapData); this.mapData = mapData; this.mapMap = {}; for (i = 0; i < mapData.length; i++) { mapPoint = mapData[i]; props = mapPoint.properties; mapPoint._i = i; // Copy the property over to root for faster access if (joinBy[0] && props && props[joinBy[0]]) { mapPoint[joinBy[0]] = props[joinBy[0]]; } this.mapMap[mapPoint[joinBy[0]]] = mapPoint; } if (options.allAreas) { data = data || []; // Registered the point codes that actually hold data if (joinBy[1]) { each(data, function (point) { dataUsed.push(point[joinBy[1]]); }); } // Add those map points that don't correspond to data, which will be drawn as null points dataUsed = '|' + dataUsed.join('|') + '|'; // String search is faster than array.indexOf each(mapData, function (mapPoint) { if (!joinBy[0] || dataUsed.indexOf('|' + mapPoint[joinBy[0]] + '|') === -1) { data.push(merge(mapPoint, { value: null })); } }); } } Series.prototype.setData.call(this, data, redraw); }, /** * No graph for the map series */ drawGraph: noop, /** * We need the points' bounding boxes in order to draw the data labels, so * we skip it now and call it from drawPoints instead. */ drawDataLabels: noop, /** * Allow a quick redraw by just translating the area group. Used for zooming and panning * in capable browsers. */ doFullTranslate: function () { return this.isDirtyData || this.chart.renderer.isVML || !this.baseTrans; }, /** * Add the path option for data points. Find the max value for color calculation. */ translate: function () { var series = this, xAxis = series.xAxis, yAxis = series.yAxis, doFullTranslate = series.doFullTranslate(); series.generatePoints(); each(series.data, function (point) { // Record the middle point (loosely based on centroid), determined // by the middleX and middleY options. point.plotX = xAxis.toPixels(point._midX, true); point.plotY = yAxis.toPixels(point._midY, true); if (doFullTranslate) { point.shapeType = 'path'; point.shapeArgs = { //d: display ? series.translatePath(point.path) : '' d: series.translatePath(point.path), 'vector-effect': 'non-scaling-stroke' }; } }); series.translateColors(); }, /** * Use the drawPoints method of column, that is able to handle simple shapeArgs. * Extend it by assigning the tooltip position. */ drawPoints: function () { var series = this, xAxis = series.xAxis, yAxis = series.yAxis, group = series.group, chart = series.chart, renderer = chart.renderer, scaleX, scaleY, translateX, translateY, baseTrans = this.baseTrans; // Set a group that handles transform during zooming and panning in order to preserve clipping // on series.group if (!series.transformGroup) { series.transformGroup = renderer.g() .attr({ scaleX: 1, scaleY: 1 }) .add(group); } // Draw the shapes again if (series.doFullTranslate()) { // Individual point actions if (chart.hasRendered && series.pointAttrToOptions.fill === 'color') { each(series.points, function (point) { // Reset color on update/redraw if (point.graphic) { point.graphic.attr('fill', point.color); } }); } // Draw them in transformGroup series.group = series.transformGroup; seriesTypes.column.prototype.drawPoints.apply(series); series.group = group; // Reset // Add class names each(series.points, function (point) { if (point.graphic) { if (point.name) { point.graphic.addClass('highcharts-name-' + point.name.replace(' ', '-').toLowerCase()); } if (point.properties && point.properties['hc-key']) { point.graphic.addClass('highcharts-key-' + point.properties['hc-key'].toLowerCase()); } } }); // Set the base for later scale-zooming. The originX and originY properties are the // axis values in the plot area's upper left corner. this.baseTrans = { originX: xAxis.min - xAxis.minPixelPadding / xAxis.transA, originY: yAxis.min - yAxis.minPixelPadding / yAxis.transA + (yAxis.reversed ? 0 : yAxis.len / yAxis.transA), transAX: xAxis.transA, transAY: yAxis.transA }; // Just update the scale and transform for better performance } else { scaleX = xAxis.transA / baseTrans.transAX; scaleY = yAxis.transA / baseTrans.transAY; if (scaleX > 0.99 && scaleX < 1.01 && scaleY > 0.99 && scaleY < 1.01) { // rounding errors translateX = 0; translateY = 0; scaleX = 1; scaleY = 1; } else { translateX = xAxis.toPixels(baseTrans.originX, true); translateY = yAxis.toPixels(baseTrans.originY, true); } this.transformGroup.animate({ translateX: translateX, translateY: translateY, scaleX: scaleX, scaleY: scaleY }); } this.drawMapDataLabels(); }, /** * Draw the data labels. Special for maps is the time that the data labels are drawn (after points), * and the clipping of the dataLabelsGroup. */ drawMapDataLabels: function () { Series.prototype.drawDataLabels.call(this); if (this.dataLabelsGroup) { this.dataLabelsGroup.clip(this.chart.clipRect); } this.hideOverlappingDataLabels(); }, /** * Hide overlapping labels. Labels are moved and faded in and out on zoom to provide a smooth * visual imression. */ hideOverlappingDataLabels: function () { var points = this.points, len = points.length, i, j, label1, label2, intersectRect = function (pos1, pos2, size1, size2) { return !( pos2.x > pos1.x + size1.width || pos2.x + size2.width < pos1.x || pos2.y > pos1.y + size1.height || pos2.y + size2.height < pos1.y ); }; // Mark with initial opacity each(points, function (point, label) { label = point.dataLabel; if (label) { label.oldOpacity = label.opacity; label.newOpacity = 1; } }); // Detect overlapping labels for (i = 0; i < len - 1; ++i) { label1 = points[i].dataLabel; for (j = i + 1; j < len; ++j) { label2 = points[j].dataLabel; if (label1 && label2 && label1.newOpacity !== 0 && label2.newOpacity !== 0 && intersectRect(label1.alignAttr, label2.alignAttr, label1, label2)) { (points[i].labelrank < points[j].labelrank ? label1 : label2).newOpacity = 0; } } } // Hide or show each(points, function (point, label) { label = point.dataLabel; if (label) { if (label.oldOpacity !== label.newOpacity) { label[label.isOld ? 'animate' : 'attr'](extend({ opacity: label.newOpacity }, label.alignAttr)); } label.isOld = true; } }); }, /** * Override render to throw in an async call in IE8. Otherwise it chokes on the US counties demo. */ render: function () { var series = this, render = Series.prototype.render; // Give IE8 some time to breathe. if (series.chart.renderer.isVML && series.data.length > 3000) { setTimeout(function () { render.call(series); }); } else { render.call(series); } }, /** * The initial animation for the map series. By default, animation is disabled. * Animation of map shapes is not at all supported in VML browsers. */ animate: function (init) { var chart = this.chart, animation = this.options.animation, group = this.group, xAxis = this.xAxis, yAxis = this.yAxis, left = xAxis.pos, top = yAxis.pos; if (chart.renderer.isSVG) { if (animation === true) { animation = { duration: 1000 }; } // Initialize the animation if (init) { // Scale down the group and place it in the center group.attr({ translateX: left + xAxis.len / 2, translateY: top + yAxis.len / 2, scaleX: 0.001, // #1499 scaleY: 0.001 }); // Run the animation } else { group.animate({ translateX: left, translateY: top, scaleX: 1, scaleY: 1 }, animation); // Delete this function to allow it only once this.animate = null; } } }, /** * Animate in the new series from the clicked point in the old series. * Depends on the drilldown.js module */ animateDrilldown: function (init) { var toBox = this.chart.plotBox, level = this.chart.drilldownLevels[this.chart.drilldownLevels.length - 1], fromBox = level.bBox, animationOptions = this.chart.options.drilldown.animation, scale; if (!init) { scale = Math.min(fromBox.width / toBox.width, fromBox.height / toBox.height); level.shapeArgs = { scaleX: scale, scaleY: scale, translateX: fromBox.x, translateY: fromBox.y }; // TODO: Animate this.group instead each(this.points, function (point) { point.graphic .attr(level.shapeArgs) .animate({ scaleX: 1, scaleY: 1, translateX: 0, translateY: 0 }, animationOptions); }); this.animate = null; } }, drawLegendSymbol: LegendSymbolMixin.drawRectangle, /** * When drilling up, pull out the individual point graphics from the lower series * and animate them into the origin point in the upper series. */ animateDrillupFrom: function (level) { seriesTypes.column.prototype.animateDrillupFrom.call(this, level); }, /** * When drilling up, keep the upper series invisible until the lower series has * moved into place */ animateDrillupTo: function (init) { seriesTypes.column.prototype.animateDrillupTo.call(this, init); } })); // Add events to the Chart object itself extend(Chart.prototype, { renderMapNavigation: function () { var chart = this, options = this.options.mapNavigation, buttons = options.buttons, n, button, buttonOptions, attr, states, outerHandler = function () { this.handler.call(chart); }; if (pick(options.enableButtons, options.enabled) && !chart.renderer.forExport) { for (n in buttons) { if (buttons.hasOwnProperty(n)) { buttonOptions = merge(options.buttonOptions, buttons[n]); attr = buttonOptions.theme; states = attr.states; button = chart.renderer.button( buttonOptions.text, 0, 0, outerHandler, attr, states && states.hover, states && states.select, 0, n === 'zoomIn' ? 'topbutton' : 'bottombutton' ) .attr({ width: buttonOptions.width, height: buttonOptions.height, title: chart.options.lang[n], zIndex: 5 }) .css(buttonOptions.style) .add(); button.handler = buttonOptions.onclick; button.align(extend(buttonOptions, { width: button.width, height: 2 * button.height }), null, buttonOptions.alignTo); } } } }, /** * Fit an inner box to an outer. If the inner box overflows left or right, align it to the sides of the * outer. If it overflows both sides, fit it within the outer. This is a pattern that occurs more places * in Highcharts, perhaps it should be elevated to a common utility function. */ fitToBox: function (inner, outer) { each([['x', 'width'], ['y', 'height']], function (dim) { var pos = dim[0], size = dim[1]; if (inner[pos] + inner[size] > outer[pos] + outer[size]) { // right overflow if (inner[size] > outer[size]) { // the general size is greater, fit fully to outer inner[size] = outer[size]; inner[pos] = outer[pos]; } else { // align right inner[pos] = outer[pos] + outer[size] - inner[size]; } } if (inner[size] > outer[size]) { inner[size] = outer[size]; } if (inner[pos] < outer[pos]) { inner[pos] = outer[pos]; } }); return inner; }, /** * Zoom the map in or out by a certain amount. Less than 1 zooms in, greater than 1 zooms out. */ mapZoom: function (howMuch, centerXArg, centerYArg, mouseX, mouseY) { /*if (this.isMapZooming) { this.mapZoomQueue = arguments; return; }*/ var chart = this, xAxis = chart.xAxis[0], xRange = xAxis.max - xAxis.min, centerX = pick(centerXArg, xAxis.min + xRange / 2), newXRange = xRange * howMuch, yAxis = chart.yAxis[0], yRange = yAxis.max - yAxis.min, centerY = pick(centerYArg, yAxis.min + yRange / 2), newYRange = yRange * howMuch, fixToX = mouseX ? ((mouseX - xAxis.pos) / xAxis.len) : 0.5, fixToY = mouseY ? ((mouseY - yAxis.pos) / yAxis.len) : 0.5, newXMin = centerX - newXRange * fixToX, newYMin = centerY - newYRange * fixToY, newExt = chart.fitToBox({ x: newXMin, y: newYMin, width: newXRange, height: newYRange }, { x: xAxis.dataMin, y: yAxis.dataMin, width: xAxis.dataMax - xAxis.dataMin, height: yAxis.dataMax - yAxis.dataMin }); // When mousewheel zooming, fix the point under the mouse if (mouseX) { xAxis.fixTo = [mouseX - xAxis.pos, centerXArg]; } if (mouseY) { yAxis.fixTo = [mouseY - yAxis.pos, centerYArg]; } // Zoom if (howMuch !== undefined) { xAxis.setExtremes(newExt.x, newExt.x + newExt.width, false); yAxis.setExtremes(newExt.y, newExt.y + newExt.height, false); // Reset zoom } else { xAxis.setExtremes(undefined, undefined, false); yAxis.setExtremes(undefined, undefined, false); } // Prevent zooming until this one is finished animating /*chart.holdMapZoom = true; setTimeout(function () { chart.holdMapZoom = false; }, 200);*/ /*delay = animation ? animation.duration || 500 : 0; if (delay) { chart.isMapZooming = true; setTimeout(function () { chart.isMapZooming = false; if (chart.mapZoomQueue) { chart.mapZoom.apply(chart, chart.mapZoomQueue); } chart.mapZoomQueue = null; }, delay); }*/ chart.redraw(); } }); /** * Extend the Chart.render method to add zooming and panning */ wrap(Chart.prototype, 'render', function (proceed) { var chart = this, mapNavigation = chart.options.mapNavigation; // Render the plus and minus buttons. Doing this before the shapes makes getBBox much quicker, at least in Chrome. chart.renderMapNavigation(); proceed.call(chart); // Add the double click event if (pick(mapNavigation.enableDoubleClickZoom, mapNavigation.enabled) || mapNavigation.enableDoubleClickZoomTo) { addEvent(chart.container, 'dblclick', function (e) { chart.pointer.onContainerDblClick(e); }); } // Add the mousewheel event if (pick(mapNavigation.enableMouseWheelZoom, mapNavigation.enabled)) { addEvent(chart.container, document.onmousewheel === undefined ? 'DOMMouseScroll' : 'mousewheel', function (e) { chart.pointer.onContainerMouseWheel(e); return false; }); } }); // Extend the Pointer extend(Pointer.prototype, { /** * The event handler for the doubleclick event */ onContainerDblClick: function (e) { var chart = this.chart; e = this.normalize(e); if (chart.options.mapNavigation.enableDoubleClickZoomTo) { if (chart.pointer.inClass(e.target, 'highcharts-tracker')) { chart.hoverPoint.zoomTo(); } } else if (chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) { chart.mapZoom( 0.5, chart.xAxis[0].toValue(e.chartX), chart.yAxis[0].toValue(e.chartY), e.chartX, e.chartY ); } }, /** * The event handler for the mouse scroll event */ onContainerMouseWheel: function (e) { var chart = this.chart, delta; e = this.normalize(e); // Firefox uses e.detail, WebKit and IE uses wheelDelta delta = e.detail || -(e.wheelDelta / 120); if (chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) { chart.mapZoom( //delta > 0 ? 2 : 0.5, Math.pow(2, delta), chart.xAxis[0].toValue(e.chartX), chart.yAxis[0].toValue(e.chartY), e.chartX, e.chartY ); } } }); // Implement the pinchType option wrap(Pointer.prototype, 'init', function (proceed, chart, options) { proceed.call(this, chart, options); // Pinch status if (pick(options.mapNavigation.enableTouchZoom, options.mapNavigation.enabled)) { this.pinchX = this.pinchHor = this.pinchY = this.pinchVert = this.hasZoom = true; } }); // Extend the pinchTranslate method to preserve fixed ratio when zooming wrap(Pointer.prototype, 'pinchTranslate', function (proceed, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch) { var xBigger; proceed.call(this, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch); // Keep ratio if (this.chart.options.chart.type === 'map' && this.hasZoom) { xBigger = transform.scaleX > transform.scaleY; this.pinchTranslateDirection( !xBigger, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch, xBigger ? transform.scaleX : transform.scaleY ); } }); // The mapline series type defaultPlotOptions.mapline = merge(defaultPlotOptions.map, { lineWidth: 1, fillColor: 'none' }); seriesTypes.mapline = extendClass(seriesTypes.map, { type: 'mapline', pointAttrToOptions: { // mapping between SVG attributes and the corresponding options stroke: 'color', 'stroke-width': 'lineWidth', fill: 'fillColor', dashstyle: 'dashStyle' }, drawLegendSymbol: seriesTypes.line.prototype.drawLegendSymbol }); // The mappoint series type defaultPlotOptions.mappoint = merge(defaultPlotOptions.scatter, { dataLabels: { enabled: true, formatter: function () { // #2945 return this.point.name; }, color: 'black', crop: false, defer: false, overflow: false, style: { HcTextStroke: '3px rgba(255,255,255,0.5)' } } }); seriesTypes.mappoint = extendClass(seriesTypes.scatter, { type: 'mappoint', forceDL: true });/* **************************************************************************** * Start Bubble series code * *****************************************************************************/ // 1 - set default options defaultPlotOptions.bubble = merge(defaultPlotOptions.scatter, { dataLabels: { formatter: function () { // #2945 return this.point.z; }, inside: true, style: { color: 'white', textShadow: '0px 0px 3px black' }, verticalAlign: 'middle' }, // displayNegative: true, marker: { // fillOpacity: 0.5, lineColor: null, // inherit from series.color lineWidth: 1 }, minSize: 8, maxSize: '20%', // negativeColor: null, // sizeBy: 'area' states: { hover: { halo: { size: 5 } } }, tooltip: { pointFormat: '({point.x}, {point.y}), Size: {point.z}' }, turboThreshold: 0, zThreshold: 0 }); var BubblePoint = extendClass(Point, { haloPath: function () { return Point.prototype.haloPath.call(this, this.shapeArgs.r + this.series.options.states.hover.halo.size); } }); // 2 - Create the series object seriesTypes.bubble = extendClass(seriesTypes.scatter, { type: 'bubble', pointClass: BubblePoint, pointArrayMap: ['y', 'z'], parallelArrays: ['x', 'y', 'z'], trackerGroups: ['group', 'dataLabelsGroup'], bubblePadding: true, /** * Mapping between SVG attributes and the corresponding options */ pointAttrToOptions: { stroke: 'lineColor', 'stroke-width': 'lineWidth', fill: 'fillColor' }, /** * Apply the fillOpacity to all fill positions */ applyOpacity: function (fill) { var markerOptions = this.options.marker, fillOpacity = pick(markerOptions.fillOpacity, 0.5); // When called from Legend.colorizeItem, the fill isn't predefined fill = fill || markerOptions.fillColor || this.color; if (fillOpacity !== 1) { fill = Color(fill).setOpacity(fillOpacity).get('rgba'); } return fill; }, /** * Extend the convertAttribs method by applying opacity to the fill */ convertAttribs: function () { var obj = Series.prototype.convertAttribs.apply(this, arguments); obj.fill = this.applyOpacity(obj.fill); return obj; }, /** * Get the radius for each point based on the minSize, maxSize and each point's Z value. This * must be done prior to Series.translate because the axis needs to add padding in * accordance with the point sizes. */ getRadii: function (zMin, zMax, minSize, maxSize) { var len, i, pos, zData = this.zData, radii = [], sizeByArea = this.options.sizeBy !== 'width', zRange; // Set the shape type and arguments to be picked up in drawPoints for (i = 0, len = zData.length; i < len; i++) { zRange = zMax - zMin; pos = zRange > 0 ? // relative size, a number between 0 and 1 (zData[i] - zMin) / (zMax - zMin) : 0.5; if (sizeByArea && pos >= 0) { pos = Math.sqrt(pos); } radii.push(math.ceil(minSize + pos * (maxSize - minSize)) / 2); } this.radii = radii; }, /** * Perform animation on the bubbles */ animate: function (init) { var animation = this.options.animation; if (!init) { // run the animation each(this.points, function (point) { var graphic = point.graphic, shapeArgs = point.shapeArgs; if (graphic && shapeArgs) { // start values graphic.attr('r', 1); // animate graphic.animate({ r: shapeArgs.r }, animation); } }); // delete this function to allow it only once this.animate = null; } }, /** * Extend the base translate method to handle bubble size */ translate: function () { var i, data = this.data, point, radius, radii = this.radii; // Run the parent method seriesTypes.scatter.prototype.translate.call(this); // Set the shape type and arguments to be picked up in drawPoints i = data.length; while (i--) { point = data[i]; radius = radii ? radii[i] : 0; // #1737 // Flag for negativeColor to be applied in Series.js point.negative = point.z < (this.options.zThreshold || 0); if (radius >= this.minPxSize / 2) { // Shape arguments point.shapeType = 'circle'; point.shapeArgs = { x: point.plotX, y: point.plotY, r: radius }; // Alignment box for the data label point.dlBox = { x: point.plotX - radius, y: point.plotY - radius, width: 2 * radius, height: 2 * radius }; } else { // below zThreshold point.shapeArgs = point.plotY = point.dlBox = UNDEFINED; // #1691 } } }, /** * Get the series' symbol in the legend * * @param {Object} legend The legend object * @param {Object} item The series (this) or point */ drawLegendSymbol: function (legend, item) { var radius = pInt(legend.itemStyle.fontSize) / 2; item.legendSymbol = this.chart.renderer.circle( radius, legend.baseline - radius, radius ).attr({ zIndex: 3 }).add(item.legendGroup); item.legendSymbol.isMarker = true; }, drawPoints: seriesTypes.column.prototype.drawPoints, alignDataLabel: seriesTypes.column.prototype.alignDataLabel }); /** * Add logic to pad each axis with the amount of pixels * necessary to avoid the bubbles to overflow. */ Axis.prototype.beforePadding = function () { var axis = this, axisLength = this.len, chart = this.chart, pxMin = 0, pxMax = axisLength, isXAxis = this.isXAxis, dataKey = isXAxis ? 'xData' : 'yData', min = this.min, extremes = {}, smallestSize = math.min(chart.plotWidth, chart.plotHeight), zMin = Number.MAX_VALUE, zMax = -Number.MAX_VALUE, range = this.max - min, transA = axisLength / range, activeSeries = []; // Handle padding on the second pass, or on redraw if (this.tickPositions) { each(this.series, function (series) { var seriesOptions = series.options, zData; if (series.bubblePadding && (series.visible || !chart.options.chart.ignoreHiddenSeries)) { // Correction for #1673 axis.allowZoomOutside = true; // Cache it activeSeries.push(series); if (isXAxis) { // because X axis is evaluated first // For each series, translate the size extremes to pixel values each(['minSize', 'maxSize'], function (prop) { var length = seriesOptions[prop], isPercent = /%$/.test(length); length = pInt(length); extremes[prop] = isPercent ? smallestSize * length / 100 : length; }); series.minPxSize = extremes.minSize; // Find the min and max Z zData = series.zData; if (zData.length) { // #1735 zMin = pick(seriesOptions.zMin, math.min( zMin, math.max( arrayMin(zData), seriesOptions.displayNegative === false ? seriesOptions.zThreshold : -Number.MAX_VALUE ) )); zMax = pick(seriesOptions.zMax, math.max(zMax, arrayMax(zData))); } } } }); each(activeSeries, function (series) { var data = series[dataKey], i = data.length, radius; if (isXAxis) { series.getRadii(zMin, zMax, extremes.minSize, extremes.maxSize); } if (range > 0) { while (i--) { if (typeof data[i] === 'number') { radius = series.radii[i]; pxMin = Math.min(((data[i] - min) * transA) - radius, pxMin); pxMax = Math.max(((data[i] - min) * transA) + radius, pxMax); } } } }); if (activeSeries.length && range > 0 && pick(this.options.min, this.userMin) === UNDEFINED && pick(this.options.max, this.userMax) === UNDEFINED) { pxMax -= axisLength; transA *= (axisLength + pxMin - pxMax) / axisLength; this.min += pxMin / transA; this.max += pxMax / transA; } } }; /* **************************************************************************** * End Bubble series code * *****************************************************************************/ // The mapbubble series type if (seriesTypes.bubble) { defaultPlotOptions.mapbubble = merge(defaultPlotOptions.bubble, { animationLimit: 500, tooltip: { pointFormat: '{point.name}: {point.z}' } }); seriesTypes.mapbubble = extendClass(seriesTypes.bubble, { pointClass: extendClass(Point, { applyOptions: MapAreaPoint.prototype.applyOptions }), xyFromShape: true, type: 'mapbubble', pointArrayMap: ['z'], // If one single value is passed, it is interpreted as z /** * Return the map area identified by the dataJoinBy option */ getMapData: seriesTypes.map.prototype.getMapData, getBox: seriesTypes.map.prototype.getBox, setData: seriesTypes.map.prototype.setData }); } /** * Convert a geojson object to map data of a given Highcharts type (map, mappoint or mapline). */ Highcharts.geojson = function (geojson, hType, series) { var mapData = [], path = [], polygonToPath = function (polygon) { var i = 0, len = polygon.length; path.push('M'); for (; i < len; i++) { if (i === 1) { path.push('L'); } path.push(polygon[i][0], -polygon[i][1]); } }; hType = hType || 'map'; each(geojson.features, function (feature) { var geometry = feature.geometry, type = geometry.type, coordinates = geometry.coordinates, properties = feature.properties, point; path = []; if (hType === 'map' || hType === 'mapbubble') { if (type === 'Polygon') { each(coordinates, polygonToPath); path.push('Z'); } else if (type === 'MultiPolygon') { each(coordinates, function (items) { each(items, polygonToPath); }); path.push('Z'); } if (path.length) { point = { path: path }; } } else if (hType === 'mapline') { if (type === 'LineString') { polygonToPath(coordinates); } else if (type === 'MultiLineString') { each(coordinates, polygonToPath); } if (path.length) { point = { path: path }; } } else if (hType === 'mappoint') { if (type === 'Point') { point = { x: coordinates[0], y: -coordinates[1] }; } } if (point) { mapData.push(extend(point, { name: properties.name || properties.NAME, properties: properties })); } }); // Create a credits text that includes map source, to be picked up in Chart.showCredits if (series) { series.chart.mapCredits = '<a href="http://www.highcharts.com">Highcharts</a> \u00A9 ' + '<a href="' + geojson.copyrightUrl + '">' + geojson.copyrightShort + '</a>'; } return mapData; }; /** * Override showCredits to include map source by default */ wrap(Chart.prototype, 'showCredits', function (proceed, credits) { if (defaultOptions.credits.text === this.options.credits.text && this.mapCredits) { // default text and mapCredits is set credits.text = this.mapCredits; credits.href = null; } proceed.call(this, credits); }); // Add language extend(defaultOptions.lang, { zoomIn: 'Zoom in', zoomOut: 'Zoom out' }); // Set the default map navigation options defaultOptions.mapNavigation = { buttonOptions: { alignTo: 'plotBox', align: 'left', verticalAlign: 'top', x: 0, width: 18, height: 18, style: { fontSize: '15px', fontWeight: 'bold', textAlign: 'center' }, theme: { 'stroke-width': 1 } }, buttons: { zoomIn: { onclick: function () { this.mapZoom(0.5); }, text: '+', y: 0 }, zoomOut: { onclick: function () { this.mapZoom(2); }, text: '-', y: 28 } } // enabled: false, // enableButtons: null, // inherit from enabled // enableTouchZoom: null, // inherit from enabled // enableDoubleClickZoom: null, // inherit from enabled // enableDoubleClickZoomTo: false // enableMouseWheelZoom: null, // inherit from enabled }; /** * Utility for reading SVG paths directly. */ Highcharts.splitPath = function (path) { var i; // Move letters apart path = path.replace(/([A-Za-z])/g, ' $1 '); // Trim path = path.replace(/^\s*/, "").replace(/\s*$/, ""); // Split on spaces and commas path = path.split(/[ ,]+/); // Parse numbers for (i = 0; i < path.length; i++) { if (!/[a-zA-Z]/.test(path[i])) { path[i] = parseFloat(path[i]); } } return path; }; // A placeholder for map definitions Highcharts.maps = {}; // Create symbols for the zoom buttons function selectiveRoundedRect(attr, x, y, w, h, rTopLeft, rTopRight, rBottomRight, rBottomLeft) { var normalize = (attr['stroke-width'] % 2 / 2); x -= normalize; y -= normalize; return ['M', x + rTopLeft, y, // top side 'L', x + w - rTopRight, y, // top right corner 'C', x + w - rTopRight / 2, y, x + w, y + rTopRight / 2, x + w, y + rTopRight, // right side 'L', x + w, y + h - rBottomRight, // bottom right corner 'C', x + w, y + h - rBottomRight / 2, x + w - rBottomRight / 2, y + h, x + w - rBottomRight, y + h, // bottom side 'L', x + rBottomLeft, y + h, // bottom left corner 'C', x + rBottomLeft / 2, y + h, x, y + h - rBottomLeft / 2, x, y + h - rBottomLeft, // left side 'L', x, y + rTopLeft, // top left corner 'C', x, y + rTopLeft / 2, x + rTopLeft / 2, y, x + rTopLeft, y, 'Z' ]; } SVGRenderer.prototype.symbols.topbutton = function (x, y, w, h, attr) { return selectiveRoundedRect(attr, x, y, w, h, attr.r, attr.r, 0, 0); }; SVGRenderer.prototype.symbols.bottombutton = function (x, y, w, h, attr) { return selectiveRoundedRect(attr, x, y, w, h, 0, 0, attr.r, attr.r); }; // The symbol callbacks are generated on the SVGRenderer object in all browsers. Even // VML browsers need this in order to generate shapes in export. Now share // them with the VMLRenderer. if (Renderer === VMLRenderer) { each(['topbutton', 'bottombutton'], function (shape) { VMLRenderer.prototype.symbols[shape] = SVGRenderer.prototype.symbols[shape]; }); } /** * A wrapper for Chart with all the default values for a Map */ Highcharts.Map = function (options, callback) { var hiddenAxis = { endOnTick: false, gridLineWidth: 0, lineWidth: 0, minPadding: 0, maxPadding: 0, startOnTick: false, title: null, tickPositions: [] }, seriesOptions; /* For visual testing hiddenAxis.gridLineWidth = 1; hiddenAxis.gridZIndex = 10; hiddenAxis.tickPositions = undefined; // */ // Don't merge the data seriesOptions = options.series; options.series = null; options = merge({ chart: { panning: 'xy', type: 'map' }, xAxis: hiddenAxis, yAxis: merge(hiddenAxis, { reversed: true }) }, options, // user's options { // forced options chart: { inverted: false, alignTicks: false, preserveAspectRatio: true } }); options.series = seriesOptions; return new Chart(options, callback); }; /** * Extend the default options with map options */ defaultOptions.plotOptions.heatmap = merge(defaultOptions.plotOptions.scatter, { animation: false, borderWidth: 0, nullColor: '#F8F8F8', dataLabels: { formatter: function () { // #2945 return this.point.value; }, verticalAlign: 'middle', crop: false, overflow: false, style: { color: 'white', fontWeight: 'bold', HcTextStroke: '1px rgba(0,0,0,0.5)' } }, marker: null, tooltip: { pointFormat: '{point.x}, {point.y}: {point.value}<br/>' }, states: { normal: { animation: true }, hover: { brightness: 0.2 } } }); // The Heatmap series type seriesTypes.heatmap = extendClass(seriesTypes.scatter, merge(colorSeriesMixin, { type: 'heatmap', pointArrayMap: ['y', 'value'], hasPointSpecificOptions: true, supportsDrilldown: true, getExtremesFromAll: true, init: function () { seriesTypes.scatter.prototype.init.apply(this, arguments); this.pointRange = this.options.colsize || 1; this.yAxis.axisPointRange = this.options.rowsize || 1; // general point range }, translate: function () { var series = this, options = series.options, xAxis = series.xAxis, yAxis = series.yAxis; series.generatePoints(); each(series.points, function (point) { var xPad = (options.colsize || 1) / 2, yPad = (options.rowsize || 1) / 2, x1 = Math.round(xAxis.len - xAxis.translate(point.x - xPad, 0, 1, 0, 1)), x2 = Math.round(xAxis.len - xAxis.translate(point.x + xPad, 0, 1, 0, 1)), y1 = Math.round(yAxis.translate(point.y - yPad, 0, 1, 0, 1)), y2 = Math.round(yAxis.translate(point.y + yPad, 0, 1, 0, 1)); // Set plotX and plotY for use in K-D-Tree and more point.plotX = (x1 + x2) / 2; point.plotY = (y1 + y2) / 2; point.shapeType = 'rect'; point.shapeArgs = { x: Math.min(x1, x2), y: Math.min(y1, y2), width: Math.abs(x2 - x1), height: Math.abs(y2 - y1) }; }); series.translateColors(); // Make sure colors are updated on colorAxis update (#2893) if (this.chart.hasRendered) { each(series.points, function (point) { point.shapeArgs.fill = point.options.color || point.color; // #3311 }); } }, drawPoints: seriesTypes.column.prototype.drawPoints, animate: noop, getBox: noop, drawLegendSymbol: LegendSymbolMixin.drawRectangle, getExtremes: function () { // Get the extremes from the value data Series.prototype.getExtremes.call(this, this.valueData); this.valueMin = this.dataMin; this.valueMax = this.dataMax; // Get the extremes from the y data Series.prototype.getExtremes.call(this); } })); /** * TrackerMixin for points and graphs */ var TrackerMixin = Highcharts.TrackerMixin = { drawTrackerPoint: function () { var series = this, chart = series.chart, pointer = chart.pointer, cursor = series.options.cursor, css = cursor && { cursor: cursor }, onMouseOver = function (e) { var target = e.target, point; if (chart.hoverSeries !== series) { series.onMouseOver(); } while (target && !point) { point = target.point; target = target.parentNode; } if (point !== UNDEFINED && point !== chart.hoverPoint) { // undefined on graph in scatterchart point.onMouseOver(e); } }; // Add reference to the point each(series.points, function (point) { if (point.graphic) { point.graphic.element.point = point; } if (point.dataLabel) { point.dataLabel.element.point = point; } }); // Add the event listeners, we need to do this only once if (!series._hasTracking) { each(series.trackerGroups, function (key) { if (series[key]) { // we don't always have dataLabelsGroup series[key] .addClass(PREFIX + 'tracker') .on('mouseover', onMouseOver) .on('mouseout', function (e) { pointer.onTrackerMouseOut(e); }) .css(css); if (hasTouch) { series[key].on('touchstart', onMouseOver); } } }); series._hasTracking = true; } }, /** * Draw the tracker object that sits above all data labels and markers to * track mouse events on the graph or points. For the line type charts * the tracker uses the same graphPath, but with a greater stroke width * for better control. */ drawTrackerGraph: function () { var series = this, options = series.options, trackByArea = options.trackByArea, trackerPath = [].concat(trackByArea ? series.areaPath : series.graphPath), trackerPathLength = trackerPath.length, chart = series.chart, pointer = chart.pointer, renderer = chart.renderer, snap = chart.options.tooltip.snap, tracker = series.tracker, cursor = options.cursor, css = cursor && { cursor: cursor }, singlePoints = series.singlePoints, singlePoint, i, onMouseOver = function () { if (chart.hoverSeries !== series) { series.onMouseOver(); } }, /* * Empirical lowest possible opacities for TRACKER_FILL for an element to stay invisible but clickable * IE6: 0.002 * IE7: 0.002 * IE8: 0.002 * IE9: 0.00000000001 (unlimited) * IE10: 0.0001 (exporting only) * FF: 0.00000000001 (unlimited) * Chrome: 0.000001 * Safari: 0.000001 * Opera: 0.00000000001 (unlimited) */ TRACKER_FILL = 'rgba(192,192,192,' + (hasSVG ? 0.0001 : 0.002) + ')'; // Extend end points. A better way would be to use round linecaps, // but those are not clickable in VML. if (trackerPathLength && !trackByArea) { i = trackerPathLength + 1; while (i--) { if (trackerPath[i] === M) { // extend left side trackerPath.splice(i + 1, 0, trackerPath[i + 1] - snap, trackerPath[i + 2], L); } if ((i && trackerPath[i] === M) || i === trackerPathLength) { // extend right side trackerPath.splice(i, 0, L, trackerPath[i - 2] + snap, trackerPath[i - 1]); } } } // handle single points for (i = 0; i < singlePoints.length; i++) { singlePoint = singlePoints[i]; trackerPath.push(M, singlePoint.plotX - snap, singlePoint.plotY, L, singlePoint.plotX + snap, singlePoint.plotY); } // draw the tracker if (tracker) { tracker.attr({ d: trackerPath }); } else { // create series.tracker = renderer.path(trackerPath) .attr({ 'stroke-linejoin': 'round', // #1225 visibility: series.visible ? VISIBLE : HIDDEN, stroke: TRACKER_FILL, fill: trackByArea ? TRACKER_FILL : NONE, 'stroke-width' : options.lineWidth + (trackByArea ? 0 : 2 * snap), zIndex: 2 }) .add(series.group); // The tracker is added to the series group, which is clipped, but is covered // by the marker group. So the marker group also needs to capture events. each([series.tracker, series.markerGroup], function (tracker) { tracker.addClass(PREFIX + 'tracker') .on('mouseover', onMouseOver) .on('mouseout', function (e) { pointer.onTrackerMouseOut(e); }) .css(css); if (hasTouch) { tracker.on('touchstart', onMouseOver); } }); } } }; /* End TrackerMixin */ /** * Add tracking event listener to the series group, so the point graphics * themselves act as trackers */ if (seriesTypes.column) { ColumnSeries.prototype.drawTracker = TrackerMixin.drawTrackerPoint; } if (seriesTypes.pie) { seriesTypes.pie.prototype.drawTracker = TrackerMixin.drawTrackerPoint; } if (seriesTypes.scatter) { ScatterSeries.prototype.drawTracker = TrackerMixin.drawTrackerPoint; } /* * Extend Legend for item events */ extend(Legend.prototype, { setItemEvents: function (item, legendItem, useHTML, itemStyle, itemHiddenStyle) { var legend = this; // Set the events on the item group, or in case of useHTML, the item itself (#1249) (useHTML ? legendItem : item.legendGroup).on('mouseover', function () { item.setState(HOVER_STATE); legendItem.css(legend.options.itemHoverStyle); }) .on('mouseout', function () { legendItem.css(item.visible ? itemStyle : itemHiddenStyle); item.setState(); }) .on('click', function (event) { var strLegendItemClick = 'legendItemClick', fnLegendItemClick = function () { item.setVisible(); }; // Pass over the click/touch event. #4. event = { browserEvent: event }; // click the name or symbol if (item.firePointEvent) { // point item.firePointEvent(strLegendItemClick, event, fnLegendItemClick); } else { fireEvent(item, strLegendItemClick, event, fnLegendItemClick); } }); }, createCheckboxForItem: function (item) { var legend = this; item.checkbox = createElement('input', { type: 'checkbox', checked: item.selected, defaultChecked: item.selected // required by IE7 }, legend.options.itemCheckboxStyle, legend.chart.container); addEvent(item.checkbox, 'click', function (event) { var target = event.target; fireEvent(item, 'checkboxClick', { checked: target.checked }, function () { item.select(); } ); }); } }); /* * Add pointer cursor to legend itemstyle in defaultOptions */ defaultOptions.legend.itemStyle.cursor = 'pointer'; /* * Extend the Chart object with interaction */ extend(Chart.prototype, { /** * Display the zoom button */ showResetZoom: function () { var chart = this, lang = defaultOptions.lang, btnOptions = chart.options.chart.resetZoomButton, theme = btnOptions.theme, states = theme.states, alignTo = btnOptions.relativeTo === 'chart' ? null : 'plotBox'; this.resetZoomButton = chart.renderer.button(lang.resetZoom, null, null, function () { chart.zoomOut(); }, theme, states && states.hover) .attr({ align: btnOptions.position.align, title: lang.resetZoomTitle }) .add() .align(btnOptions.position, false, alignTo); }, /** * Zoom out to 1:1 */ zoomOut: function () { var chart = this; fireEvent(chart, 'selection', { resetSelection: true }, function () { chart.zoom(); }); }, /** * Zoom into a given portion of the chart given by axis coordinates * @param {Object} event */ zoom: function (event) { var chart = this, hasZoomed, pointer = chart.pointer, displayButton = false, resetZoomButton; // If zoom is called with no arguments, reset the axes if (!event || event.resetSelection) { each(chart.axes, function (axis) { hasZoomed = axis.zoom(); }); } else { // else, zoom in on all axes each(event.xAxis.concat(event.yAxis), function (axisData) { var axis = axisData.axis, isXAxis = axis.isXAxis; // don't zoom more than minRange if (pointer[isXAxis ? 'zoomX' : 'zoomY'] || pointer[isXAxis ? 'pinchX' : 'pinchY']) { hasZoomed = axis.zoom(axisData.min, axisData.max); if (axis.displayBtn) { displayButton = true; } } }); } // Show or hide the Reset zoom button resetZoomButton = chart.resetZoomButton; if (displayButton && !resetZoomButton) { chart.showResetZoom(); } else if (!displayButton && isObject(resetZoomButton)) { chart.resetZoomButton = resetZoomButton.destroy(); } // Redraw if (hasZoomed) { chart.redraw( pick(chart.options.chart.animation, event && event.animation, chart.pointCount < 100) // animation ); } }, /** * Pan the chart by dragging the mouse across the pane. This function is called * on mouse move, and the distance to pan is computed from chartX compared to * the first chartX position in the dragging operation. */ pan: function (e, panning) { var chart = this, hoverPoints = chart.hoverPoints, doRedraw; // remove active points for shared tooltip if (hoverPoints) { each(hoverPoints, function (point) { point.setState(); }); } each(panning === 'xy' ? [1, 0] : [1], function (isX) { // xy is used in maps var mousePos = e[isX ? 'chartX' : 'chartY'], axis = chart[isX ? 'xAxis' : 'yAxis'][0], startPos = chart[isX ? 'mouseDownX' : 'mouseDownY'], halfPointRange = (axis.pointRange || 0) / 2, extremes = axis.getExtremes(), newMin = axis.toValue(startPos - mousePos, true) + halfPointRange, newMax = axis.toValue(startPos + chart[isX ? 'plotWidth' : 'plotHeight'] - mousePos, true) - halfPointRange; if (axis.series.length && newMin > mathMin(extremes.dataMin, extremes.min) && newMax < mathMax(extremes.dataMax, extremes.max)) { axis.setExtremes(newMin, newMax, false, false, { trigger: 'pan' }); doRedraw = true; } chart[isX ? 'mouseDownX' : 'mouseDownY'] = mousePos; // set new reference for next run }); if (doRedraw) { chart.redraw(false); } css(chart.container, { cursor: 'move' }); } }); /* * Extend the Point object with interaction */ extend(Point.prototype, { /** * Toggle the selection status of a point * @param {Boolean} selected Whether to select or unselect the point. * @param {Boolean} accumulate Whether to add to the previous selection. By default, * this happens if the control key (Cmd on Mac) was pressed during clicking. */ select: function (selected, accumulate) { var point = this, series = point.series, chart = series.chart; selected = pick(selected, !point.selected); // fire the event with the defalut handler point.firePointEvent(selected ? 'select' : 'unselect', { accumulate: accumulate }, function () { point.selected = point.options.selected = selected; series.options.data[inArray(point, series.data)] = point.options; point.setState(selected && SELECT_STATE); // unselect all other points unless Ctrl or Cmd + click if (!accumulate) { each(chart.getSelectedPoints(), function (loopPoint) { if (loopPoint.selected && loopPoint !== point) { loopPoint.selected = loopPoint.options.selected = false; series.options.data[inArray(loopPoint, series.data)] = loopPoint.options; loopPoint.setState(NORMAL_STATE); loopPoint.firePointEvent('unselect'); } }); } }); }, /** * Runs on mouse over the point */ onMouseOver: function (e) { var point = this, series = point.series, chart = series.chart, tooltip = chart.tooltip, hoverPoint = chart.hoverPoint; // set normal state to previous series if (hoverPoint && hoverPoint !== point) { hoverPoint.onMouseOut(); } // trigger the event point.firePointEvent('mouseOver'); // update the tooltip if (tooltip && (!tooltip.shared || series.noSharedTooltip)) { tooltip.refresh(point, e); } // hover this point.setState(HOVER_STATE); chart.hoverPoint = point; }, /** * Runs on mouse out from the point */ onMouseOut: function () { var chart = this.series.chart, hoverPoints = chart.hoverPoints; this.firePointEvent('mouseOut'); if (!hoverPoints || inArray(this, hoverPoints) === -1) { // #887, #2240 this.setState(); chart.hoverPoint = null; } }, /** * Import events from the series' and point's options. Only do it on * demand, to save processing time on hovering. */ importEvents: function () { if (!this.hasImportedEvents) { var point = this, options = merge(point.series.options.point, point.options), events = options.events, eventType; point.events = events; for (eventType in events) { addEvent(point, eventType, events[eventType]); } this.hasImportedEvents = true; } }, /** * Set the point's state * @param {String} state */ setState: function (state, move) { var point = this, plotX = point.plotX, plotY = point.plotY, series = point.series, stateOptions = series.options.states, markerOptions = defaultPlotOptions[series.type].marker && series.options.marker, normalDisabled = markerOptions && !markerOptions.enabled, markerStateOptions = markerOptions && markerOptions.states[state], stateDisabled = markerStateOptions && markerStateOptions.enabled === false, stateMarkerGraphic = series.stateMarkerGraphic, pointMarker = point.marker || {}, chart = series.chart, radius, halo = series.halo, haloOptions, newSymbol, pointAttr; state = state || NORMAL_STATE; // empty string pointAttr = point.pointAttr[state] || series.pointAttr[state]; if ( // already has this state (state === point.state && !move) || // selected points don't respond to hover (point.selected && state !== SELECT_STATE) || // series' state options is disabled (stateOptions[state] && stateOptions[state].enabled === false) || // general point marker's state options is disabled (state && (stateDisabled || (normalDisabled && markerStateOptions.enabled === false))) || // individual point marker's state options is disabled (state && pointMarker.states && pointMarker.states[state] && pointMarker.states[state].enabled === false) // #1610 ) { return; } // apply hover styles to the existing point if (point.graphic) { radius = markerOptions && point.graphic.symbolName && pointAttr.r; point.graphic.attr(merge( pointAttr, radius ? { // new symbol attributes (#507, #612) x: plotX - radius, y: plotY - radius, width: 2 * radius, height: 2 * radius } : {} )); // Zooming in from a range with no markers to a range with markers if (stateMarkerGraphic) { stateMarkerGraphic.hide(); } } else { // if a graphic is not applied to each point in the normal state, create a shared // graphic for the hover state if (state && markerStateOptions) { radius = markerStateOptions.radius; newSymbol = pointMarker.symbol || series.symbol; // If the point has another symbol than the previous one, throw away the // state marker graphic and force a new one (#1459) if (stateMarkerGraphic && stateMarkerGraphic.currentSymbol !== newSymbol) { stateMarkerGraphic = stateMarkerGraphic.destroy(); } // Add a new state marker graphic if (!stateMarkerGraphic) { if (newSymbol) { series.stateMarkerGraphic = stateMarkerGraphic = chart.renderer.symbol( newSymbol, plotX - radius, plotY - radius, 2 * radius, 2 * radius ) .attr(pointAttr) .add(series.markerGroup); stateMarkerGraphic.currentSymbol = newSymbol; } // Move the existing graphic } else { stateMarkerGraphic[move ? 'animate' : 'attr']({ // #1054 x: plotX - radius, y: plotY - radius }); } } if (stateMarkerGraphic) { stateMarkerGraphic[state && chart.isInsidePlot(plotX, plotY, chart.inverted) ? 'show' : 'hide'](); // #2450 } } // Show me your halo haloOptions = stateOptions[state] && stateOptions[state].halo; if (haloOptions && haloOptions.size) { if (!halo) { series.halo = halo = chart.renderer.path() .add(series.seriesGroup); } halo.attr(extend({ fill: Color(point.color || series.color).setOpacity(haloOptions.opacity).get() }, haloOptions.attributes))[move ? 'animate' : 'attr']({ d: point.haloPath(haloOptions.size) }); } else if (halo) { halo.attr({ d: [] }); } point.state = state; }, haloPath: function (size) { var series = this.series, chart = series.chart, plotBox = series.getPlotBox(), inverted = chart.inverted; return chart.renderer.symbols.circle( plotBox.translateX + (inverted ? series.yAxis.len - this.plotY : this.plotX) - size, plotBox.translateY + (inverted ? series.xAxis.len - this.plotX : this.plotY) - size, size * 2, size * 2 ); } }); /* * Extend the Series object with interaction */ extend(Series.prototype, { /** * Series mouse over handler */ onMouseOver: function () { var series = this, chart = series.chart, hoverSeries = chart.hoverSeries; // set normal state to previous series if (hoverSeries && hoverSeries !== series) { hoverSeries.onMouseOut(); } // trigger the event, but to save processing time, // only if defined if (series.options.events.mouseOver) { fireEvent(series, 'mouseOver'); } // hover this series.setState(HOVER_STATE); chart.hoverSeries = series; }, /** * Series mouse out handler */ onMouseOut: function () { // trigger the event only if listeners exist var series = this, options = series.options, chart = series.chart, tooltip = chart.tooltip, hoverPoint = chart.hoverPoint; // trigger mouse out on the point, which must be in this series if (hoverPoint) { hoverPoint.onMouseOut(); } // fire the mouse out event if (series && options.events.mouseOut) { fireEvent(series, 'mouseOut'); } // hide the tooltip if (tooltip && !options.stickyTracking && (!tooltip.shared || series.noSharedTooltip)) { tooltip.hide(); } // set normal state series.setState(); chart.hoverSeries = null; }, /** * Set the state of the graph */ setState: function (state) { var series = this, options = series.options, graph = series.graph, graphNeg = series.graphNeg, stateOptions = options.states, lineWidth = options.lineWidth, attribs; state = state || NORMAL_STATE; if (series.state !== state) { series.state = state; if (stateOptions[state] && stateOptions[state].enabled === false) { return; } if (state) { lineWidth = stateOptions[state].lineWidth || lineWidth + (stateOptions[state].lineWidthPlus || 0); } if (graph && !graph.dashstyle) { // hover is turned off for dashed lines in VML attribs = { 'stroke-width': lineWidth }; // use attr because animate will cause any other animation on the graph to stop graph.attr(attribs); if (graphNeg) { graphNeg.attr(attribs); } } } }, /** * Set the visibility of the graph * * @param vis {Boolean} True to show the series, false to hide. If UNDEFINED, * the visibility is toggled. */ setVisible: function (vis, redraw) { var series = this, chart = series.chart, legendItem = series.legendItem, showOrHide, ignoreHiddenSeries = chart.options.chart.ignoreHiddenSeries, oldVisibility = series.visible; // if called without an argument, toggle visibility series.visible = vis = series.userOptions.visible = vis === UNDEFINED ? !oldVisibility : vis; showOrHide = vis ? 'show' : 'hide'; // show or hide elements each(['group', 'dataLabelsGroup', 'markerGroup', 'tracker'], function (key) { if (series[key]) { series[key][showOrHide](); } }); // hide tooltip (#1361) if (chart.hoverSeries === series) { series.onMouseOut(); } if (legendItem) { chart.legend.colorizeItem(series, vis); } // rescale or adapt to resized chart series.isDirty = true; // in a stack, all other series are affected if (series.options.stacking) { each(chart.series, function (otherSeries) { if (otherSeries.options.stacking && otherSeries.visible) { otherSeries.isDirty = true; } }); } // show or hide linked series each(series.linkedSeries, function (otherSeries) { otherSeries.setVisible(vis, false); }); if (ignoreHiddenSeries) { chart.isDirtyBox = true; } if (redraw !== false) { chart.redraw(); } fireEvent(series, showOrHide); }, /** * Memorize tooltip texts and positions */ setTooltipPoints: function (renew) { var series = this, points = [], pointsLength, low, high, xAxis = series.xAxis, xExtremes = xAxis && xAxis.getExtremes(), axisLength = xAxis ? (xAxis.tooltipLen || xAxis.len) : series.chart.plotSizeX, // tooltipLen and tooltipPosName used in polar point, pointX, nextPoint, i, tooltipPoints = []; // a lookup array for each pixel in the x dimension // don't waste resources if tracker is disabled if (series.options.enableMouseTracking === false || series.singularTooltips) { return; } // renew if (renew) { series.tooltipPoints = null; } // concat segments to overcome null values each(series.segments || series.points, function (segment) { points = points.concat(segment); }); // Reverse the points in case the X axis is reversed if (xAxis && xAxis.reversed) { points = points.reverse(); } // Polar needs additional shaping if (series.orderTooltipPoints) { series.orderTooltipPoints(points); } // Assign each pixel position to the nearest point pointsLength = points.length; for (i = 0; i < pointsLength; i++) { point = points[i]; pointX = point.x; if (pointX >= xExtremes.min && pointX <= xExtremes.max) { // #1149 nextPoint = points[i + 1]; // Set this range's low to the last range's high plus one low = high === UNDEFINED ? 0 : high + 1; // Now find the new high high = points[i + 1] ? mathMin(mathMax(0, mathFloor( // #2070 (point.clientX + (nextPoint ? (nextPoint.wrappedClientX || nextPoint.clientX) : axisLength)) / 2 )), axisLength) : axisLength; while (low >= 0 && low <= high) { tooltipPoints[low++] = point; } } } series.tooltipPoints = tooltipPoints; }, /** * Show the graph */ show: function () { this.setVisible(true); }, /** * Hide the graph */ hide: function () { this.setVisible(false); }, /** * Set the selected state of the graph * * @param selected {Boolean} True to select the series, false to unselect. If * UNDEFINED, the selection state is toggled. */ select: function (selected) { var series = this; // if called without an argument, toggle series.selected = selected = (selected === UNDEFINED) ? !series.selected : selected; if (series.checkbox) { series.checkbox.checked = selected; } fireEvent(series, selected ? 'select' : 'unselect'); }, drawTracker: TrackerMixin.drawTrackerGraph }); // global variables extend(Highcharts, { // Constructors Axis: Axis, Chart: Chart, Color: Color, Point: Point, Tick: Tick, Renderer: Renderer, Series: Series, SVGElement: SVGElement, SVGRenderer: SVGRenderer, // Various arrayMin: arrayMin, arrayMax: arrayMax, charts: charts, dateFormat: dateFormat, format: format, pathAnim: pathAnim, getOptions: getOptions, hasBidiBug: hasBidiBug, isTouchDevice: isTouchDevice, numberFormat: numberFormat, seriesTypes: seriesTypes, setOptions: setOptions, addEvent: addEvent, removeEvent: removeEvent, createElement: createElement, discardElement: discardElement, css: css, each: each, extend: extend, map: map, merge: merge, pick: pick, splat: splat, extendClass: extendClass, pInt: pInt, wrap: wrap, svg: hasSVG, canvas: useCanVG, vml: !hasSVG && !useCanVG, product: PRODUCT, version: VERSION }); }());
dist/1.8.1/jquery-css-dimensions.js
michael829/jquery-builder
/*! * jQuery JavaScript Library v1.8.1 -css,-effects,-offset,-dimensions * 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: Sun Sep 23 2012 10:59:53 GMT-0700 (PDT) */ (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 -css,-effects,-offset,-dimensions", // 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 cachedruns, assertGetIdNotName, Expr, getText, isXML, contains, compile, sortOrder, hasDuplicate, outermostContext, baseHasDuplicate = true, strundefined = "undefined", expando = ( "sizcache" + Math.random() ).replace( ".", "" ), Token = String, document = window.document, docElem = document.documentElement, dirruns = 0, done = 0, pop = [].pop, push = [].push, slice = [].slice, // Use a stripped-down indexOf if a native one is unavailable indexOf = [].indexOf || function( elem ) { var i = 0, len = this.length; for ( ; i < len; i++ ) { if ( this[i] === elem ) { return i; } } return -1; }, // Augment a function for special use by Sizzle markFunction = function( fn, value ) { fn[ expando ] = value == null || value; 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 = ":(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", // 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 ), "POS": new RegExp( pos, "i" ), "CHILD": new RegExp( "^:(only|nth|first|last)-child(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), // 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 ( !selector || typeof selector !== "string" ) { return results; } if ( nodeType !== 1 && nodeType !== 9 ) { return []; } 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.replace( rtrim, "$1" ), 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; }; } // Returns a function to use in pseudos for positionals 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]); } } }); }); } /** * 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( 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 val, xml = isXML( elem ); if ( !xml ) { name = name.toLowerCase(); } if ( (val = Expr.attrHandle[ name ]) ) { return val( elem ); } if ( xml || assertAttributes ) { return elem.getAttribute( name ); } val = elem.getAttributeNode( name ); return val ? typeof elem[ name ] === "boolean" ? elem[ name ] ? name : null : val.specified ? val.value : null : null; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, // 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": assertUsableName && function( tag, context ) { if ( typeof context.getElementsByName !== strundefined ) { return context.getElementsByName( name ); } }, "CLASS": assertUsableClassName && 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 ) { 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, 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 ) { return function( elem, context ) { 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.substr( result.length - check.length ) === check : operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.substr( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, argument, first, last ) { if ( type === "nth" ) { return function( elem ) { var node, diff, parent = elem.parentNode; if ( first === 1 && last === 0 ) { return true; } if ( parent ) { diff = 0; for ( node = parent.firstChild; node; node = node.nextSibling ) { if ( node.nodeType === 1 ) { diff++; if ( elem === node ) { break; } } } } // Incorporate the offset (or cast to NaN), then check against cycle size diff -= last; return diff === first || ( 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 ) { // 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.call( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, 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 ); return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), "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; }, "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; }, // Positional types "first": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length, argument ) { for ( var i = 0; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length, argument ) { for ( var i = 1; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { for ( var i = argument < 0 ? argument + length : argument; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { for ( var i = argument < 0 ? argument + length : argument; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; 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, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ expando ][ 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 ) { soFar = soFar.slice( match[0].length ); } groups.push( tokens = [] ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { tokens.push( matched = new Token( match.shift() ) ); soFar = soFar.slice( matched.length ); // Cast descendant combinators to space matched.type = match[0].replace( rtrim, " " ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || // The last two arguments here are (context, xml) for backCompat (match = preFilters[ type ]( match, document, true ))) ) { tokens.push( matched = new Token( match.shift() ) ); soFar = soFar.slice( matched.length ); matched.type = type; matched.matches = match; } } 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 addCombinator( matcher, combinator, base ) { var dir = combinator.dir, checkNonElements = base && combinator.dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( checkNonElements || elem.nodeType === 1 ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching if ( !xml ) { var cache, dirkey = dirruns + " " + doneName + " ", cachedkey = dirkey + cachedruns; while ( (elem = elem[ dir ]) ) { if ( checkNonElements || 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, context, xml ) ) { elem.sizset = true; return elem; } elem.sizset = false; } } } } else { while ( (elem = elem[ dir ]) ) { if ( checkNonElements || elem.nodeType === 1 ) { if ( matcher( elem, context, xml ) ) { return elem; } } } } }; } 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 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 ) { // Positional selectors apply to seed elements, so it is invalid to follow them with relative ones if ( seed && postFinder ) { return; } var i, elem, postFilterIn, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [], seed ), // 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 ) { postFilterIn = condense( matcherOut, postMap ); postFilter( postFilterIn, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = postFilterIn.length; while ( i-- ) { if ( (elem = postFilterIn[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } // Keep seed and results synchronized if ( seed ) { // Ignore postFinder because it can't coexist with seed i = preFilter && matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { seed[ preMap[i] ] = !(results[ preMap[i] ] = elem); } } } 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.call( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator( elementMatcher( matchers ), matcher ) ]; } else { // The concatenated values are (context, xml) for backCompat 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 && tokens.slice( 0, i - 1 ).join("").replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && tokens.join("") ); } 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, expandContext ) { var elem, j, matcher, setMatched = [], matchedCount = 0, i = "0", unmatched = seed && [], outermost = expandContext != null, contextBackup = outermostContext, // We must always have either seed elements or context elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ), // Nested matchers should use non-integer dirruns dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.E); if ( outermost ) { outermostContext = context !== document && context; cachedruns = superMatcher.el; } // Add elements passing elementMatchers directly to results for ( ; (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { for ( j = 0; (matcher = elementMatchers[j]); j++ ) { if ( matcher( elem, context, xml ) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; cachedruns = ++superMatcher.el; } } // 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 ) { for ( j = 0; (matcher = setMatchers[j]); 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; }; superMatcher.el = 0; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ expando ][ selector ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !group ) { group = tokenize( selector ); } i = group.length; while ( i-- ) { cached = matcherFromTokens( group[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); } return cached; }; function multipleContexts( selector, contexts, results, seed ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results, seed ); } return results; } function select( selector, context, results, seed, xml ) { var i, tokens, token, type, find, match = tokenize( selector ), j = match.length; if ( !seed ) { // Try to minimize operations if there is 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" && context.nodeType === 9 && !xml && Expr.relative[ tokens[1].type ] ) { context = Expr.find["ID"]( token.matches[0].replace( rbackslash, "" ), context, xml )[0]; if ( !context ) { return results; } selector = selector.slice( tokens.shift().length ); } // Fetch a seed set for right-to-left matching for ( i = matchExpr["POS"].test( selector ) ? -1 : tokens.length - 1; i >= 0; 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( rbackslash, "" ), rsibling.test( tokens[0].type ) && context.parentNode || context, xml )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && tokens.join(""); if ( !selector ) { push.apply( results, slice.call( seed, 0 ) ); return results; } break; } } } } } // Compile and execute a filtering function // Provide `match` to avoid retokenization if we modified the selector above compile( selector, match )( seed, context, xml, results, rsibling.test( selector ) ); return results; } if ( document.querySelectorAll ) { (function() { var disconnectedMatch, oldSelect = select, rescape = /'|\\/g, rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g, // qSa(:focus) reports false when true (Chrome 21), // A support test would require too much code (would include document ready) rbuggyQSA = [":focus"], // matchesSelector(:focus) reports false when true (Chrome 21), // 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", ":focus" ], 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 always contains :focus, so no need for a length check 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 )) ) { var groups, i, old = true, nid = expando, newContext = context, newSelector = context.nodeType === 9 && 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 ( context.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 + groups[i].join(""); } newContext = rsibling.test( selector ) && context.parentNode || context; newSelector = groups.join(","); } if ( newSelector ) { try { push.apply( results, slice.call( newContext.querySelectorAll( newSelector ), 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( "!=", pseudos ); } catch ( e ) {} }); // rbuggyMatches always contains :active and :focus, 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.pseudos["nth"] = Expr.pseudos["eq"]; // Back-compat function setFilters() {} Expr.filters = setFilters.prototype = Expr.pseudos; Expr.setFilters = new setFilters(); // 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 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); } } }; } }); } // Expose jQuery to the global object window.jQuery = window.$ = jQuery; // Expose jQuery as an AMD module, but only for AMD loaders that // understand the issues with loading multiple versions of jQuery // in a page that all might call define(). The loader will indicate // they have special allowances for multiple jQuery versions by // specifying define.amd.jQuery = true. Register as a named module, // since jQuery can be concatenated with other files that may use define, // but not use a proper concatenation script that understands anonymous // AMD modules. A named AMD is safest and most robust way to register. // Lowercase jquery is used because AMD module names are derived from // file names, and jQuery is normally delivered in a lowercase file name. // Do this after creating the global so that if an AMD module wants to call // noConflict to hide this version of jQuery, it will work. if ( typeof define === "function" && define.amd && define.amd.jQuery ) { define( "jquery", [], function () { return jQuery; } ); } })( window );
frontend/src/Components/HeartRating.js
lidarr/Lidarr
import PropTypes from 'prop-types'; import React from 'react'; import Icon from 'Components/Icon'; import { icons } from 'Helpers/Props'; import styles from './HeartRating.css'; function HeartRating({ rating, iconSize }) { return ( <span> <Icon className={styles.heart} name={icons.HEART} size={iconSize} /> {rating * 10}% </span> ); } HeartRating.propTypes = { rating: PropTypes.number.isRequired, iconSize: PropTypes.number.isRequired }; HeartRating.defaultProps = { iconSize: 14 }; export default HeartRating;
examples/js/pagination/demo.js
dana2208/react-bootstrap-table
/* eslint max-len: 0 */ import React from 'react'; import DefaultPaginationTable from './default-pagination-table'; import CustomPaginationTable from './custom-pagination-table'; import PaginationHookTable from './pagination-hook-table'; class Demo extends React.Component { render() { return ( <div> <div className='col-md-offset-1 col-md-8'> <div className='panel panel-default'> <div className='panel-heading'>Basic Pagination Example</div> <div className='panel-body'> <h5>Source in /examples/js/pagination/default-pagination-table.js</h5> <DefaultPaginationTable /> </div> </div> </div> <div className='col-md-offset-1 col-md-8'> <div className='panel panel-default'> <div className='panel-heading'>Custom Pagination Example</div> <div className='panel-body'> <h5>Source in /examples/js/pagination/custom-pagination-table.js</h5> <CustomPaginationTable /> </div> </div> </div> <div className='col-md-offset-1 col-md-8'> <div className='panel panel-default'> <div className='panel-heading'>Pagination Hooks(onPageChange) Example</div> <div className='panel-body'> <h5>Source in /examples/js/pagination/pagination-hook-table.js</h5> <PaginationHookTable /> </div> </div> </div> </div> ); } } export default Demo;
src/svg-icons/content/remove-circle.js
hai-cea/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ContentRemoveCircle = (props) => ( <SvgIcon {...props}> <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm5 11H7v-2h10v2z"/> </SvgIcon> ); ContentRemoveCircle = pure(ContentRemoveCircle); ContentRemoveCircle.displayName = 'ContentRemoveCircle'; ContentRemoveCircle.muiName = 'SvgIcon'; export default ContentRemoveCircle;
src/components/layout/AppLayout.js
GustavoKatel/franz
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { observer, PropTypes as MobxPropTypes } from 'mobx-react'; import { defineMessages, intlShape } from 'react-intl'; import { TitleBar } from 'electron-react-titlebar'; import InfoBar from '../ui/InfoBar'; import { Component as DelayApp } from '../../features/delayApp'; import { Component as BasicAuth } from '../../features/basicAuth'; import ErrorBoundary from '../util/ErrorBoundary'; // import globalMessages from '../../i18n/globalMessages'; import { isWindows } from '../../environment'; function createMarkup(HTMLString) { return { __html: HTMLString }; } const messages = defineMessages({ servicesUpdated: { id: 'infobar.servicesUpdated', defaultMessage: '!!!Your services have been updated.', }, updateAvailable: { id: 'infobar.updateAvailable', defaultMessage: '!!!A new update for Franz is available.', }, buttonReloadServices: { id: 'infobar.buttonReloadServices', defaultMessage: '!!!Reload services', }, changelog: { id: 'infobar.buttonChangelog', defaultMessage: '!!!Changelog', }, buttonInstallUpdate: { id: 'infobar.buttonInstallUpdate', defaultMessage: '!!!Restart & install update', }, requiredRequestsFailed: { id: 'infobar.requiredRequestsFailed', defaultMessage: '!!!Could not load services and user information', }, }); export default @observer class AppLayout extends Component { static propTypes = { isFullScreen: PropTypes.bool.isRequired, sidebar: PropTypes.element.isRequired, services: PropTypes.element.isRequired, children: PropTypes.element, news: MobxPropTypes.arrayOrObservableArray.isRequired, // isOnline: PropTypes.bool.isRequired, showServicesUpdatedInfoBar: PropTypes.bool.isRequired, appUpdateIsDownloaded: PropTypes.bool.isRequired, removeNewsItem: PropTypes.func.isRequired, reloadServicesAfterUpdate: PropTypes.func.isRequired, installAppUpdate: PropTypes.func.isRequired, showRequiredRequestsError: PropTypes.bool.isRequired, areRequiredRequestsSuccessful: PropTypes.bool.isRequired, retryRequiredRequests: PropTypes.func.isRequired, areRequiredRequestsLoading: PropTypes.bool.isRequired, darkMode: PropTypes.bool.isRequired, isDelayAppScreenVisible: PropTypes.bool.isRequired, }; static defaultProps = { children: [], }; static contextTypes = { intl: intlShape, }; render() { const { isFullScreen, sidebar, services, children, // isOnline, news, showServicesUpdatedInfoBar, appUpdateIsDownloaded, removeNewsItem, reloadServicesAfterUpdate, installAppUpdate, showRequiredRequestsError, areRequiredRequestsSuccessful, retryRequiredRequests, areRequiredRequestsLoading, darkMode, isDelayAppScreenVisible, } = this.props; const { intl } = this.context; return ( <ErrorBoundary> <div className={(darkMode ? 'theme__dark' : '')}> <div className="app"> {isWindows && !isFullScreen && <TitleBar menu={window.franz.menu.template} icon="assets/images/logo.svg" />} <div className="app__content"> {sidebar} <div className="app__service"> {news.length > 0 && news.map(item => ( <InfoBar key={item.id} position="top" type={item.type} sticky={item.sticky} onHide={() => removeNewsItem({ newsId: item.id })} > <span dangerouslySetInnerHTML={createMarkup(item.message)} /> </InfoBar> ))} {/* {!isOnline && ( <InfoBar type="danger" sticky > <span className="mdi mdi-flash" /> {intl.formatMessage(globalMessages.notConnectedToTheInternet)} </InfoBar> )} */} {!areRequiredRequestsSuccessful && showRequiredRequestsError && ( <InfoBar type="danger" ctaLabel="Try again" ctaLoading={areRequiredRequestsLoading} sticky onClick={retryRequiredRequests} > <span className="mdi mdi-flash" /> {intl.formatMessage(messages.requiredRequestsFailed)} </InfoBar> )} {showServicesUpdatedInfoBar && ( <InfoBar type="primary" ctaLabel={intl.formatMessage(messages.buttonReloadServices)} onClick={reloadServicesAfterUpdate} sticky > <span className="mdi mdi-power-plug" /> {intl.formatMessage(messages.servicesUpdated)} </InfoBar> )} {appUpdateIsDownloaded && ( <InfoBar type="primary" ctaLabel={intl.formatMessage(messages.buttonInstallUpdate)} onClick={installAppUpdate} sticky > <span className="mdi mdi-information" /> {intl.formatMessage(messages.updateAvailable)} {' '} <a href="https://meetfranz.com/changelog" target="_blank"> <u>{intl.formatMessage(messages.changelog)}</u> </a> </InfoBar> )} {isDelayAppScreenVisible && (<DelayApp />)} <BasicAuth /> {services} </div> </div> </div> {children} </div> </ErrorBoundary> ); } }
5eShapedCompanion/4.4.1/5eShapedCompanion.js
mcstalker/roll20-api-scripts
var ShapedScripts = /******/ (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'; const Roll20 = __webpack_require__(1); const roll20 = new Roll20(); const parseModule = __webpack_require__(3); const mmFormat = __webpack_require__(4); const myState = roll20.getState('ShapedScripts'); const Logger = __webpack_require__(5); const logger = new Logger('5eShapedCompanion', roll20); const EntityLookup = __webpack_require__(6); const JSONValidator = __webpack_require__(8); const el = new EntityLookup(); const Reporter = __webpack_require__(9); const reporter = new Reporter(roll20, 'Shaped Scripts'); const ShapedScripts = __webpack_require__(10); const srdConverter = __webpack_require__(22); const sanitise = __webpack_require__(23); const mpp = __webpack_require__(24); const shaped = new ShapedScripts(logger, myState, roll20, parseModule.getParser(mmFormat, logger), el, reporter, srdConverter, sanitise, mpp); const _ = __webpack_require__(2); roll20.logWrap = 'roll20'; logger.wrapModule(el); logger.wrapModule(roll20); logger.wrapModule(srdConverter); const jsonValidator = new JSONValidator(__webpack_require__(4)); el.configureEntity('monsters', [ EntityLookup.jsonValidatorAsEntityProcessor(jsonValidator), el.getSpellHydrator(), ], EntityLookup.jsonValidatorAsVersionChecker(jsonValidator)); el.configureEntity('spells', [el.getMonsterSpellUpdater()], EntityLookup.getVersionChecker('0.2.1')); roll20.on('ready', () => { shaped.checkInstall(); shaped.registerEventHandlers(); }); module.exports = { addEntities(entities) { try { if (typeof entities === 'string') { entities = JSON.parse(entities); } // Suppress excessive logging when adding big lists of entities const prevLogLevel = myState.config.logLevel; myState.config.logLevel = Logger.INFO; const result = el.addEntities(entities); myState.config.logLevel = prevLogLevel; const summary = _.mapObject(result, (resultObject, type) => { if (type === 'errors') { return resultObject.length; } return _.mapObject(resultObject, operationResultArray => operationResultArray.length); }); logger.info('Summary of adding entities to the lookup: $$$', summary); logger.info('Details: $$$', result); if (!_.isEmpty(result.errors)) { const message = _.chain(result.errors) .groupBy('entity') .mapObject(entityErrors => _.chain(entityErrors) .pluck('errors') .flatten() .value() ) .map((errors, entityName) => `<li>${entityName}:<ul><li>${errors.join('</li><li>')}</li></ul></li>`) .value(); reporter.reportError(`JSON import error:<ul>${message}</ul>`); } } catch (e) { reporter.reportError('JSON parse error, please see log for more information'); logger.error(e.toString()); logger.error(e.stack); } }, }; /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { /* globals state, createObj, findObjs, getObj, getAttrByName, sendChat, on, log, Campaign, playerIsGM, spawnFx, spawnFxBetweenPoints, filterObjs */ 'use strict'; const _ = __webpack_require__(2); // noinspection JSUnusedLocalSymbols module.exports = class Roll20Wrapper { getState(module) { if (!state[module]) { state[module] = {}; } return state[module]; } createObj(type, attributes) { return createObj(type, attributes); } findObjs(attributes) { return findObjs(attributes); } filterObjs(attributes) { return filterObjs(attributes); } getObj(type, id) { return getObj(type, id); } getOrCreateObj(type, attributes) { const newAttributes = _.extend(_.clone(attributes), { type }); const existing = this.findObjs(newAttributes); switch (existing.length) { case 0: return this.createObj(type, newAttributes); case 1: return existing[0]; default: throw new Error(`Asked for a single ${type} but more than 1 was found matching attributes: ` + `${JSON.stringify(attributes)}`); } } getAttrByName(character, attrName, valueType) { return getAttrByName(character, attrName, valueType); } checkCharacterFlag(character, flag) { const value = this.getAttrByName(character, flag); switch (typeof value) { case 'boolean': return value; case 'number': return !!value; default: return value === '1' || value === 'on'; } } getAttrObjectByName(character, attrName) { const attr = this.findObjs({ type: 'attribute', characterid: character, name: attrName }); return attr && attr.length > 0 ? attr[0] : null; } getOrCreateAttr(characterId, attrName) { return this.getOrCreateObj('attribute', { characterid: characterId, name: attrName }); } setAttrByName(characterId, attrName, value) { this.getOrCreateAttr(characterId, attrName).set('current', value); } processAttrValue(characterId, attrName, cb) { const attribute = this.getOrCreateAttr(characterId, attrName); attribute.set('current', cb(attribute.get('current'))); } getRepeatingSectionAttrs(characterId, sectionName) { const prefix = `repeating_${sectionName}`; return _.filter(this.findObjs({ type: 'attribute', characterid: characterId }), attr => attr.get('name').indexOf(prefix) === 0); } getRepeatingSectionItemIdsByName(characterId, sectionName) { const re = new RegExp(`repeating_${sectionName}_([^_]+)_name$`); return _.reduce(this.getRepeatingSectionAttrs(characterId, sectionName), (lookup, attr) => { const match = attr.get('name').match(re); if (match) { lookup[attr.get('current').toLowerCase()] = match[1]; } return lookup; }, {}); } getCurrentPage(playerId) { let pageId; if (this.playerIsGM(playerId)) { pageId = this.getObj('player', playerId).get('lastpage'); } else { pageId = this.getCampaign().get('playerspecificpages')[playerId] || this.getCampaign().get('playerpageid'); } return pageId ? this.getObj('page', pageId) : null; } spawnFx(pointsArray, fxType, pageId) { switch (pointsArray.length) { case 1: spawnFx(pointsArray[0].x, pointsArray[0].y, fxType, pageId); break; case 2: spawnFxBetweenPoints(pointsArray[0], pointsArray[1], fxType, pageId); break; default: throw new Error('Wrong number of points supplied to spawnFx: $$$', pointsArray); } } playerIsGM(playerId) { return playerIsGM(playerId); } getCampaign() { return Campaign(); // eslint-disable-line } sendChat(sendAs, message, callback, options) { return sendChat(sendAs, message, callback, options); } on(event, callback) { return on(event, callback); } log(msg) { return log(msg); } }; /***/ }, /* 2 */ /***/ function(module, exports) { module.exports = _; /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; const _ = __webpack_require__(2); /** * A specification of a field that can appear * in the format that this parser processes * @typedef {Object} FieldSpec * @property {FieldSpec[]} [contentModel] - list of child fieldSpecs for complex content * @property {boolean} [bare] - if true this field appears as a bare value with no parseToken in front of it * @property {string} [parseToken] - the token that defines the beginning of this field (usually case insensitive). Not * used for bare tokens. * @property {string} [pattern] - a pattern that defines the value of this field. For bare properties this will * determine if the field matches at all, whereas for normal ones this will just be used to validate them * @property {number} [forNextMatchGroup] - the 1-based index of the match group from the supplied pattern that will * contain text that should be handed to the next parser rather than used as part of this field. * @property {number} [forPreviousMatchGroup] - the 1-based index of the match group from the supplied pattern that * will contain text that should be handed to the previous parser to complete its value rather than used as part of * this field. Only applicable to bare properties, since ones with a token have a clearly defined start based on the * parseToken * @property {number} [matchGroup=0] - the index of the capturing group in the supplied pattern to use as the value for * this field. If left at the default of 0, the whole match will be used. * @property {boolean} [caseSensitive=false] - If true, the pattern used for the value of this field will be made case * sensitive. Note that parseToken matching is always case insensitive. * @property {string} type - the type of this field. Currently valid values are [orderedContent, unorderedContent, * string, enumType, integer, abililty] * @property {string[]} enumValues - an array of valid values for this field if the type is enumType * @property {number} [minOccurs=1] - the minimum number of times this field should occur in the parent content model. * @property {number} [maxOccurs=1] - the maximum number of times this field should occur in the parent content model. */ /** * * @param {FieldSpec} formatSpec - Root format specification for this parser * @param logger - Logger object to use for reporting errors etc. * @returns {{parse: ((*))}} - A parser that will process text in the format specified by the supplied formatSpec into * JSON objects */ function getParser(formatSpec, logger) { // noinspection JSUnusedGlobalSymbols const parserModule = { makeContentModelParser(fieldSpec, ordered) { const module = this; return { parse(stateManager, textLines, resume) { const parseState = stateManager.enterChildParser(this, resume); let someMatch = false; let canContinue; let stopParser = null; parseState.subParsers = parseState.subParsers || module.makeParserList(fieldSpec.contentModel); if (parseState.resumeParser) { if (!parseState.resumeParser.resumeParse(stateManager, textLines)) { stateManager.leaveChildParser(this); return false; } someMatch = true; } function parseRunner(parser, index, parsers) { if (!parser.parse(stateManager, textLines)) { if (parser.required === 0 || !ordered) { // No match but it's ok to keep looking // through the rest of the content model for one return false; } // No match but one was required here by the content model } else { parser.justMatched = true; if (parser.required > 0) { parser.required--; } parser.allowed--; if (ordered) { // Set all the previous parsers to be exhausted since we've matched // this one and we're in a strictly ordered content model. _.each(parsers.slice(0, index), _.partial(_.extend, _, { allowed: 0 })); } } return true; } do { stopParser = _.find(parseState.subParsers, parseRunner); logger.debug('Stopped at parser $$$', stopParser); canContinue = stopParser && stopParser.justMatched; if (stopParser) { someMatch = someMatch || stopParser.justMatched; stopParser.justMatched = false; } // Lose any parsers that have used up all their cardinality already parseState.subParsers = _.reject(parseState.subParsers, { allowed: 0 }); } while (!_.isEmpty(parseState.subParsers) && !_.isEmpty(textLines) && canContinue); stateManager.leaveChildParser(this, someMatch ? parseState : undefined); return someMatch; }, resumeParse(stateManager, textLines) { return this.parse(stateManager, textLines, true); }, complete(parseState/* , finalText*/) { const missingContent = _.filter(parseState.subParsers, 'required'); if (!_.isEmpty(missingContent)) { throw new MissingContentError(missingContent); } }, }; }, matchParseToken(myParseState, textLines) { if (_.isEmpty(textLines) || this.bare) { return !_.isEmpty(textLines); } const re = new RegExp(`^(.*?)(${this.parseToken})(?:[\\s.]+|$)`, 'i'); const match = textLines[0].match(re); if (match) { logger.debug('Found match $$$', match[0]); myParseState.forPrevious = match[1]; myParseState.text = ''; textLines[0] = textLines[0].slice(match[0].length).trim(); if (!textLines[0]) { textLines.shift(); } } return !!match; }, matchValue(myParseState, textLines) { if (this.pattern && this.bare) { // If this is not a bare value then we can take all the text up to next // token and just validate it at the end. If it is, then the pattern itself // defines whether this field matches and we must run it immediately. if (_.isEmpty(textLines)) { return false; } textLines[0] = textLines[0].trim(); const matchGroup = this.matchGroup || 0; const re = new RegExp(this.pattern, this.caseSensitive ? '' : 'i'); logger.debug('$$$ attempting to match value [$$$] against regexp $$$', this.name, textLines[0], re.toString()); const match = textLines[0].match(re); if (match) { logger.debug('Successful match! $$$', match); myParseState.text = match[matchGroup]; if (!myParseState.forPrevious && this.forPreviousMatchGroup) { logger.debug('Setting forPrevious to $$$', match[this.forPreviousMatchGroup]); myParseState.forPrevious = match[this.forPreviousMatchGroup]; } textLines[0] = textLines[0].slice(match.index + match[0].length); if (this.forNextMatchGroup && match[this.forNextMatchGroup]) { textLines[0] = match[this.forNextMatchGroup] + textLines[0]; } if (!textLines[0]) { myParseState.text += '\n'; textLines.shift(); } return true; } logger.debug('Match failed'); return false; } logger.debug('$$$ standard string match, not using pattern', this.name); myParseState.text = ''; return true; }, orderedContent(fieldSpec) { return this.makeContentModelParser(fieldSpec, true); }, unorderedContent(fieldSpec) { return this.makeContentModelParser(fieldSpec, false); }, string(/* fieldSpec */) { return this.makeSimpleValueParser(); }, enumType(fieldSpec) { const parser = this.makeSimpleValueParser(); if (fieldSpec.bare) { parser.matchValue = function matchValue(myParseState, textLines) { const firstMatch = _.chain(fieldSpec.enumValues) .map(enumValue => { logger.debug('Attempting to parse as enum property $$$', enumValue); const pattern = `^(.*?)(${enumValue})(?:[\\s.]+|$)`; const re = new RegExp(pattern, this.caseSensitive ? '' : 'i'); return textLines[0].match(re); }) .compact() .sortBy(match => match[1].length) .first() .value(); if (firstMatch) { logger.debug('Finished trying to parse as enum property, match: $$$', firstMatch); myParseState.text = firstMatch[2]; myParseState.forPrevious = firstMatch[1]; textLines[0] = textLines[0].slice(firstMatch.index + firstMatch[0].length); if (!textLines[0]) { textLines.shift(); } return true; } return false; }; } return parser; }, number(fieldSpec) { const parser = this.makeSimpleValueParser(); parser.typeConvert = function typeConvert(textValue) { const parts = textValue.split('/'); let intVal; if (parts.length > 1) { intVal = parts[0] / parts[1]; } else { intVal = parseInt(textValue, 10); } if (_.isNaN(intVal)) { throw new BadValueError(fieldSpec.name, textValue, '[Integer]'); } return intVal; }; return parser; }, ability(/* fieldSpec */) { const parser = this.number(); parser.matchValue = function matchValue(parseState, textLines) { if (_.isEmpty(textLines)) { return false; } textLines[0] = textLines[0].trim(); const re = new RegExp('^([\\sa-z\\(\\)]*)(\\d+(?:\\s?\\([\\-+\\d]+\\))?)', 'i'); logger.debug('Attempting to match value [$$$] against regexp $$$', textLines[0].trim(), re.toString()); let match = textLines[0].match(re); if (match) { logger.debug('Successful match $$$', match); parseState.text = match[2]; textLines[0] = match[1] + textLines[0].slice(match.index + match[0].length); if (!textLines[0]) { textLines.shift(); } return true; } else if (textLines[1]) { // Try and match against the next line in case we have a two line format textLines[1] = textLines[1].trim(); match = textLines[1].match(/^(\d+)(?:\s?\([\-+\d]+\))?/); if (match) { logger.debug('Successful ability match $$$ on next line - looks like two line format', match); parseState.text = match[1]; textLines[1] = textLines[1].slice(match[0].length); if (!textLines[0]) { textLines.shift(); } if (!textLines[0]) { textLines.shift(); } return true; } } return false; }; return parser; }, heading(fieldSpec) { fieldSpec.bare = true; const parser = this.makeSimpleValueParser(); parser.skipOutput = true; return parser; }, makeSimpleValueParser() { const module = this; return { parse(stateManager, textLines) { const parseState = stateManager.enterChildParser(this); const match = this.matchParseToken(parseState, textLines) && this.matchValue(parseState, textLines); if (match) { stateManager.completeCurrentStack(parseState.forPrevious); delete parseState.forPrevious; stateManager.leaveChildParser(this, parseState); } else { stateManager.leaveChildParser(this); } return match; }, complete(parseState, finalText) { parseState.text += finalText || ''; if (parseState.text) { parseState.value = this.extractValue(parseState.text); parseState.value = this.typeConvert(parseState.value); parseState.setOutputValue(); } }, extractValue(text) { text = text.trim(); if (this.pattern && !this.bare) { const regExp = new RegExp(this.pattern, this.caseSensitive ? '' : 'i'); const match = text.match(regExp); if (match) { const matchGroup = this.matchGroup || 0; return match[matchGroup]; } throw new BadValueError(this.name, text, regExp); } else { return text; } }, typeConvert(textValue) { return textValue; }, resumeParse(stateManager, textLines) { if (_.isEmpty(textLines)) { return false; } const parseState = stateManager.enterChildParser(this, true); parseState.text += `${textLines.shift()}\n`; stateManager.leaveChildParser(this, parseState); return true; }, matchParseToken: module.matchParseToken, matchValue: module.matchValue, }; }, makeBaseParseState(skipOutput, propertyPath, outputObject, completedObjects) { return { text: '', getObjectValue() { let value = outputObject; const segments = _.clone(propertyPath); while (segments.length) { const prop = segments.shift(); if (prop.flatten) { continue; } value = value[prop.name]; if (_.isArray(value)) { value = _.last(value); } } return value; }, setOutputValue() { if (skipOutput) { return; } let outputTo = outputObject; const segments = _.clone(propertyPath); while (segments.length > 0) { const prop = segments.shift(); if (prop.flatten) { continue; } let currentValue = outputTo[prop.name]; let newValue = segments.length === 0 ? this.value : {}; if (_.isUndefined(currentValue) && prop.allowed > 1) { currentValue = []; outputTo[prop.name] = currentValue; } if (_.isArray(currentValue)) { let arrayItem = _.find(currentValue, _.partial(_.negate(_.contains), completedObjects)); if (!arrayItem) { currentValue.push(newValue); arrayItem = _.last(currentValue); } newValue = arrayItem; } else if (_.isUndefined(currentValue)) { outputTo[prop.name] = newValue; } else if (segments.length === 0) { throw new Error('Simple value property somehow already had value when we came to set it'); } else { newValue = currentValue; } outputTo = newValue; } }, logWrap: `parseState[${_.pluck(propertyPath, 'name').join('/')}]`, toJSON() { return _.extend(_.clone(this), { propertyPath }); }, }; }, makeParseStateManager() { const incompleteParserStack = []; const currentPropertyPath = []; const completedObjects = []; const module = this; return { outputObject: {}, leaveChildParser(parser, state) { currentPropertyPath.pop(); if (state) { state.resumeParser = _.isEmpty(incompleteParserStack) ? null : _.last(incompleteParserStack).parser; incompleteParserStack.push({ parser, state }); } }, completeCurrentStack(finalText) { while (!_.isEmpty(incompleteParserStack)) { const incomplete = incompleteParserStack.shift(); incomplete.parser.complete(incomplete.state, finalText); const value = incomplete.state.getObjectValue(); if (_.isObject(value) && !incomplete.parser.flatten) { // Crude but this list is unlikely to get that big completedObjects.push(value); } } }, enterChildParser(parser, resume) { currentPropertyPath.push({ name: parser.name, allowed: parser.allowed, flatten: parser.flatten, }); if (!resume || _.isEmpty(incompleteParserStack) || parser !== _.last(incompleteParserStack).parser) { return module.makeBaseParseState(parser.skipOutput, _.clone(currentPropertyPath), this.outputObject, completedObjects); } return incompleteParserStack.pop().state; }, logWrap: 'parserState', toJSON() { return _.extend(_.clone(this), { incompleteParsers: incompleteParserStack, propertyPath: currentPropertyPath, }); }, }; }, parserId: 0, parserAttributes: [ 'forPreviousMatchGroup', 'forNextMatchGroup', 'parseToken', 'flatten', 'pattern', 'matchGroup', 'bare', 'caseSensitive', 'name', 'skipOutput', ], getParserFor(fieldSpec) { logger.debug('Making parser for field $$$', fieldSpec); const parserBuilder = this[fieldSpec.type]; if (!parserBuilder) { throw new Error(`Can\'t make parser for type ${fieldSpec.type}`); } const parser = parserBuilder.call(this, fieldSpec); parser.required = _.isUndefined(fieldSpec.minOccurs) ? 1 : fieldSpec.minOccurs; parser.allowed = _.isUndefined(fieldSpec.maxOccurs) ? 1 : fieldSpec.maxOccurs; _.extend(parser, _.pick(fieldSpec, this.parserAttributes)); _.defaults(parser, { parseToken: parser.name, }); parser.id = this.parserId++; parser.logWrap = `parser[${parser.name}]`; return parser; }, makeParserList(contentModelArray) { const module = this; return _.chain(contentModelArray) .reject('noParse') .reduce((parsers, fieldSpec) => { parsers.push(module.getParserFor(fieldSpec)); return parsers; }, []) .value(); }, logWrap: 'parseModule', }; logger.wrapModule(parserModule); const parser = parserModule.getParserFor(formatSpec); return { parse(text) { logger.debug('Text: $$$', text); const textLines = _.chain(text.split('\n')) .invoke('trim') .compact() .value(); logger.debug(parser); const stateManager = parserModule.makeParseStateManager(); const success = parser.parse(stateManager, textLines); while (success && !_.isEmpty(textLines)) { parser.resumeParse(stateManager, textLines); } stateManager.completeCurrentStack(textLines.join('\n')); if (success && textLines.length === 0) { stateManager.outputObject.version = formatSpec.formatVersion; logger.info(stateManager.outputObject); return stateManager.outputObject; } return null; }, }; } /** * @constructor */ function ParserError(message) { // noinspection JSUnusedGlobalSymbols this.message = message; } ParserError.prototype = new Error(); /** * @constructor */ function MissingContentError(missingFieldParsers) { this.missingFieldParsers = missingFieldParsers; this.message = '<ul>'; this.message += _.reduce(this.missingFieldParsers, (memo, parser) => `${memo}<li>Field ${parser.parseToken} should have appeared ${parser.required} more times</li>` , ''); this.message += '</ul>'; } MissingContentError.prototype = new ParserError(); /** * @constructor */ function BadValueError(name, value, pattern) { 'use strict'; this.name = name; this.value = value; this.pattern = pattern; // noinspection JSUnusedGlobalSymbols this.message = `Bad value [${this.value}] for field [${this.name}]. Should have matched pattern: ${this.pattern}`; } BadValueError.prototype = new ParserError(); module.exports = { getParser, MissingContentError, BadValueError, ParserError, }; /***/ }, /* 4 */ /***/ function(module, exports) { module.exports = { "formatVersion": "0.2", "name": "monsters", "maxOccurs": "Infinity", "type": "orderedContent", "bare": true, "contentModel": [ { "name": "coreInfo", "type": "orderedContent", "flatten": true, "contentModel": [ { "name": "name", "type": "string", "bare": "true" }, { "name": "size", "enumValues": [ "Tiny", "Small", "Medium", "Large", "Huge", "Gargantuan" ], "type": "enumType", "bare": "true" }, { "name": "type", "type": "string", "bare": "true", "pattern": "^([\\w\\s\\(\\),-]+),", "matchGroup": 1 }, { "name": "alignment", "type": "enumType", "enumValues": [ "lawful good", "lawful neutral", "lawful evil", "neutral good", "neutral evil", "neutral", "chaotic good", "chaotic neutral", "chaotic evil", "unaligned", "any alignment", "any good alignment", "any non-good alignment", "any evil alignment", "any non-evil alignment", "any lawful alignment", "any non-lawful alignment", "any chaotic alignment", "any non-chaotic alignment", "construct", "(?:lawful|neutral|chaotic) (?:good|neutral|evil) \\(\\d+%\\) or (?:lawful|neutral|chaotic) (?:good|neutral|evil) \\(\\d+%\\)" ], "bare": true } ] }, { "name": "attributes", "type": "unorderedContent", "flatten": true, "contentModel": [ { "name": "AC", "parseToken": "armor class", "pattern": "\\d+\\s*(?:\\([^)]*\\))?", "type": "string" }, { "name": "HP", "parseToken": "hit points", "type": "string", "pattern": "\\d+(?:\\s?\\(\\s?\\d+d\\d+(?:\\s?[-+]\\s?\\d+)?\\s?\\))?" }, { "name": "speed", "minOccurs": 0, "type": "string", "pattern": "^\\d+\\s?ft[\\.]?(,\\s?(fly|swim|burrow|climb)\\s\\d+\\s?ft[\\.]?)*(\\s?\\([^\\)]+\\))?$" }, { "name": "strength", "parseToken": "str", "type": "ability" }, { "name": "dexterity", "parseToken": "dex", "type": "ability" }, { "name": "constitution", "parseToken": "con", "type": "ability" }, { "name": "intelligence", "parseToken": "int", "type": "ability" }, { "name": "wisdom", "parseToken": "wis", "type": "ability" }, { "name": "charisma", "parseToken": "cha", "type": "ability" }, { "name": "savingThrows", "minOccurs": 0, "parseToken": "saving throws", "type": "string", "pattern": "(?:(?:^|,\\s*)(?:Str|Dex|Con|Int|Wis|Cha)\\s+[\\-\\+]\\d+)+" }, { "name": "skills", "minOccurs": 0, "type": "string", "pattern": "(?:(?:^|,\\s*)(?:Acrobatics|Animal Handling|Arcana|Athletics|Deception|History|Insight|Intimidation|Investigation|Medicine|Nature|Perception|Performance|Persuasion|Religion|Sleight of Hand|Stealth|Survival|Influence|Society)\\s+[\\-\\+]\\d+)+" }, { "minOccurs": 0, "type": "string", "name": "damageVulnerabilities", "parseToken": "damage vulnerabilities" }, { "minOccurs": 0, "type": "string", "name": "damageResistances", "parseToken": "damage resistances" }, { "minOccurs": 0, "type": "string", "name": "damageImmunities", "parseToken": "damage immunities" }, { "minOccurs": 0, "type": "string", "name": "conditionImmunities", "parseToken": "condition immunities" }, { "name": "senses", "type": "string", "minOccurs": 0, "pattern": "(?:(?:^|,\\s*)(?:blindsight|darkvision|tremorsense|truesight)\\s+\\d+\\s*ft\\.?(?: or \\d+ ft\\. while deafened)?(?:\\s?\\([^\\)]+\\))?)+" }, { "name": "passivePerception", "parseToken": ",?\\s*passive Perception", "minOccurs": 0, "type": "number", "skipOutput": true }, { "name": "spells", "minOccurs": 0, "type": "string" }, { "name": "languages", "minOccurs": 0, "type": "string" } ] }, { "name": "challenge", "type": "string", "pattern": "^\\s*(\\d+(?:\\s*\\/\\s*\\d)?)\\s*(?:\\(\\s*[\\d,]+\\s*XP\\s*\\)\\s*)?$", "matchGroup": 1 }, { "name": "traitSection", "type": "orderedContent", "minOccurs": 0, "maxOccurs": 1, "flatten": true, "contentModel": [ { "name": "traits", "type": "orderedContent", "minOccurs": 1, "maxOccurs": "Infinity", "contentModel": [ { "name": "name", "type": "string", "pattern": "(^|.*?[a-z]\\.\\s?)((?:[A-Z][\\w\\-']+[,:!]?|A)(?:\\s(?:[A-Z][\\w\\-']+[,:!]?|of|to|in|the|with|and|or|a)+)*)(\\s?\\([^\\)]+\\))?\\.(?!$)", "matchGroup": 2, "forPreviousMatchGroup": 1, "forNextMatchGroup": 3, "bare": true, "caseSensitive": true }, { "name": "recharge", "type": "string", "pattern": "^\\(([^\\)]+)\\)", "bare": true, "matchGroup": 1, "minOccurs": 0 }, { "name": "text", "bare": true, "type": "string" } ] } ] }, { "name": "actionSection", "type": "orderedContent", "minOccurs": 0, "maxOccurs": 1, "flatten": true, "contentModel": [ { "name": "actionHeader", "type": "heading", "bare": true, "pattern": "^Actions$" }, { "name": "actions", "type": "orderedContent", "minOccurs": 1, "maxOccurs": "Infinity", "contentModel": [ { "name": "name", "type": "string", "pattern": "(^|.*?[a-z]\\.\\s?)((?:\\d+\\.\\s?)?(?:[A-Z][\\w\\-']+[,:!]?|A)(?:\\s(?:[A-Z][\\w\\-']+[,:!]?|of|in|to|with|the|and|or|a|\\+\\d+)+)*)(\\s?\\([^\\)]+\\))?\\.(?!$)", "matchGroup": 2, "forPreviousMatchGroup": 1, "forNextMatchGroup": 3, "bare": true, "caseSensitive": true }, { "name": "recharge", "type": "string", "bare": true, "pattern": "^\\(([^\\)]+)\\)", "matchGroup": 1, "minOccurs": 0 }, { "name": "text", "bare": true, "type": "string" } ] } ] }, { "name": "reactionSection", "type": "orderedContent", "minOccurs": 0, "maxOccurs": 1, "flatten": true, "contentModel": [ { "name": "reactionHeader", "type": "heading", "bare": true, "pattern": "^Reactions$" }, { "name": "reactions", "type": "orderedContent", "minOccurs": 1, "maxOccurs": "Infinity", "contentModel": [ { "name": "name", "type": "string", "pattern": "(^|.*?[a-z]\\.\\s?)((?:[A-Z][\\w\\-']+[,:!]?|A)(?:\\s(?:[A-Z][\\w\\-']+[,:!]?|of|in|to|with|the|and|or|a)+)*)(\\s?\\([^\\)]+\\))?\\.(?!$)", "matchGroup": 2, "forPreviousMatchGroup": 1, "forNextMatchGroup": 3, "bare": true, "caseSensitive": true }, { "name": "recharge", "type": "string", "bare": true, "pattern": "^\\(([^\\)]+)\\)", "matchGroup": 1, "minOccurs": 0 }, { "name": "text", "bare": true, "type": "string" } ] } ] }, { "name": "legendaryActionSection", "type": "orderedContent", "minOccurs": 0, "maxOccurs": 1, "flatten": true, "contentModel": [ { "name": "actionHeader", "type": "heading", "bare": true, "pattern": "^Legendary Actions$" }, { "name": "legendaryPoints", "type": "number", "bare": true, "pattern": "^The[ \\w]+can take (\\d+) legendary actions.*?start of its turn[.]?", "matchGroup": 1 }, { "name": "legendaryActions", "type": "orderedContent", "minOccurs": 1, "maxOccurs": "Infinity", "contentModel": [ { "name": "name", "type": "string", "bare": true, "pattern": "(^|.*?[a-z]\\.\\s?)((?:[A-Z][\\w\\-']+[,:!]?|A)(?:\\s(?:[A-Z][\\w\\-']+[,:!]?|of|with|to|the|and|or|a)+)*)(\\s?\\([^\\)]+\\))?\\.(?!$)", "matchGroup": 2, "forPreviousMatchGroup": 1, "forNextMatchGroup": 3, "caseSensitive": true }, { "name": "cost", "type": "number", "bare": true, "pattern": "^\\s*\\(\\s*costs (\\d+) actions\\s*\\)", "matchGroup": 1, "minOccurs": 0 }, { "name": "text", "bare": true, "type": "string" } ] } ] }, { "name": "lairActionSection", "type": "orderedContent", "minOccurs": 0, "maxOccurs": 1, "flatten": true, "contentModel": [ { "name": "actionHeader", "type": "heading", "bare": true, "pattern": "^Lair Actions$" }, { "name": "lairActions", "type": "string", "bare": true, "minOccurs": 1, "maxOccurs": "Infinity" } ] }, { "name": "regionalEffectsSection", "type": "orderedContent", "minOccurs": 0, "maxOccurs": 1, "flatten": true, "contentModel": [ { "name": "actionHeader", "type": "heading", "bare": true, "pattern": "^Regional Effects$" }, { "name": "regionalEffects", "type": "string", "minOccurs": 1, "maxOccurs": "Infinity", "bare": true }, { "name": "regionalEffectsFade", "type": "string", "bare": true } ] } ] }; /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; const _ = __webpack_require__(2); function stringify(object) { if (object === undefined) { return object; } return typeof object === 'string' ? object : JSON.stringify(object, (key, value) => (key !== 'logWrap' && key !== 'isLogWrapped' ? value : undefined) ); } function wrapFunctions(object, moduleName, makeWrapper) { const funcs = getAllFuncs(object); return _.each(funcs, funcName => (object[funcName] = makeWrapper(funcName, object[funcName], moduleName))); } function getAllFuncs(obj) { let props = []; let current = obj; do { props = props.concat(Object.getOwnPropertyNames(current)); } while ((current = Object.getPrototypeOf(current)) && current !== Object.prototype); return props.sort().filter((e, i, arr) => (e !== arr[i + 1] && typeof obj[e] === 'function')); } module.exports = class Logger { constructor(loggerName, roll20) { this.prefixString = ''; const state = roll20.getState('roll20-logger'); state[loggerName] = state[loggerName] || Logger.levels.INFO; roll20.on('chat:message', (msg) => { if (msg.type === 'api' && msg.content.startsWith('!logLevel')) { const parts = msg.content.split(/\s/); if (parts.length > 2) { if (!state[parts[1]]) { roll20.sendChat('Logger', `Unrecognised logger name ${parts[1]}`); return; } state[parts[1]] = Logger.levels[parts[2].toUpperCase()] || Logger.levels.INFO; } } }); function shouldLog(level) { return level <= state[loggerName]; } function outputLog(level, message) { if (!shouldLog(level)) { return; } const args = arguments.length > 2 ? _.toArray(arguments).slice(2) : []; let processedMessage = stringify(message); if (processedMessage) { processedMessage = processedMessage.replace(/\$\$\$/g, () => stringify(args.shift())); } // noinspection NodeModulesDependencies roll20.log(`${loggerName} ${Date.now()} ` + `${Logger.getLabel(level)} : ${shouldLog(Logger.levels.TRACE) ? this.prefixString : ''}` + `${processedMessage}`); } _.each(Logger.levels, (level, levelName) => { this[levelName.toLowerCase()] = _.partial(outputLog, level); }); this.wrapModule = function wrapModule(modToWrap) { if (shouldLog(Logger.levels.TRACE)) { wrapFunctions(modToWrap, modToWrap.logWrap, this.wrapFunction.bind(this)); modToWrap.isLogWrapped = true; } return modToWrap; }; this.getLogTap = function getLogTap(level, messageString) { return _.partial(outputLog, level, messageString); }; this.wrapFunction = function wrapFunction(name, func, moduleName) { if (shouldLog(Logger.levels.TRACE)) { if (name === 'toJSON' || moduleName === 'roll20' && name === 'log') { return func; } const logger = this; return function functionWrapper() { logger.trace('$$$.$$$ starting with this value: $$$ and args $$$', moduleName, name, this, arguments); logger.prefixString = `${logger.prefixString} `; const retVal = func.apply(this, arguments); logger.prefixString = logger.prefixString.slice(0, -2); logger.trace('$$$.$$$ ending with return value $$$', moduleName, name, retVal); if (retVal && retVal.logWrap && !retVal.isLogWrapped) { logger.wrapModule(retVal); } return retVal; }; } return func; }; } static getLabel(logLevel) { const logPair = _.chain(Logger.levels).pairs().find(pair => pair[1] === logLevel).value(); return logPair ? logPair[0] : 'UNKNOWN'; } static get levels() { return { OFF: 0, ERROR: 1, WARN: 2, INFO: 3, DEBUG: 4, TRACE: 5, }; } }; /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; const _ = __webpack_require__(2); const utils = __webpack_require__(7); module.exports = class EntityLookup { constructor() { this.entities = {}; this.noWhiteSpaceEntities = {}; this.entityProcessors = {}; this.versionCheckers = {}; } configureEntity(entityName, processors, versionChecker) { this.entities[entityName] = {}; this.noWhiteSpaceEntities[entityName] = {}; this.entityProcessors[entityName] = processors || []; this.versionCheckers[entityName] = versionChecker || _.constant(true); } addEntities(entitiesObject) { const results = { errors: [], }; _.chain(entitiesObject) .omit('version', 'patch') .each((entityArray, type) => { results[type] = { withErrors: [], skipped: [], deleted: [], patched: [], added: [], }; if (!this.entities[type]) { results.errors.push({ entity: 'general', errors: [`Unrecognised entity type ${type}`] }); return; } if (!this.versionCheckers[type](entitiesObject.version, results.errors)) { return; } _.each(entityArray, (entity) => { let key = entity.name.toLowerCase(); let operation = !!this.entities[type][key] ? (entitiesObject.patch ? 'patched' : 'skipped') : 'added'; if (operation === 'patched') { entity = patchEntity(this.entities[type][key], entity); if (!entity) { operation = 'deleted'; delete this.entities[type][key]; delete this.noWhiteSpaceEntities[type][key.replace(/\s+/g, '')]; } } if (_.contains(['patched', 'added'], operation)) { const processed = _.reduce(this.entityProcessors[type], utils.executor, { entity, type, version: entitiesObject.version, errors: [], }); if (!_.isEmpty(processed.errors)) { processed.entity = processed.entity.name; results.errors.push(processed); operation = 'withErrors'; } else { if (processed.entity.name.toLowerCase() !== key) { results[type].deleted.push(key); delete this.entities[type][key]; delete this.noWhiteSpaceEntities[type][key.replace(/\s+/g, '')]; key = processed.entity.name.toLowerCase(); } this.entities[type][key] = processed.entity; this.noWhiteSpaceEntities[type][key.replace(/\s+/g, '')] = processed.entity; } } results[type][operation].push(key); }); }); return results; } findEntity(type, name, tryWithoutWhitespace) { const key = name.toLowerCase(); if (!this.entities[type]) { throw new Error(`Unrecognised entity type ${type}`); } let found = this.entities[type][key]; if (!found && tryWithoutWhitespace) { found = this.noWhiteSpaceEntities[type][key.replace(/\s+/g, '')]; } return found && utils.deepClone(found); } searchEntities(type, criteria) { function containsSomeIgnoreCase(array, testValues) { testValues = (_.isArray(testValues) ? testValues : [testValues]).map(s => s.toLowerCase()); return !!_.chain(array) .map(s => s.toLowerCase()) .intersection(testValues) .value().length; } return _.reduce(criteria, (results, criterionValue, criterionField) => { const re = new RegExp(criterionValue, 'i'); const matcher = (entity) => { const value = entity[criterionField]; switch (typeof value) { case 'string': return value.match(re); case 'boolean': case 'number': return value === criterionValue; case 'object': return _.isArray(value) && containsSomeIgnoreCase(value, criterionValue); default: return false; } }; return results.filter(matcher); }, this.getAll(type)); } getAll(type) { if (!this.entities[type]) { throw new Error(`Unrecognised entity type: ${type}`); } return utils.deepClone(_.values(this.entities[type])); } /** * Gets all of the keys for the specified entity type * @param {string} type - The entity type to retrieve keys for (either 'monster' or 'spell') * @param {boolean} sort - True if the returned array should be sorted alphabetically; false otherwise * @function * @public * @name EntityLookup#getKeys * @return {Array} An array containing all keys for the specified entity type */ getKeys(type, sort) { if (!this.entities[type]) { throw new Error(`Unrecognised entity type: ${type}`); } const keys = _.keys(this.entities[type]); if (sort) { keys.sort(); } return keys; } /** * Gets spell hydrator * @function * @public * @name EntityLookup#getSpellHydrator * @return {function} */ getSpellHydrator() { const self = this; return function spellHydrator(monsterInfo) { const monster = monsterInfo.entity; if (monster.spells) { const spellArray = monster.spells.split(', '); monster.spells = _.map(spellArray, spellName => self.findEntity('spells', spellName) || spellName); } return monsterInfo; }; } getMonsterSpellUpdater() { const self = this; return function spellUpdater(spellInfo) { const spell = spellInfo.entity; _.chain(self.entities.monsters) .pluck('spells') .compact() .each(spellArray => { const spellIndex = _.findIndex(spellArray, monsterSpell => { if (typeof monsterSpell === 'string') { return monsterSpell.toLowerCase() === spell.name.toLowerCase(); } return monsterSpell !== spell && monsterSpell.name.toLowerCase() === spell.name.toLowerCase(); }); if (spellIndex !== -1) { spellArray[spellIndex] = spell; } }); return spellInfo; }; } toJSON() { return { monsterCount: _.size(this.entities.monsters), spellCount: _.size(this.entities.spells) }; } get logWrap() { return 'entityLookup'; } static jsonValidatorAsEntityProcessor(jsonValidator) { return function jsonValidatorEntityProcessor(entityInfo) { const wrapper = { version: entityInfo.version, }; wrapper[entityInfo.type] = [entityInfo.entity]; const errors = jsonValidator.validate(wrapper); const flattenedErrors = _.chain(errors).values().flatten().value(); entityInfo.errors = entityInfo.errors.concat(flattenedErrors); return entityInfo; }; } static jsonValidatorAsVersionChecker(jsonValidator) { return EntityLookup.getVersionChecker(jsonValidator.getVersionNumber()); } static getVersionChecker(requiredVersion) { function pruneToMinor(versionString) { return versionString.split('.', 2).join('.'); } return function versionChecker(version, errorsArray) { const prunedVersion = pruneToMinor(version); const prunedRequiredVersion = pruneToMinor(requiredVersion); const valid = prunedVersion === prunedRequiredVersion; if (!valid) { errorsArray.push({ entity: 'general', errors: [`Incorrect entity objects version: [${version}]. Required is: ${requiredVersion}`], }); } return valid; }; } }; function patchEntity(original, patch) { if (patch.remove) { return undefined; } return _.mapObject(original, (propVal, propName) => { if (propName === 'name' && patch.newName) { return patch.newName; } return patch[propName] || propVal; }); } /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; const _ = __webpack_require__(2); // noinspection JSUnusedGlobalSymbols module.exports = { deepExtend(original, newValues) { if (!original) { original = _.isArray(newValues) ? [] : {}; } _.each(newValues, (value, key) => { if (_.isArray(original[key])) { if (!_.isArray(value)) { original[key].push(value); } else { original[key] = _.map(value, (item, index) => { if (_.isObject(item)) { return this.deepExtend(original[key][index], item); } return item !== undefined ? item : original[key][index]; }); } } else if (_.isObject(original[key])) { original[key] = this.deepExtend(original[key], value); } else { original[key] = value; } }); return original; }, createObjectFromPath(pathString, value) { const newObject = {}; _.reduce(pathString.split(/\./), (object, pathPart, index, pathParts) => { const match = pathPart.match(/([^.\[]*)(?:\[(\d+)\])?/); const newVal = index === pathParts.length - 1 ? value : {}; if (match[2]) { object[match[1]] = []; object[match[1]][match[2]] = newVal; } else { object[match[1]] = newVal; } return newVal; }, newObject); return newObject; }, getObjectFromPath(obj, path) { path = path.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties path = path.replace(/^\./, ''); // strip a leading dot path.split('.').every(segment => (obj = obj[segment])); return obj; }, deepClone(object) { return JSON.parse(JSON.stringify(object)); }, executor() { switch (arguments.length) { case 0: return undefined; case 1: return arguments[0](); default: // Fall through } const args = Array.apply(null, arguments).slice(2); args.unshift(arguments[0]); return arguments[1].apply(null, args); }, /** * Gets a string as 'Title Case' capitalizing the first letter of each word (i.e. 'the grapes of wrath' -> 'The * Grapes Of Wrath') * @param {string} s - The string to be converted * @return {string} the supplied string in title case */ toTitleCase(s) { return s.replace(/\w\S*/g, txt => txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase()); }, toOptionsString(options) { let res = options.join(' --'); if (res.length > 0) { res = `--${res}`; } return res; }, /** * Calculates a contrasting color using YIQ luma value * @param {string} hexcolor - the color to calculate a contrasting color for * @return {string} either 'white' or 'black' as determined to be the best contrasting text color for the input color */ getContrastYIQ(hexcolor) { hexcolor = hexcolor.replace('#', ''); if (hexcolor.length === 3) { hexcolor += hexcolor; } const r = parseInt(hexcolor.substr(0, 2), 16); const g = parseInt(hexcolor.substr(2, 2), 16); const b = parseInt(hexcolor.substr(4, 2), 16); const yiq = (r * 299 + g * 587 + b * 114) / 1000; return yiq >= 128 ? 'black' : 'white'; }, /** * Builds an html element as a string using the specified options * @param {string} tag - the html tag type * @param innerHtml - can be a string to be used as the element inner html, or a {tag, innerHtml, attrs} object * in order to build a child html element string * @param attrs - a collection of attributes and their values to be applied to the html element * @return {string} the full html element as a string */ buildHTML(tag, innerHtml, attrs) { if (typeof innerHtml === 'object') { innerHtml = _.map(innerHtml, html => html && this.buildHTML(html.tag, html.innerHtml, html.attrs)).join(''); } let h = `<${tag}`; h += _.chain(attrs) .map((attrVal, attrName) => attrVal !== false && ` ${attrName}="${attrVal}"`) .compact() .value() .join(''); if (innerHtml) { h += `>${innerHtml}</${tag}>`; } else { h += '/>'; } return h; }, missingParam(name) { throw new Error(`Parameter ${name} is required`); }, flattenObject(object) { return _.reduce(object, (explodedProps, propVal, propKey) => { if (_.isObject(propVal)) { return _.extend(explodedProps, this.flattenObject(propVal)); } explodedProps[propKey] = propVal; return explodedProps; }, {}); }, }; /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; const _ = __webpack_require__(2); // noinspection JSUnusedGlobalSymbols const validatorFactories = { orderedContent(spec) { return makeContentModelValidator(spec); }, unorderedContent(spec) { return makeContentModelValidator(spec); }, string(spec) { if (spec.pattern) { if (spec.matchGroup) { return regExValidator(spec.name, extractRegexPart(spec.pattern, spec.matchGroup), spec.caseSensitive); } return regExValidator(spec.name, spec.pattern, spec.caseSensitive); } return function noop() { }; }, enumType(spec) { return function enumValidator(value, errors) { if (!_.some(spec.enumValues, enumVal => new RegExp(`^${enumVal}$`, 'i').test(value))) { errors.add(`Value "${value}" should have been one of [${spec.enumValues.join(',')}]`); } }; }, ability(spec) { return regExValidator(spec.name, '\\d+'); }, heading() { // Do not replace with _.noop, these functions get annotated return function noop() { }; }, number() { return function numberValidator(value, errors) { if (typeof value !== 'number') { errors.add(`Value "${value}" should have been a number`); } }; }, }; function extractRegexPart(regexp, matchIndex) { let braceCount = 0; let startIndex = _.findIndex(regexp, (character, index) => { if (character === '(' && (index < 2 || regexp[index - 1] !== '\\') && regexp[index + 1] !== '?') { return ++braceCount === matchIndex; } return false; }); if (startIndex === -1) { throw new Error(`Can\'t find matchgroup ${matchIndex} in regular expression ${regexp}`); } // Lose the bracket startIndex++; let openCount = 1; const endIndex = _.findIndex(regexp.slice(startIndex), (character, index, regexpPart) => { if (character === '(' && regexpPart[index - 1] !== '\\') { openCount++; } if (character === ')' && regexpPart[index - 1] !== '\\') { return --openCount === 0; } return false; }); if (endIndex === -1) { throw new Error(`matchgroup ${matchIndex} seems not to have closing brace in regular expression ${regexp}`); } return regexp.slice(startIndex, startIndex + endIndex); } function regExValidator(fieldName, regexp, caseSensitive) { const re = new RegExp(`^${regexp}$`, caseSensitive ? undefined : 'i'); return function regexpValidate(value, errors) { if (!re.test(value)) { errors.add(`Value "${value}" doesn\'t match pattern /${regexp}/`); } }; } function makeValidator(spec) { const validator = validatorFactories[spec.type](spec); validator.max = _.isUndefined(spec.maxOccurs) ? 1 : spec.maxOccurs; validator.min = _.isUndefined(spec.minOccurs) ? 1 : spec.minOccurs; validator.fieldName = spec.name; return validator; } function makeContentModelValidator(spec) { const parts = _.chain(spec.contentModel) .reject({ type: 'heading' }) .partition({ flatten: true }) .value(); const flattened = _.map(parts[0], makeValidator); const subValidators = _.reduce(parts[1], (subVals, field) => { subVals[field.name] = makeValidator(field); return subVals; }, {}); return function contentModelValidator(object, errors, isFlatten) { let completed = _.reduce(object, (completedMemo, fieldValue, fieldName) => { const validator = subValidators[fieldName]; if (validator) { completedMemo.push(fieldName); errors.pushPath(fieldName); if (_.isArray(fieldValue)) { if (fieldValue.length > validator.max) { errors.add(`Number of entries [${fieldValue.length}] exceeds maximum allowed: ${validator.max}`); } else if (fieldValue.length < validator.min) { errors.add(`Number of entries [${fieldValue.length}] is less than minimum allowed: ${validator.min}`); } else { _.each(fieldValue, (arrayItem, index) => { errors.pushIndex(arrayItem.name ? arrayItem.name : index); validator(arrayItem, errors); errors.popIndex(); }); } } else { validator(fieldValue, errors); } errors.popPath(); } return completedMemo; }, []); let toValidate = _.omit(object, completed); _.chain(flattened) .map(validator => { const subCompleted = validator(toValidate, errors, true); if (subCompleted.length === 0) { return validator; } completed = completed.concat(subCompleted); toValidate = _.omit(toValidate, completed); return null; }) .compact() .each(validator => { if (validator.min > 0) { errors.pushPath(validator.fieldName); errors.add('Section is missing'); errors.popPath(); } }); // If we're a flattened validator (our content is injected directly into the parent content model) // Then we should only report missing fields if there was some match in our content model - otherwise // the parent content model will check the cardinality of this model as a whole if (!isFlatten || !_.isEmpty(completed)) { _.chain(subValidators) .omit(completed) .each(validator => { if (validator.min > 0) { errors.pushPath(validator.fieldName); errors.add('Field is missing'); errors.popPath(); } }); } // Flattened content models shouldn't check for unrecognised fields since they're only parsing // part of the current content model. if (!isFlatten) { _.chain(object) .omit(completed) .each((value, key) => { errors.pushPath(key); errors.add('Unrecognised field'); errors.popPath(); }); } return completed; }; } class Errors { constructor() { this.errors = []; this.currentPath = []; } pushPath(path) { this.currentPath.push(path); } popPath() { return this.currentPath.pop(); } pushIndex(index) { this.currentPath[this.currentPath.length - 1] = `${this.currentPath[this.currentPath.length - 1]}[${index}]`; } popIndex() { this.currentPath[this.currentPath.length - 1] = this.currentPath[this.currentPath.length - 1].replace(/\[[^\]]+\]/, ''); } add(msg) { this.errors.push({ msg, path: _.clone(this.currentPath) }); } getErrors() { return _.chain(this.errors) .groupBy(error => error.path[0]) .mapObject(errorList => _.map(errorList, error => `${error.path.slice(1).join('.')}: ${error.msg}`) ) .value(); } } module.exports = class JSONValidator { constructor(spec) { this.versionProp = { type: 'string', name: 'version', }; this.spec = spec; this.contentValidator = makeValidator({ type: 'unorderedContent', contentModel: [spec, this.versionProp] }); } validate(object) { const errors = new Errors(); this.contentValidator(object, errors); return errors.getErrors(); } getVersionNumber() { return this.spec.formatVersion; } }; /***/ }, /* 9 */ /***/ function(module, exports) { 'use strict'; function makeNormalMessage(scriptName, heading, text) { return '<div style="border: 1px solid black; background-color: white; padding: 3px 3px;">' + '<div style="font-weight: bold; border-bottom: 1px solid black;font-size: 130%;">' + `${scriptName} ${heading}</div>${text}</div>`; } function makeErrorMessage(scriptName, text) { return '<div style="border: 1px solid black; background-color: white; padding: 3px 3px;">' + '<div style="font-weight: bold; border-bottom: 1px solid black;font-size: 130%;color:red;">' + `${scriptName}</div>${text}</div>`; } class Reporter { constructor(roll20, scriptName) { this.roll20 = roll20; this.scriptName = scriptName; } setPlayer(playerId) { this.playerId = playerId; } reportPublic(heading, text) { // Horrible bug with this at the moment - seems to generate spurious chat // messages when noarchive:true is set // sendChat('ShapedScripts', '' + msg, null, {noarchive:true}); this.roll20.sendChat('', `${makeNormalMessage(this.scriptName, heading, text)}`); } reportPlayer(heading, text) { this.roll20.sendChat('', `/w ${this.getPlayerName()} ${makeNormalMessage(this.scriptName, heading, text)}`); } reportError(text) { this.roll20.sendChat('', `/w ${this.getPlayerName()} ${makeErrorMessage(this.scriptName, text)}`); } getPlayerName() { return this.playerId ? this.roll20.getObj('player', this.playerId).get('displayname').split(/ /)[0] : 'gm'; } } module.exports = Reporter; /***/ }, /* 10 */ /***/ function(module, exports, __webpack_require__) { /* globals unescape */ 'use strict'; const _ = __webpack_require__(2); const parseModule = __webpack_require__(3); const makeCommandProc = __webpack_require__(11); const utils = __webpack_require__(7); const UserError = __webpack_require__(12); const Migrator = __webpack_require__(14); const ShapedConfig = __webpack_require__(15); // Modules const AbilityMaker = __webpack_require__(16); const ConfigUI = __webpack_require__(17); const AdvantageTracker = __webpack_require__(18); const RestManager = __webpack_require__(19); const TraitManager = __webpack_require__(20); const AmmoManager = __webpack_require__(21); /** * @typedef {Object} ChatMessage * @property {string} content * @property {string} type * @property {SelectedItem[]} selected * @property {string} rolltemplate */ /** * * @typedef {Object} SelectedItem * @property {string} _id * @property (string _type */ module.exports = ShapedScripts; function ShapedScripts(logger, myState, roll20, parser, entityLookup, reporter, srdConverter, sanitise, mpp) { let addedTokenIds = []; const reportPublic = reporter.reportPublic.bind(reporter); const reportPlayer = reporter.reportPlayer.bind(reporter); const reportError = reporter.reportError.bind(reporter); const commandProc = makeCommandProc('shaped', roll20); const chatWatchers = []; const advantageTracker = new AdvantageTracker(); const traitManager = new TraitManager(); const ammoManager = new AmmoManager(); const abilityMaker = new AbilityMaker(); const modules = [ abilityMaker, new ConfigUI(), advantageTracker, traitManager, new RestManager(), ammoManager, ]; modules.forEach(module => module.configure(roll20, reporter, logger, myState, commandProc)); /** * * @param {ChatMessage} msg */ this.handleInput = function handleInput(msg) { logger.debug(msg); reporter.setPlayer(msg.playerid); if (msg.type !== 'api') { this.triggerChatWatchers(msg); return; } this.oldStyleModulesConfigure(commandProc).processCommand(msg); }; ///////////////////////////////////////// // Command handlers ///////////////////////////////////////// this.applyTokenDefaults = function applyTokenDefaults(options) { _.each(options.selected.graphic, token => { const represents = token.get('represents'); const character = roll20.getObj('character', represents); if (character) { this.applyCharacterDefaults(character); this.getTokenConfigurer(token)(character); } }); }; this.importStatblock = function importStatblock(options) { logger.info('Importing statblocks for tokens $$$', options.selected.graphic); _.each(options.selected.graphic, token => { const error = `Could not find GM notes on either selected token ${token.get('name')} or the character ` + 'it represents. Have you pasted it in correctly?'; const text = token.get('gmnotes'); if (!text) { const char = roll20.getObj('character', token.get('represents')); if (char) { char.get('gmnotes', notes => { if (notes) { return this.processGMNotes(options, token, notes); } return reportError(error); }); } else { return reportError(error); } } return this.processGMNotes(options, token, text); }); }; this.processGMNotes = function processGMNotes(options, token, text) { text = sanitise(unescape(text), logger); const monsters = parser.parse(text).monsters; mpp(monsters, entityLookup); this.importMonsters(monsters, options, token, [ function gmNotesSetter(character) { character.set('gmnotes', text.replace(/\n/g, '<br>')); }, ]); }; this.importMonstersFromJson = function importMonstersFromJson(options) { if (options.all) { options.monsters = entityLookup.getAll('monsters'); delete options.all; } if (_.isEmpty(options.monsters)) { this.showEntityPicker('monster', 'monsters'); } else { this.importMonsters(options.monsters.slice(0, 20), options, options.selected.graphic, []); options.monsters = options.monsters.slice(20); if (!_.isEmpty(options.monsters)) { setTimeout(() => this.importMonstersFromJson(options), 200); } } }; this.importMonsters = function importMonsters(monsters, options, token, characterProcessors) { const characterRetrievalStrategies = []; if (token) { characterProcessors.push(this.getAvatarCopier(token).bind(this)); if (_.size(monsters) === 1) { characterProcessors.push(this.getTokenConfigurer(token).bind(this)); characterProcessors.push(this.getTokenVisionConfigurer(token, monsters[0].senses)); if (options.replace || options.overwrite) { characterRetrievalStrategies.push(this.getTokenRetrievalStrategy(token).bind(this)); } } } if (options.replace) { characterRetrievalStrategies.push(this.nameRetrievalStrategy); } characterRetrievalStrategies.push(this.creationRetrievalStrategy.bind(this)); characterProcessors.push(this.monsterDataPopulator.bind(this)); const errors = []; const importedList = _.chain(monsters) .map(monsterData => { const character = _.reduce(characterRetrievalStrategies, (result, strategy) => result || strategy(monsterData.name, errors), null); if (!character) { logger.error('Failed to find or create character for monster $$$', monsterData.name); return null; } const oldAttrs = roll20.findObjs({ type: 'attribute', characterid: character.id }); _.invoke(oldAttrs, 'remove'); character.set('name', monsterData.name); _.each(characterProcessors, proc => proc(character, monsterData)); return character && character.get('name'); }) .compact() .value(); if (!_.isEmpty(importedList)) { const monsterList = importedList.join('</li><li>'); reportPlayer('Import Success', `Added the following monsters: <ul><li>${monsterList}</li></ul>`); } if (!_.isEmpty(errors)) { const errorList = errors.join('</li><li>'); reportError(`The following errors occurred on import: <ul><li>${errorList}</li></ul>`); } }; this.importSpellsFromJson = function importSpellsFromJson(options) { if (_.isEmpty(options.spells)) { this.showEntityPicker('spell', 'spells'); } else { this.addSpellsToCharacter(options.selected.character, options.spells); } }; this.importSpellListFromJson = function importSpellListFromJson(options) { const spells = entityLookup.searchEntities('spells', _.pick(options, _.keys(ShapedConfig.spellSearchOptions))); const newOpts = _.omit(options, _.keys(ShapedConfig.spellSearchOptions)); newOpts.spells = spells; this.importSpellsFromJson(newOpts); }; this.getEntityCriteriaAdaptor = function getEntityCriteriaAdaptor(entityType) { return function entityCriteriaAdaptor(criterionOption, options) { const result = entityLookup.searchEntities(entityType, criterionOption, options[entityType]); if (result) { // If we get a result, wipe the existing list so that the new one replaces it options[entityType] = []; } return result; }; }; this.showEntityPicker = function showEntityPicker(entityName, entityNamePlural) { const list = entityLookup.getKeys(entityNamePlural, true); if (!_.isEmpty(list)) { // title case the names for better display list.forEach((part, index) => (list[index] = utils.toTitleCase(part))); // create a clickable button with a roll query to select an entity from the loaded json reportPlayer(`${utils.toTitleCase(entityName)} Importer`, `<a href="!shaped-import-${entityName} --?{Pick a ${entityName}|${list.join('|')}}">Click to select a ` + `${entityName}</a>`); } else { reportError(`Could not find any ${entityNamePlural}.<br/>Please ensure you have a properly formatted ` + `${entityNamePlural} json file.`); } }; this.addSpellsToCharacter = function addSpellsToCharacter(character, spells, noreport) { const gender = roll20.getAttrByName(character.id, 'gender'); const defaultIndex = Math.min(myState.config.defaultGenderIndex, myState.config.genderPronouns.length); const defaultPronounInfo = myState.config.genderPronouns[defaultIndex]; const pronounInfo = _.clone(_.find(myState.config.genderPronouns, pronounDetails => new RegExp(pronounDetails.matchPattern, 'i').test(gender)) || defaultPronounInfo); _.defaults(pronounInfo, defaultPronounInfo); const importData = { spells: srdConverter.convertSpells(spells, pronounInfo), }; this.getImportDataWrapper(character).mergeImportData(importData); if (!noreport) { reportPlayer('Import Success', 'Added the following spells: <ul><li>' + `${_.map(importData.spells, spell => spell.name).join('</li><li>')}</li></ul>`); } }; this.monsterDataPopulator = function monsterDataPopulator(character, monsterData) { this.applyCharacterDefaults(character); const converted = srdConverter.convertMonster(monsterData); logger.debug('Converted monster data: $$$', converted); const expandedSpells = converted.spells; delete converted.spells; this.getImportDataWrapper(character).setNewImportData({ npc: converted }); if (expandedSpells) { this.addSpellsToCharacter(character, expandedSpells, true); } return character; }; this.getTokenRetrievalStrategy = function getTokenRetrievalStrategy(token) { return function tokenRetrievalStrategy(name, errors) { if (token) { const character = roll20.getObj('character', token.get('represents')); if (character && roll20.getAttrByName(character.id, 'locked')) { errors.push(`Character with name ${character.get('name')} and id ${character.id}` + ' was locked and cannot be overwritten'); return null; } return character; } return null; }; }; this.nameRetrievalStrategy = function nameRetrievalStrategy(name, errors) { const chars = roll20.findObjs({ type: 'character', name }); if (chars.length > 1) { errors.push(`More than one existing character found with name "${name}". Can\'t replace`); return null; } if (chars[0] && roll20.getAttrByName(chars[0].id, 'locked')) { errors.push(`Character with name ${chars[0].get('name')} and id ${chars[0].id}` + ' was locked and cannot be overwritten'); return null; } return chars[0]; }; this.creationRetrievalStrategy = function creationRetrievalStrategy(name, errors) { if (!_.isEmpty(roll20.findObjs({ type: 'character', name }))) { errors.push(`Can\'t create new character with name "${name}` + '" because one already exists with that name. Perhaps you want --replace?'); return null; } return roll20.createObj('character', { name }); }; this.getAvatarCopier = function getAvatarCopier(token) { return function avatarCopier(character) { character.set('avatar', token.get('imgsrc')); }; }; this.applyCharacterDefaults = function applyCharacterDefaults(character) { _.each(utils.flattenObject(_.omit(myState.config.newCharSettings, 'tokenActions')), (value, key) => { const attrName = ShapedConfig.configToAttributeLookup[key]; if (attrName) { const attribute = roll20.getOrCreateAttr(character.id, attrName); if (value === '***default***' || (_.isBoolean(value) && !value)) { attribute.remove(); } else { attribute.set('current', _.isBoolean(value) ? 'on' : value); } } }); const abilityNames = _.chain(myState.config.newCharSettings.tokenActions) .map((action, actionName) => (action === true ? actionName : action)) .compact() .values() .value(); abilityMaker.addAbilitiesByName(abilityNames, character); }; this.getTokenConfigurer = function getTokenConfigurer(token) { return function tokenConfigurer(character) { token.set('represents', character.id); token.set('name', character.get('name')); const settings = myState.config.tokenSettings; if (settings.number && token.get('name').indexOf('%%NUMBERED%%') === -1) { token.set('name', `${token.get('name')} %%NUMBERED%%`); } _.chain(settings) .pick(['bar1', 'bar2', 'bar3']) .each((bar, barName) => { if (!_.isEmpty(bar.attribute)) { const attribute = roll20.getOrCreateAttr(character.id, bar.attribute); if (attribute) { token.set(`${barName}_value`, attribute.get('current')); if (bar.max) { token.set(`${barName}_max`, attribute.get('max')); } token.set(`showplayers_${barName}`, bar.showPlayers); if (bar.link) { token.set(`${barName}_link`, attribute.id); } } } }); // auras _.chain(settings) .pick(['aura1', 'aura2']) .each((aura, auraName) => { token.set(`${auraName}_radius`, aura.radius); token.set(`${auraName}_color`, aura.color); token.set(`${auraName}_square`, aura.square); }); logger.debug('Settings for tokens: $$$', settings); token.set('showname', settings.showName); token.set('showplayers_name', settings.showNameToPlayers); token.set('showplayers_aura1', settings.showAura1ToPlayers); token.set('showplayers_aura2', settings.showAura2ToPlayers); token.set('light_radius', settings.light.radius); token.set('light_dimradius', settings.light.dimRadius); token.set('light_otherplayers', settings.light.otherPlayers); token.set('light_hassight', settings.light.hasSight); token.set('light_angle', settings.light.angle); token.set('light_losangle', settings.light.losAngle); token.set('light_multiplier', settings.light.multiplier); }; }; this.getTokenVisionConfigurer = function getTokenVisionConfigurer(token, sensesString) { if (_.isEmpty(sensesString)) { return _.noop; } function fullRadiusLightConfigurer() { token.set('light_radius', Math.max(token.get('light_radius') || 0, this.lightRadius)); token.set('light_dimradius', Math.max(token.get('light_dimradius') || 0, this.lightRadius)); } function darkvisionLightConfigurer() { token.set('light_radius', Math.max(token.get('light_radius') || 0, this.lightRadius * 1.1666666)); if (!token.get('light_dimradius')) { token.set('light_dimradius', -5); } } const configureFunctions = { blindsight: fullRadiusLightConfigurer, truesight: fullRadiusLightConfigurer, tremorsense: fullRadiusLightConfigurer, darkvision: darkvisionLightConfigurer, }; const re = /(blindsight|darkvision|tremorsense|truesight)\s+(\d+)/; let match; const senses = []; while ((match = sensesString.match(re))) { senses.push({ name: match[1], lightRadius: parseInt(match[2], 10), configureVision: configureFunctions[match[1]], }); sensesString = sensesString.slice(match.index + match[0].length); } return function configureTokenVision() { senses.forEach(sense => sense.configureVision()); }; }; this.getImportDataWrapper = function getImportDataWrapper(character) { return { setNewImportData(importData) { if (_.isEmpty(importData)) { return; } roll20.setAttrByName(character.id, 'import_data', JSON.stringify(importData)); roll20.setAttrByName(character.id, 'import_data_present', 'on'); }, mergeImportData(importData) { if (_.isEmpty(importData)) { return undefined; } const attr = roll20.getOrCreateAttr(character.id, 'import_data'); const dataPresentAttr = roll20.getOrCreateAttr(character.id, 'import_data_present'); let current = {}; try { if (!_.isEmpty(attr.get('current').trim())) { current = JSON.parse(attr.get('current')); } } catch (e) { logger.warn('Existing import_data attribute value was not valid JSON: [$$$]', attr.get('current')); } _.each(importData, (value, key) => { const currentVal = current[key]; if (currentVal) { if (!_.isArray(currentVal)) { current[key] = [currentVal]; } current[key] = current[key].concat(value); } else { current[key] = value; } }); logger.debug('Setting import data to $$$', current); attr.set('current', JSON.stringify(current)); dataPresentAttr.set('current', 'on'); return current; }, logWrap: 'importDataWrapper', }; }; this.handleSlots = function handleSlots(options) { if (options.use) { roll20.processAttrValue(options.character.id, `spell_slots_l${options.use}`, val => Math.max(0, --val)); } if (options.restore) { const attrName = `spell_slots_l${options.restore}`; const max = roll20.getAttrByName(options.character.id, attrName, 'max'); roll20.processAttrValue(options.character.id, `spell_slots_l${options.restore}`, val => { const retVal = Math.min(max, ++val); logger.debug('Setting attribute to $$$', retVal); return retVal; }); } }; ///////////////////////////////////////////////// // Event Handlers ///////////////////////////////////////////////// this.handleAddToken = function handleAddToken(token) { const represents = token.get('represents'); if (_.isEmpty(represents)) { return; } const character = roll20.getObj('character', represents); if (!character) { return; } addedTokenIds.push(token.id); const wrappedChangeToken = this.wrapHandler(this.handleChangeToken); // URGH. Thanks Roll20. setTimeout((function wrapper(id) { return function innerWrapper() { const addedToken = roll20.getObj('graphic', id); if (addedToken) { wrappedChangeToken(addedToken); } }; /* eslint-disable no-spaced-func */ }(token.id)), 100); /* eslint-enable no-spaced-func */ }; this.handleChangeToken = function handleChangeToken(token) { if (_.contains(addedTokenIds, token.id)) { addedTokenIds = _.without(addedTokenIds, token.id); this.setTokenBarsOnDrop(token, true); advantageTracker.handleTokenChange(token); } }; this.handleAddCharacter = function handleAddCharacter(character) { if (myState.config.newCharSettings.applyToAll) { this.applyCharacterDefaults(character); } }; this.setTokenBarsOnDrop = function setTokenBarsOnDrop(token, overwrite) { const character = roll20.getObj('character', token.get('represents')); if (!character) { return; } function setBar(barName, bar, value) { if (value) { token.set(`${barName}_value`, value); if (bar.max) { token.set(`${barName}_max`, value); } } } _.chain(myState.config.tokenSettings) .pick('bar1', 'bar2', 'bar3') .each((bar, barName) => { if (bar.attribute && !token.get(`${barName}_link`) && (!token.get(`${barName}_value`) || overwrite)) { if (bar.attribute === 'HP' && myState.config.sheetEnhancements.rollHPOnDrop) { // Guard against characters that aren't properly configured - i.e. ones used for templates and system // things rather than actual characters if (_.isEmpty(roll20.getAttrByName(character.id, 'hp_formula'))) { logger.debug('Ignoring character $$$ for rolling HP - has no hp_formula attribute', character.get('name')); return; } roll20.sendChat('', `%{${character.get('name')}|shaped_npc_hp}`, results => { if (results && results.length === 1) { const message = this.processInlinerolls(results[0]); if (!results[0].inlinerolls || !results[0].inlinerolls[0]) { logger.warn('HP roll didn\'t have the expected structure. This is what we got back: $$$', results[0]); } else { roll20.sendChat('HP Roller', `/w GM &{template:5e-shaped} ${message}`); setBar(barName, bar, results[0].inlinerolls[0].results.total); } } }); } else { setBar(barName, bar, roll20.getAttrByName(character.id, bar.attribute)); } } }); }; this.registerChatWatcher = function registerChatWatcher(handler, triggerFields) { const matchers = []; if (triggerFields && !_.isEmpty(triggerFields)) { matchers.push((msg, options) => { logger.debug('Matching options: $$$ against triggerFields $$$', options, triggerFields); return _.intersection(triggerFields, _.keys(options)).length === triggerFields.length; }); } chatWatchers.push({ matchers, handler: handler.bind(this) }); }; this.triggerChatWatchers = function triggerChatWatchers(msg) { const options = this.getRollTemplateOptions(msg); logger.debug('Roll template options: $$$', options); _.each(chatWatchers, watcher => { if (_.every(watcher.matchers, matcher => matcher(msg, options))) { watcher.handler(options, msg); } }); }; /** * * @param options * @param {ChatMessage} msg */ this.handleAmmo = function handleAmmo(options, msg) { if (!roll20.checkCharacterFlag(options.character.id, 'ammo_auto_use')) { return; } ammoManager.consumeAmmo(options, msg); }; this.handleHD = function handleHD(options, msg) { const match = options.title.match(/(\d+)d(\d+) HIT_DICE/); if (match && myState.config.sheetEnhancements.autoHD) { const hdCount = parseInt(match[1], 10); const hdSize = match[2]; const hdAttr = roll20.getAttrObjectByName(options.character.id, `hd_d${hdSize}`); const hpAttr = roll20.getOrCreateAttr(options.character.id, 'HP'); const newHp = Math.min(parseInt(hpAttr.get('current') || 0, 10) + this.getRollValue(msg, options.roll1), hpAttr.get('max') || Infinity); if (hdAttr) { if (hdCount <= hdAttr.get('current')) { hdAttr.set('current', hdAttr.get('current') - hdCount); hpAttr.set('current', newHp); if (!hpAttr.get('max')) { hpAttr.set('max', newHp); } } else { reportPublic('HD Police', `${options.characterName} can't use ${hdCount}d${hdSize} hit dice because they ` + `only have ${hdAttr.get('current')} left`); } } } }; this.handleD20Roll = function handleD20Roll(options) { if (options.disadvantage || options.advantage) { const autoRevertOptions = roll20.getAttrByName(options.character.id, 'auto_revert_advantage'); if (autoRevertOptions === 'on') { advantageTracker.setRollOption('normal', [options.character]); } } }; this.handleTraitClick = function handleTraitClick(options) { if (myState.config.sheetEnhancements.autoTraits) { traitManager.handleTraitClick(options); } }; this.handleSpellCast = function handleSpellCast(options) { if (options.friendlyLevel === 'Cantrip' || !myState.config.sheetEnhancements.autoSpellSlots) { return; } const spellLevel = parseInt(options.friendlyLevel.slice(0, 1), 10); const level = options.castAsLevel ? parseInt(options.castAsLevel, 10) : spellLevel; const availableSlots = _.chain(_.range(spellLevel, 10)) .map(slotLevel => roll20.getAttrObjectByName(options.character.id, `spell_slots_l${slotLevel}`)) .compact() .filter(attr => attr.get('current') > 0) .value(); const spellId = _.chain(roll20.getRepeatingSectionItemIdsByName(options.character.id, 'spell')) .pick(options.title.toLowerCase()) .values() .first() .value(); logger.debug('Spell id : $$$', spellId); const ritual = spellId ? !!roll20.getAttrByName(options.character.id, `repeating_spell_${spellId}_ritual`) : false; let msg; const bestSlot = availableSlots .find(slot => parseInt(slot.get('name').match(/spell_slots_l(\d)/)[1], 10) === level) || _.first(availableSlots); if (bestSlot) { const slotLevel = parseInt(bestSlot.get('name').match(/spell_slots_l(\d)/)[1], 10); if (slotLevel === level) { bestSlot.set('current', bestSlot.get('current') - 1); if (ritual) { msg = `1 slot of level ${level} used. [Cast as ritual](!shaped-slots --restore ${level} ` + `--character ${options.character.id}) instead?`; } } else if (!options.castAsLevel) { msg = `You have no level ${level} spell slots left. Do you want to ` + `[Cast at level ${slotLevel}](!shaped-slots --use ${slotLevel} --character ${options.character.id}) instead?`; if (ritual) { msg += ' Alternatively, you could cast a ritual without using a slot.'; } } else { msg = `You have no ${level} spell slots left. You can ` + `[Recast at level ${slotLevel}](!&#13;&#37;{${options.character.get('name')}` + `|repeating_spell_${spellId}_spell})`; if (ritual) { msg += ' or cast as a ritual instead.'; } } } else { msg = `${options.character.get('name')} has no spell slots of level ${level} to cast ${options.title}`; if (ritual) { msg += ' but could cast as a ritual instead without using a slot.'; } } if (msg) { roll20.sendChat('Spell Slots Police', msg); } }; this.handleDeathSave = function handleDeathSave(options, msg) { // TODO: Do we want to output text on death/recovery? function increment(val) { return ++val; } // TODO: Advantage? if (roll20.getAttrByName(options.character.id, 'roll_setting') !== '{{roll2=[[d20@{d20_mod}') { const result = this.getRollValue(msg, options.roll1); const attributeToIncrement = result >= 10 ? 'death_saving_throw_successes' : 'death_saving_throw_failures'; roll20.processAttrValue(options.character.id, attributeToIncrement, increment); } }; this.handleFX = function handleFX(options, msg) { const parts = options.fx.split(' '); if (parts.length < 2 || _.some(parts.slice(0, 2), _.isEmpty)) { logger.warn('FX roll template variable is not formated correctly: [$$$]', options.fx); return; } const fxType = parts[0]; const pointsOfOrigin = parts[1]; let targetTokenId; const sourceCoords = {}; const targetCoords = {}; let fxCoords = []; let pageId; // noinspection FallThroughInSwitchStatementJS switch (pointsOfOrigin) { case 'sourceToTarget': case 'source': targetTokenId = parts[2]; fxCoords.push(sourceCoords, targetCoords); break; case 'targetToSource': case 'target': targetTokenId = parts[2]; fxCoords.push(targetCoords, sourceCoords); break; default: throw new Error(`Unrecognised pointsOfOrigin type in fx spec: ${pointsOfOrigin}`); } if (targetTokenId) { const targetToken = roll20.getObj('graphic', targetTokenId); pageId = targetToken.get('_pageid'); targetCoords.x = targetToken.get('left'); targetCoords.y = targetToken.get('top'); } else { pageId = roll20.getCurrentPage(msg.playerid).id; } const casterTokens = roll20.findObjs({ type: 'graphic', pageid: pageId, represents: options.character.id }); if (casterTokens.length) { // If there are multiple tokens for the character on this page, then try and find one of them that is selected // This doesn't work without a selected token, and the only way we can get this is to use @{selected} which is a // pain for people who want to launch without a token selected if(casterTokens.length > 1) { const selected = // _.findWhere(casterTokens, {id: sourceTokenId}); if (selected) { casterTokens = [selected]; } } sourceCoords.x = casterTokens[0].get('left'); sourceCoords.y = casterTokens[0].get('top'); } if (!fxCoords[0]) { logger.warn('Couldn\'t find required point for fx for character $$$, casterTokens: $$$, fxSpec: $$$ ', options.character.id, casterTokens, options.fx); return; } else if (!fxCoords[1]) { fxCoords = fxCoords.slice(0, 1); } roll20.spawnFx(fxCoords, fxType, pageId); }; this.getRollValue = function getRollValue(msg, rollOutputExpr) { const rollIndex = rollOutputExpr.match(/\$\[\[(\d+)\]\]/)[1]; return msg.inlinerolls[rollIndex].results.total; }; /** * * @returns {*} */ this.getRollTemplateOptions = function getRollTemplateOptions(msg) { if (msg.rolltemplate === '5e-shaped') { const regex = /\{\{(.*?)\}\}/g; let match; const options = {}; while (!!(match = regex.exec(msg.content))) { if (match[1]) { const splitAttr = match[1].split('='); const propertyName = splitAttr[0].replace(/_([a-z])/g, (m, letter) => letter.toUpperCase()); options[propertyName] = splitAttr.length === 2 ? splitAttr[1].replace(/\^\{/, '') : ''; } } if (options.characterName) { options.character = roll20.findObjs({ _type: 'character', name: options.characterName, })[0]; } return options; } return {}; }; this.processInlinerolls = function processInlinerolls(msg) { if (_.has(msg, 'inlinerolls')) { return _.chain(msg.inlinerolls) .reduce((previous, current, index) => { previous[`$[[${index}]]`] = current.results.total || 0; return previous; }, {}) .reduce((previous, current, index) => previous.replace(index.toString(), current), msg.content) .value(); } return msg.content; }; // This method can go once all functions are moved into modules which handle their own configuration this.commandProcConfigured = false; this.oldStyleModulesConfigure = function oldStyleModulesConfigure(cp) { if (this.commandProcConfigured) { return cp; } this.commandProcConfigured = true; return cp // !shaped-import-statblock .addCommand('import-statblock', this.importStatblock.bind(this), true) .option('overwrite', ShapedConfig.booleanValidator) .option('replace', ShapedConfig.booleanValidator) .withSelection({ graphic: { min: 1, max: Infinity, }, }) // !shaped-import-monster , !shaped-monster .addCommand(['import-monster', 'monster'], this.importMonstersFromJson.bind(this), true) .option('all', ShapedConfig.booleanValidator) .optionLookup('monsters', _.partial(entityLookup.findEntity.bind(entityLookup), 'monsters', _, false)) .option('overwrite', ShapedConfig.booleanValidator) .option('replace', ShapedConfig.booleanValidator) .withSelection({ graphic: { min: 0, max: 1, }, }) // !shaped-import-spell, !shaped-spell .addCommand(['import-spell', 'spell'], this.importSpellsFromJson.bind(this), false) .optionLookup('spells', _.partial(entityLookup.findEntity.bind(entityLookup), 'spells', _, false)) .withSelection({ character: { min: 1, max: 1, }, }) // !shaped-import-spell-list .addCommand('import-spell-list', this.importSpellListFromJson.bind(this), false) .options(ShapedConfig.spellSearchOptions) .withSelection({ character: { min: 1, max: 1, }, }) // !shaped-token-defaults .addCommand(['token-defaults', 'apply-defaults'], this.applyTokenDefaults.bind(this), false) .withSelection({ graphic: { min: 1, max: Infinity, }, }) // !shaped-slots .addCommand('slots', this.handleSlots.bind(this), false) .option('character', ShapedConfig.getCharacterValidator(roll20), true) .option('use', ShapedConfig.integerValidator) .option('restore', ShapedConfig.integerValidator); }; this.checkInstall = function checkInstall() { logger.info('-=> ShapedScripts v4.4.1 <=-'); Migrator.migrateShapedConfig(myState, logger); }; this.wrapHandler = function wrapHandler(handler) { const self = this; return function handlerWrapper() { try { handler.apply(self, arguments); } catch (e) { if (typeof e === 'string' || e instanceof parseModule.ParserError || e instanceof UserError) { reportError(e); logger.error('Error: $$$', e.toString()); } else { logger.error(e.toString()); logger.error(e.stack); reportError('An error occurred. Please see the log for more details.'); } } finally { logger.prefixString = ''; } }; }; this.updateBarsForCharacterTokens = function updateBarsForCharacterTokens(curr) { roll20.findObjs({ type: 'graphic', represents: curr.get('characterid') }) .forEach(token => this.setTokenBarsOnDrop(token, false)); }; this.getAttributeChangeHandler = function getAttributeChangeHandler(attributeName) { const handlers = { roll_setting: advantageTracker.handleRollOptionChange.bind(advantageTracker), }; _.chain(myState.config.tokenSettings) .pick('bar1', 'bar2', 'bar3') .pluck('attribute') .each(attrName => { if (attrName === 'HP') { attrName = 'hp_formula'; } handlers[attrName] = this.updateBarsForCharacterTokens.bind(this); }); return handlers[attributeName]; }; this.registerEventHandlers = function registerEventHandlers() { roll20.on('chat:message', this.wrapHandler(this.handleInput)); roll20.on('add:token', this.wrapHandler(this.handleAddToken)); roll20.on('change:token', this.wrapHandler(this.handleChangeToken)); roll20.on('change:attribute', this.wrapHandler((curr, prev) => { const handler = this.getAttributeChangeHandler(curr.get('name')); if (handler) { handler(curr, prev); } })); roll20.on('add:character', this.wrapHandler(this.handleAddCharacter)); this.registerChatWatcher(this.handleDeathSave, ['deathSavingThrow', 'character', 'roll1']); this.registerChatWatcher(this.handleAmmo, ['ammoName', 'character']); this.registerChatWatcher(this.handleFX, ['fx', 'character']); this.registerChatWatcher(this.handleHD, ['character', 'title']); this.registerChatWatcher(this.handleD20Roll, ['character', 'roll1']); this.registerChatWatcher(this.handleTraitClick, ['character', 'trait']); // this.registerChatWatcher(this.handleSpellCast, ['character', 'spell', 'friendlyLevel']); }; logger.wrapModule(this); } ShapedScripts.prototype.logWrap = 'ShapedScripts'; /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; const _ = __webpack_require__(2); const utils = __webpack_require__(7); const UserError = __webpack_require__(12); const ShapedModule = __webpack_require__(13); function getParser(optionString, validator) { return function parseOptions(arg, errors, options) { const argParts = arg.split(/\s+/); if (argParts[0].toLowerCase() === optionString.toLowerCase()) { const value = argParts.length === 1 ? true : argParts.slice(1).join(' '); const result = validator(value); if (result.valid) { options[argParts[0]] = result.converted; } else { errors.push(`Invalid value [${value}] for option [${argParts[0]}]`); } return true; } return false; }; } function getObjectParser(specObject) { return function parseOptions(arg, errors, options) { const argParts = arg.split(/\s+/); const newObject = utils.createObjectFromPath(argParts[0], argParts.slice(1).join(' ')); const comparison = { spec: specObject, actual: newObject }; while (comparison.spec) { const key = _.keys(comparison.actual)[0]; const spec = comparison.spec[key]; if (!spec) { return false; } if (_.isFunction(comparison.spec[key])) { const result = comparison.spec[key](comparison.actual[key]); if (result.valid) { comparison.actual[key] = result.converted; utils.deepExtend(options, newObject); } else { errors.push(`Invalid value [${comparison.actual[key]}] for option [${argParts[0]}]`); } return true; } else if (_.isArray(comparison.actual[key])) { const newVal = []; newVal[comparison.actual[key].length - 1] = comparison.spec[key][0]; comparison.spec = newVal; comparison.actual = comparison.actual[key]; } else { comparison.spec = comparison.spec[key]; comparison.actual = comparison.actual[key]; } } return false; }; } /** * @constructor */ class Command { constructor(root, handler, roll20, name, gmOnly) { this.root = root; this.handler = handler; this.parsers = []; this.roll20 = roll20; this.name = name; this.gmOnly = gmOnly; } option(optionString, validator, required) { let parser; if (_.isFunction(validator)) { parser = getParser(optionString, validator); } else if (_.isObject(validator)) { const dummy = {}; dummy[optionString] = validator; parser = getObjectParser(dummy); } else { throw new Error(`Bad validator [${validator}] specified for option ${optionString}`); } parser.required = required; parser.optName = optionString; this.parsers.push(parser); return this; } options(optsSpec) { _.each(optsSpec, (validator, key) => this.option(key, validator)); return this; } optionLookup(groupName, lookup, required) { if (typeof lookup !== 'function') { lookup = _.propertyOf(lookup); } const parser = (arg, errors, options) => { const singleResolved = lookup(arg, options); if (singleResolved) { options[groupName] = options[groupName] || []; options[groupName].push.apply(options[groupName], _.isArray(singleResolved) ? singleResolved : [singleResolved]); return true; } const results = _.chain(arg.split(',')) .map(_.partial(_.result, _, 'trim')) .uniq() .reduce((memo, name) => { const resolvedPart = lookup(name, options); if (resolvedPart) { memo.resolved.push(resolvedPart); } else { memo.errors.push(`Unrecognised item ${name} for option group ${groupName}`); } return memo; }, { errors: [], resolved: [] }) .value(); if (!_.isEmpty(results.resolved)) { options[groupName] = results.resolved; errors.push.apply(errors, results.errors); return true; } return false; }; parser.optName = groupName; parser.required = required; this.parsers.push(parser); return this; } handle(args, selection, cmdString, playerIsGM, playerId) { if (!playerIsGM && this.gmOnly) { throw new UserError('You must be a GM to run this command'); } const caches = {}; const startOptions = { errors: [], }; Object.defineProperty(startOptions, 'getCache', { enumerable: false, value: function getCache(key) { return (caches[key] = caches[key] || {}); }, }); startOptions.selected = this.selectionSpec && processSelection(selection || [], this.selectionSpec, this.roll20); const finalOptions = _.chain(args) .reduce((options, arg) => { if (!_.some(this.parsers, parser => parser(arg, options.errors, options))) { options.errors.push(`Unrecognised or poorly formed option ${arg}`); } return options; }, startOptions) .each((propVal, propName, obj) => { // NB Cannot use omit or it will remove the getCache property if (_.isUndefined(propVal)) { delete obj[propName]; } }) .value(); if (finalOptions.errors.length > 0) { throw finalOptions.errors.join('\n'); } delete finalOptions.errors; const missingOpts = _.chain(this.parsers) .where({ required: true }) .pluck('optName') .difference(_.keys(finalOptions)) .value(); if (!_.isEmpty(missingOpts)) { throw new UserError(`Command ${cmdString} was missing options: [${missingOpts.join(',')}]`); } if (finalOptions.character && !playerIsGM) { finalOptions.character.forEach(character => { if (!character.controlledby.contains(playerId) && !character.controlledby.contains('all')) { throw new UserError(`You do not have permission to make changes to character ${character.get('name')}`); } }); } this.handler(finalOptions); } withSelection(selectionSpec) { this.selectionSpec = selectionSpec; return this; } addCommand() { return this.root.addCommand.apply(this.root, arguments); } addModule() { return this.root.addModule.apply(this.root, arguments); } processCommand() { return this.root.processCommand.apply(this.root, arguments); } get logWrap() { return `command [${this.name}]`; } } function processSelection(selection, constraints, roll20) { return _.reduce(constraints, (result, constraintDetails, type) => { const objects = _.chain(selection) .where({ _type: type === 'character' ? 'graphic' : type }) .map(selected => roll20.getObj(selected._type, selected._id)) .map(object => { if (type === 'character' && object) { return roll20.getObj('character', object.get('represents')); } return object; }) .compact() .uniq() .value(); if (_.size(objects) < constraintDetails.min || _.size(objects) > constraintDetails.max) { throw new UserError(`Wrong number of objects of type [${type}] selected, should be between ` + `${constraintDetails.min} and ${constraintDetails.max}`); } switch (_.size(objects)) { case 0: break; case 1: if (constraintDetails.max === 1) { result[type] = objects[0]; } else { result[type] = objects; } break; default: result[type] = objects; } return result; }, {}); } module.exports = function commandParser(rootCommand, roll20) { const commands = {}; return { addCommand(cmds, handler, gmOnly) { const command = new Command(this, handler, roll20, _.isArray(cmds) ? cmds.join(',') : cmds, gmOnly); (_.isArray(cmds) ? cmds : [cmds]).forEach(cmdString => (commands[cmdString] = command)); return command; }, addModule(module) { if (!module instanceof ShapedModule) { throw new Error('Can only pass ShapedModules to addModule'); } return module.configure(this); }, processCommand(msg) { const prefix = `!${rootCommand}-`; if (msg.type === 'api' && msg.content.indexOf(prefix) === 0) { const cmdString = msg.content.slice(prefix.length); const parts = cmdString.split(/\s+--/); const cmdName = parts.shift(); const cmd = commands[cmdName]; if (!cmd) { throw new UserError(`Unrecognised command ${prefix}${cmdName}`); } cmd.handle(parts, msg.selected, `${prefix}${cmdName}`, roll20.playerIsGM(msg.playerid), msg.playerid); } }, logWrap: 'commandParser', }; }; /***/ }, /* 12 */ /***/ function(module, exports) { 'use strict'; class UserError extends Error { constructor(message) { super(); this.message = message; } } module.exports = UserError; /***/ }, /* 13 */ /***/ function(module, exports) { 'use strict'; module.exports = class ShapedModule { configure(roll20, reporter, logger, myState, commandProcessor) { this.roll20 = roll20; this.reporter = reporter; this.logger = logger; this.myState = myState; this.addCommands(commandProcessor); logger.wrapModule(this); } addCommands(/* commandProcessor */) { throw new Error('Subclasses must implement addCommands'); } reportPublic(heading, text) { this.reporter.reportPublic(heading, text); } reportPlayer(heading, text) { this.reporter.reportPlayer(heading, text); } reportError(text) { this.reporter.reportError(text); } get logWrap() { return this.constructor.name; } }; /***/ }, /* 14 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; const _ = __webpack_require__(2); const utils = __webpack_require__(7); const oneSixConfig = { logLevel: 'INFO', tokenSettings: { number: false, bar1: { attribute: 'HP', max: true, link: false, showPlayers: false, }, bar2: { attribute: 'speed', max: false, link: true, showPlayers: false, }, bar3: { attribute: '', max: false, link: false, showPlayers: false, }, aura1: { radius: '', color: '#FFFF99', square: false, }, aura2: { radius: '', color: '#59e594', square: false, }, light: { radius: '', dimRadius: '', otherPlayers: false, hasSight: false, angle: 360, losAngle: 360, multiplier: 1, }, showName: true, showNameToPlayers: false, showAura1ToPlayers: true, showAura2ToPlayers: true, }, newCharSettings: { sheetOutput: '@{output_to_all}', deathSaveOutput: '@{output_to_all}', initiativeOutput: '@{output_to_all}', showNameOnRollTemplate: '@{show_character_name_yes}', rollOptions: '@{normal}', initiativeRoll: '@{normal_initiative}', initiativeToTracker: '@{initiative_to_tracker_yes}', breakInitiativeTies: '@{initiative_tie_breaker_var}', showTargetAC: '@{attacks_vs_target_ac_no}', showTargetName: '@{attacks_vs_target_name_no}', autoAmmo: '@{ammo_auto_use_var}', autoRevertAdvantage: false, houserules: { savingThrowsHalfProf: false, mediumArmorMaxDex: 2, }, }, advTrackerSettings: { showMarkers: false, ignoreNpcs: false, advantageMarker: 'green', disadvantageMarker: 'red', output: 'silent', }, sheetEnhancements: { rollHPOnDrop: true, autoHD: true, autoSpellSlots: true, }, genderPronouns: [ { matchPattern: '^f$|female|girl|woman|feminine', nominative: 'she', accusative: 'her', possessive: 'her', reflexive: 'herself', }, { matchPattern: '^m$|male|boy|man|masculine', nominative: 'he', accusative: 'him', possessive: 'his', reflexive: 'himself', }, { matchPattern: '^n$|neuter|none|construct|thing|object', nominative: 'it', accusative: 'it', possessive: 'its', reflexive: 'itself', }, ], defaultGenderIndex: 2, }; class Migrator { constructor(startVersion) { this._versions = [{ version: startVersion || 0.1, migrations: [] }]; } skipToVersion(version) { this._versions.push({ version, migrations: [] }); return this; } nextVersion() { const currentVersion = this._versions.slice(-1)[0].version; const nextVersion = (currentVersion * 10 + 1) / 10; // Avoid FP errors this._versions.push({ version: nextVersion, migrations: [] }); return this; } addProperty(path, value) { const expandedProperty = utils.createObjectFromPath(path, value); return this.transformConfig((config) => utils.deepExtend(config, expandedProperty), `Adding property ${path} with value ${value}`); } overwriteProperty(path, value) { return this.transformConfig((config) => { const parts = path.split('.'); const obj = parts.length > 1 ? utils.getObjectFromPath(config, parts.slice(0, -1).join('.')) : config; obj[parts.slice(-1)[0]] = value; return config; }, `Overwriting property ${path} with value ${JSON.stringify(value)}`); } copyProperty(oldPath, newPath) { return this.transformConfig(Migrator.propertyCopy.bind(null, oldPath, newPath), `Copying property from ${oldPath} to ${newPath}`); } static propertyCopy(oldPath, newPath, config) { const oldVal = utils.getObjectFromPath(config, oldPath); if (!_.isUndefined(oldVal)) { const expandedProperty = utils.createObjectFromPath(newPath, oldVal); utils.deepExtend(config, expandedProperty); } return config; } static propertyDelete(path, config) { const parts = path.split('.'); const obj = parts.length > 1 ? utils.getObjectFromPath(config, parts.slice(0, -1).join('.')) : config; if (obj && !_.isUndefined(obj[parts.slice(-1)[0]])) { delete obj[parts.slice(-1)[0]]; } return config; } deleteProperty(propertyPath) { return this.transformConfig(Migrator.propertyDelete.bind(null, propertyPath), `Deleting property ${propertyPath} from config`); } moveProperty(oldPath, newPath) { return this.transformConfig((config) => { config = Migrator.propertyCopy(oldPath, newPath, config); return Migrator.propertyDelete(oldPath, config); }, `Moving property from ${oldPath} to ${newPath}`); } transformConfig(transformer, message) { const lastVersion = this._versions.slice(-1)[0]; lastVersion.migrations.push({ transformer, message }); return this; } migrateConfig(state, logger) { logger.info('Checking config for upgrade, starting state: $$$', state); if (_.isEmpty(state)) { // working with a fresh install here state.version = 0; } if (!this._versions.find(version => version.version >= state.version)) { throw new Error(`Unrecognised schema state ${state.version} - cannot upgrade.`); } return this._versions .filter(version => version.version > state.version) .reduce((versionResult, version) => { logger.info('Upgrading schema to version $$$', version.version); versionResult = version.migrations.reduce((result, migration) => { logger.info(migration.message); return migration.transformer(result); }, versionResult); versionResult.version = version.version; logger.info('Post-upgrade state: $$$', versionResult); return versionResult; }, state); } } const migrator = new Migrator() .addProperty('config', {}) .skipToVersion(0.4) .overwriteProperty('config.genderPronouns', utils.deepClone(oneSixConfig).genderPronouns) .skipToVersion(1.2) .moveProperty('config.autoHD', 'config.sheetEnhancements.autoHD') .moveProperty('config.rollHPOnDrop', 'config.sheetEnhancements.rollHPOnDrop') .skipToVersion(1.4) .moveProperty('config.newCharSettings.savingThrowsHalfProf', 'config.newCharSettings.houserules.savingThrowsHalfProf') .moveProperty('config.newCharSettings.mediumArmorMaxDex', 'config.newCharSettings.houserules.mediumArmorMaxDex') .skipToVersion(1.6) .transformConfig(state => { _.defaults(state.config, oneSixConfig); _.defaults(state.config.tokenSettings, oneSixConfig.tokenSettings); _.defaults(state.config.newCharSettings, oneSixConfig.newCharSettings); _.defaults(state.config.advTrackerSettings, oneSixConfig.advTrackerSettings); _.defaults(state.config.sheetEnhancements, oneSixConfig.sheetEnhancements); return state; }, 'Applying defaults as at schema version 1.6') // 1.7 // add base houserules and variants section // add sheetEnhancements.autoTraits .nextVersion() .addProperty('config.variants', { rests: { longNoHpFullHd: false, }, }) .addProperty('config.sheetEnhancements.autoTraits', true) // 1.8 // Set tokens to have vision by default so that people see the auto-generated stuff based on senses .nextVersion() .overwriteProperty('config.tokenSettings.light.hasSight', true) // 1.9 Add default tab setting .nextVersion() .addProperty('config.newCharSettings.tab', 'core') // 2.0 Add default token actions .nextVersion() .addProperty('config.newCharSettings.tokenActions', { initiative: false, abilityChecks: null, advantageTracker: null, savingThrows: null, attacks: null, statblock: false, traits: null, actions: null, reactions: null, legendaryActions: null, lairActions: null, regionalEffects: null, rests: false, }) // 2.1 Add spells token action .nextVersion() .addProperty('config.newCharSettings.tokenActions.spells', false) // 2.2 Changes to support new roll behaviour in sheet 4.2.1 .nextVersion() .overwriteProperty('config.newCharSettings.sheetOutput', '') .overwriteProperty('config.newCharSettings.deathSaveOutput', '') .overwriteProperty('config.newCharSettings.initiativeOutput', '') .overwriteProperty('config.newCharSettings.showNameOnRollTemplate', '') .overwriteProperty('config.newCharSettings.rollOptions', '') .overwriteProperty('config.newCharSettings.initiativeRoll', '') .overwriteProperty('config.newCharSettings.initiativeToTracker', '') .overwriteProperty('config.newCharSettings.breakInitiativeTies', '') .overwriteProperty('config.newCharSettings.showTargetAC', '') .overwriteProperty('config.newCharSettings.showTargetName', '') .overwriteProperty('config.newCharSettings.autoAmmo', '1') // 2.3 Remove "small" macros .nextVersion() .transformConfig(config => { _.each(config.config.newCharSettings.tokenActions, (value, key) => { if (typeof value === 'string' && value.match('.*Small$')) { config.config.newCharSettings.tokenActions[key] = value.replace(/Small$/, ''); } }); return config; }, 'Removing "small" macros') .addProperty('config.newCharSettings.textSizes', { spellsTextSize: 'text', abilityChecksTextSize: 'text', savingThrowsTextSize: 'text', }) // 2.4 Don't set default values for sheet options to save on attribute bloat .nextVersion() .transformConfig(config => { const ncs = config.config.newCharSettings; const defaults = { sheetOutput: '', deathSaveOutput: '', initiativeOutput: '', showNameOnRollTemplate: '', rollOptions: '{{ignore=[[0', initiativeRoll: '@{shaped_d20}', initiativeToTracker: '@{selected|initiative_formula} &{tracker}', breakInitiativeTies: '', showTargetAC: '', showTargetName: '', autoAmmo: '', tab: 'core', }; _.each(defaults, (defaultVal, key) => { if (ncs[key] === defaultVal) { ncs[key] = '***default***'; } }); if (ncs.houserules.mediumArmorMaxDex === '2') { ncs.houserules.mediumArmorMaxDex = '***default***'; } ['spellsTextSize', 'abilityChecksTextSize', 'savingThrowsTextSize'].forEach(prop => { if (ncs.textSizes[prop] === 'text_big') { ncs.textSizes[prop] = '***default***'; } }); return config; }, 'Removing default values') // 2.5 Custom saving throws .nextVersion() .addProperty('config.newCharSettings.houserules.saves', { useCustomSaves: '***default***', useAverageOfAbilities: '***default***', fortitude: { fortitudeStrength: '***default***', fortitudeDexterity: '***default***', fortitudeConstitution: '***default***', fortitudeIntelligence: '***default***', fortitudeWisdom: '***default***', fortitudeCharisma: '***default***', }, reflex: { reflexStrength: '***default***', reflexDexterity: '***default***', reflexConstitution: '***default***', reflexIntelligence: '***default***', reflexWisdom: '***default***', reflexCharisma: '***default***', }, will: { willStrength: '***default***', willDexterity: '***default***', willConstitution: '***default***', willIntelligence: '***default***', willWisdom: '***default***', willCharisma: '***default***', }, }) .moveProperty('config.newCharSettings.houserules.savingThrowsHalfProf', 'config.newCharSettings.houserules.saves.savingThrowsHalfProf') .addProperty('config.newCharSettings.houserules.baseDC', '***default***') // 2.6 expertise_as_advantage .nextVersion() .addProperty('config.newCharSettings.houserules.expertiseAsAdvantage', '***default***') // 2.7 add hide options .nextVersion() .addProperty('config.newCharSettings.hide', { hideAttack: '***default***', hideDamage: '***default***', hideAbilityChecks: '***default***', hideSavingThrows: '***default***', hideSavingThrowDC: '***default***', hideSpellContent: '***default***', hideActionFreetext: '***default***', hideSavingThrowFailure: '***default***', hideSavingThrowSuccess: '***default***', hideRecharge: '***default***', }) // 2.8 rename hideActionFreetext .nextVersion() .moveProperty('config.newCharSettings.hide.hideActionFreetext', 'config.newCharSettings.hide.hideFreetext') // 2.9 make auto-applying new character settings optional (and switched off by default) .nextVersion() .addProperty('config.newCharSettings.applyToAll', false); Migrator.migrateShapedConfig = migrator.migrateConfig.bind(migrator); module.exports = Migrator; /***/ }, /* 15 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; const _ = __webpack_require__(2); module.exports = class ShapedConfig { static get configToAttributeLookup() { const lookup = { sheetOutput: 'output_option', deathSaveOutput: 'death_save_output_option', initiativeOutput: 'initiative_output_option', showNameOnRollTemplate: 'show_character_name', rollOptions: 'roll_setting', initiativeRoll: 'initiative_roll', initiativeToTracker: 'initiative_to_tracker', breakInitiativeTies: 'initiative_tie_breaker', showTargetAC: 'attacks_vs_target_ac', showTargetName: 'attacks_vs_target_name', autoAmmo: 'ammo_auto_use', autoRevertAdvantage: 'auto_revert_advantage', savingThrowsHalfProf: 'saving_throws_half_proficiency', mediumArmorMaxDex: 'medium_armor_max_dex', spellsTextSize: 'spells_text_size', abilityChecksTextSize: 'ability_checks_text_size', savingThrowsTextSize: 'saving_throws_text_size', baseDC: 'base_dc', tab: 'tab', useCustomSaves: 'use_custom_saving_throws', useAverageOfAbilities: 'average_of_abilities', expertiseAsAdvantage: 'expertise_as_advantage', hideAttack: 'hide_attack', hideDamage: 'hide_damage', hideAbilityChecks: 'hide_ability_checks', hideSavingThrows: 'hide_saving_throws', hideSavingThrowDC: 'hide_saving_throw_dc', hideSpellContent: 'hide_spell_content', hideFreetext: 'hide_freetext', hideSavingThrowFailure: 'hide_saving_throw_failure', hideSavingThrowSuccess: 'hide_saving_throw_success', hideRecharge: 'hide_recharge', customSkills: 'custom_skills', }; ['fortitude', 'reflex', 'will'].forEach(save => { ['Strength', 'Dexterity', 'Constitution', 'Intelligence', 'Wisdom', 'Charisma'].forEach(ability => { lookup[`${save}${ability}`] = `${save}_${ability.toLowerCase()}`; }); }); return lookup; } static booleanValidator(value) { const converted = value === 'true' || (value === 'false' ? false : value); return { valid: typeof value === 'boolean' || value === 'true' || value === 'false', converted, }; } static stringValidator(value) { return { valid: true, converted: value, }; } static arrayValidator(value) { return { valid: true, converted: value.split(',').map(s => s.trim()), }; } static getOptionList(options) { return function optionList(value) { if (value === undefined) { return options; } return { converted: options[value], valid: options[value] !== undefined, }; }; } static getHideOption(propertyName) { return this.getOptionList({ false: '***default***', true: `{{${propertyName}=1}}` }); } static getBooleanOptionList() { return this.getOptionList({ true: 1, false: '***default***', }); } static integerValidator(value) { const parsed = parseInt(value, 10); return { converted: parsed, valid: !isNaN(parsed), }; } static colorValidator(value) { return { converted: value, valid: /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(value), }; } static get sheetOutputValidator() { return this.getOptionList({ public: '***default***', whisper: '/w GM', }); } static get textSizeValidator() { return this.getOptionList({ normal: 'text', big: '***default***', }); } static get commandOutputValidator() { return this.getOptionList({ public: 'public', whisper: 'whisper', silent: 'silent', }); } static get statusMarkerValidator() { return this.getOptionList(ShapedConfig.validStatusMarkers()); } static get barValidator() { return { attribute: this.stringValidator, max: this.booleanValidator, link: this.booleanValidator, showPlayers: this.booleanValidator, }; } static get auraValidator() { return { radius: this.stringValidator, color: this.colorValidator, square: this.booleanValidator, }; } static get lightValidator() { return { radius: this.stringValidator, dimRadius: this.stringValidator, otherPlayers: this.booleanValidator, hasSight: this.booleanValidator, angle: this.integerValidator, losAngle: this.integerValidator, multiplier: this.integerValidator, }; } static getCharacterValidator(roll20) { return function characterValidator(value) { const char = roll20.getObj('character', value); return { converted: char, valid: !!char, }; }; } static get spellSearchOptions() { return { classes: this.arrayValidator, domains: this.arrayValidator, oaths: this.arrayValidator, patrons: this.arrayValidator, school: this.stringValidator, level: this.integerValidator, }; } static regExpValidator(value) { try { new RegExp(value, 'i').test(''); return { converted: value, valid: true, }; } catch (e) { return { converted: null, valid: false, }; } } static get configOptionsSpec() { return { tokenSettings: { number: this.booleanValidator, bar1: this.barValidator, bar2: this.barValidator, bar3: this.barValidator, aura1: this.auraValidator, aura2: this.auraValidator, light: this.lightValidator, showName: this.booleanValidator, showNameToPlayers: this.booleanValidator, showAura1ToPlayers: this.booleanValidator, showAura2ToPlayers: this.booleanValidator, }, newCharSettings: { applyToAll: this.booleanValidator, sheetOutput: this.sheetOutputValidator, deathSaveOutput: this.sheetOutputValidator, initiativeOutput: this.sheetOutputValidator, showNameOnRollTemplate: this.getOptionList({ true: '/w GM', false: '***default***', }), rollOptions: this.getOptionList({ normal: '***default***', advantage: 'adv {{ignore=[[0', disadvantage: 'dis {{ignore=[[0', two: '{{roll2=[[d20@{d20_mod}', }), initiativeRoll: this.getOptionList({ normal: '***default***', advantage: '2d20@{d20_mod}kh1', disadvantage: '2d20@{d20_mod}kl1', }), initiativeToTracker: this.getOptionList({ true: '***default***', false: '@{initiative_formula}', }), breakInitiativeTies: this.getOptionList({ true: '[[@{initiative} / 100]][tie breaker]', false: '***default***', }), showTargetAC: this.getOptionList({ true: '[[@{target|AC}]]', false: '***default***', }), showTargetName: this.getOptionList({ true: '@{target|token_name}', false: '***default***', }), autoAmmo: this.getOptionList({ true: '1', false: '***default***', }), autoRevertAdvantage: this.booleanValidator, houserules: { baseDC: this.getOptionList(_.range(0, 21).reduce((result, val) => { result[val] = val === 8 ? '***default***' : val; return result; }, {})), mediumArmorMaxDex: this.getOptionList(_.range(0, 11).reduce((result, val) => { result[val] = val === 2 ? '***default***' : val; return result; }, {})), expertiseAsAdvantage: this.getBooleanOptionList(), saves: { savingThrowsHalfProf: this.booleanValidator, useCustomSaves: this.getBooleanOptionList(), useAverageOfAbilities: this.getBooleanOptionList(), fortitude: { fortitudeStrength: this.getBooleanOptionList(), fortitudeDexterity: this.getBooleanOptionList(), fortitudeConstitution: this.getBooleanOptionList(), fortitudeIntelligence: this.getBooleanOptionList(), fortitudeWisdom: this.getBooleanOptionList(), fortitudeCharisma: this.getBooleanOptionList(), }, reflex: { reflexStrength: this.getBooleanOptionList(), reflexDexterity: this.getBooleanOptionList(), reflexConstitution: this.getBooleanOptionList(), reflexIntelligence: this.getBooleanOptionList(), reflexWisdom: this.getBooleanOptionList(), reflexCharisma: this.getBooleanOptionList(), }, will: { willStrength: this.getBooleanOptionList(), willDexterity: this.getBooleanOptionList(), willConstitution: this.getBooleanOptionList(), willIntelligence: this.getBooleanOptionList(), willWisdom: this.getBooleanOptionList(), willCharisma: this.getBooleanOptionList(), }, }, }, tab: this.getOptionList({ core: '***default***', spells: 'spells', equipment: 'equipment', character: 'character', settings: 'settings', all: 'all', }), tokenActions: { initiative: this.booleanValidator, abilityChecks: this.getOptionList({ none: null, query: 'abilityChecksQuery', chatWindow: 'abilityChecks', queryShort: 'abilChecksQuery', chatWindowShort: 'abilChecks', }), advantageTracker: this.getOptionList({ none: null, normal: 'advantageTracker', short: 'advantageTrackerShort', shortest: 'advantageTrackerShortest', query: 'advantageTrackerQuery', }), savingThrows: this.getOptionList({ none: null, query: 'savingThrowsQuery', chatWindow: 'savingThrows', queryShort: 'savesQuery', chatWindowShort: 'saves', }), attacks: this.getOptionList({ none: null, individualActions: 'attacks', chatWindow: 'attacksMacro', }), statblock: this.booleanValidator, traits: this.getOptionList({ none: null, individualActions: 'traits', chatWindow: 'traitsMacro', }), actions: this.getOptionList({ none: null, individualActions: 'actions', chatWindow: 'actionsMacro', }), spells: this.booleanValidator, reactions: this.getOptionList({ none: null, individualActions: 'reactions', chatWindow: 'reactionsMacro', }), legendaryActions: this.getOptionList({ none: null, individualActions: 'legendaryActions', chatWindow: 'legendaryActionsMacro', chatWindowShort: 'legendaryA', }), lairActions: this.getOptionList({ none: null, chatWindow: 'lairActions', chatWindowShort: 'lairA', }), regionalEffects: this.getOptionList({ none: null, chatWindow: 'regionalEffects', chatWindowShort: 'regionalE', }), rests: this.booleanValidator, }, textSizes: { spellsTextSize: this.textSizeValidator, abilityChecksTextSize: this.textSizeValidator, savingThrowsTextSize: this.textSizeValidator, }, hide: { hideAttack: this.getHideOption('hide_attack'), hideDamage: this.getHideOption('hide_damage'), hideAbilityChecks: this.getHideOption('hide_ability_checks'), hideSavingThrows: this.getHideOption('hide_saving_throws'), hideSavingThrowDC: this.getHideOption('hide_saving_throw_dc'), hideSpellContent: this.getHideOption('hide_spell_content'), hideFreetext: this.getHideOption('hide_freetext'), hideSavingThrowFailure: this.getHideOption('hide_saving_throw_failure'), hideSavingThrowSuccess: this.getHideOption('hide_saving_throw_success'), hideRecharge: this.getHideOption('hide_recharge'), }, customSkills: this.stringValidator, }, advTrackerSettings: { showMarkers: this.booleanValidator, ignoreNpcs: this.booleanValidator, advantageMarker: this.statusMarkerValidator, disadvantageMarker: this.statusMarkerValidator, output: this.commandOutputValidator, }, sheetEnhancements: { rollHPOnDrop: this.booleanValidator, autoHD: this.booleanValidator, autoSpellSlots: this.booleanValidator, autoTraits: this.booleanValidator, }, genderPronouns: [ { matchPattern: this.regExpValidator, nominative: this.stringValidator, accusative: this.stringValidator, possessive: this.stringValidator, reflexive: this.stringValidator, }, ], defaultGenderIndex: this.integerValidator, variants: { rests: { longNoHpFullHd: this.booleanValidator, }, }, }; } static validStatusMarkers() { const markers = [ 'red', 'blue', 'green', 'brown', 'purple', 'pink', 'yellow', 'dead', 'skull', 'sleepy', 'half-heart', 'half-haze', 'interdiction', 'snail', 'lightning-helix', 'spanner', 'chained-heart', 'chemical-bolt', 'death-zone', 'drink-me', 'edge-crack', 'ninja-mask', 'stopwatch', 'fishing-net', 'overdrive', 'strong', 'fist', 'padlock', 'three-leaves', 'fluffy-wing', 'pummeled', 'tread', 'arrowed', 'aura', 'back-pain', 'black-flag', 'bleeding-eye', 'bolt-shield', 'broken-heart', 'cobweb', 'broken-shield', 'flying-flag', 'radioactive', 'trophy', 'broken-skull', 'frozen-orb', 'rolling-bomb', 'white-tower', 'grab', 'screaming', 'grenade', 'sentry-gun', 'all-for-one', 'angel-outfit', 'archery-target', ]; const obj = {}; for (let i = 0; i < markers.length; i++) { obj[markers[i]] = markers[i]; } return obj; } }; /***/ }, /* 16 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; const _ = __webpack_require__(2); const utils = __webpack_require__(7); const ShapedModule = __webpack_require__(13); const ShapedConfig = __webpack_require__(15); class MacroMaker { constructor(roll20) { if (!roll20) { throw new Error('Rol20 parameter is required for MacroMaker constructor'); } this.roll20 = roll20; this.sortKey = 'originalOrder'; } getAbilityMaker(character) { const self = this; return function abilityMaker(abilitySpec) { const ability = self.roll20.getOrCreateObj('ability', { characterid: character.id, name: abilitySpec.name }); ability.set({ action: abilitySpec.action, istokenaction: true }); // TODO configure this return abilitySpec.name; }; } } class AbilityDeleter extends MacroMaker { constructor(roll20) { super(roll20); this.sortKey = ''; } run(character) { const abilities = this.roll20.findObjs({ type: 'ability', characterid: character.id }); const deleted = _.map(abilities, obj => { const name = obj.get('name'); obj.remove(); return name; }); return `Deleted: ${_.isEmpty(deleted) ? 'None' : deleted.join(', ')}`; } } class RepeatingAbilityMaker extends MacroMaker { constructor(repeatingSection, abilityName, label, canMark, roll20) { super(roll20); this.repeatingSection = repeatingSection; this.abilityName = abilityName; this.label = label; this.canMark = canMark; } run(character, options) { const cache = options.getCache(character.id); cache[this.repeatingSection] = cache[this.repeatingSection] || this.roll20.getRepeatingSectionItemIdsByName(character.id, this.repeatingSection); const configured = _.chain(cache[this.repeatingSection]) .map((repeatingId, repeatingName) => { let repeatingAction = `%{${character.get('name')}|repeating_${this.repeatingSection}_${repeatingId}` + `_${this.abilityName}}`; if (this.canMark && options.mark) { repeatingAction += '\n!mark @{target|token_id}'; } return { name: utils.toTitleCase(repeatingName), action: repeatingAction }; }) .map(this.getAbilityMaker(character)) .value(); const addedText = _.isEmpty(configured) ? 'Not present for character' : configured.join(', '); return `${this.label}: ${addedText}`; } } class RollAbilityMaker extends MacroMaker { constructor(abilityName, newName, roll20) { super(roll20); this.abilityName = abilityName; this.newName = newName; } run(character) { return this.getAbilityMaker(character)({ name: this.newName, action: `%{${character.get('name')}|${this.abilityName}}`, }); } } class CommandAbilityMaker extends MacroMaker { constructor(command, options, newName, roll20) { super(roll20); this.command = command; this.options = options; this.newName = newName; } run(character) { return this.getAbilityMaker(character)({ name: this.newName, action: `!${this.command} ${utils.toOptionsString(this.options)}`, }); } } class MultiCommandAbilityMaker extends MacroMaker { constructor(commandSpecs, roll20) { super(roll20); this.commandSpecs = commandSpecs; } run(character) { const abilMaker = this.getAbilityMaker(character); return this.commandSpecs.map(cmdSpec => abilMaker({ name: cmdSpec.abilityName, action: `!${cmdSpec.command} ${utils.toOptionsString(cmdSpec.options)}`, }) ); } } class RepeatingSectionMacroMaker extends MacroMaker { constructor(abilityName, repeatingSection, macroName, roll20) { super(roll20); this.abilityName = abilityName; this.repeatingSection = repeatingSection; this.macroName = macroName; this.sortKey = 'originalOrder'; } run(character) { if (!_.isEmpty(this.roll20.getRepeatingSectionAttrs(character.id, this.repeatingSection))) { return this.getAbilityMaker(character)({ name: this.macroName, action: `%{${character.get('name')}|${this.abilityName}}`, }); } return `${this.macroName}: Not present for character`; } } function getRepeatingSectionAbilityLookup(sectionName, rollName, roll20) { return function repeatingSectionAbilityLookup(optionName, existingOptions) { const characterId = existingOptions.selected.character[0].id; const cache = existingOptions.getCache(characterId); cache[sectionName] = cache[sectionName] || roll20.getRepeatingSectionItemIdsByName(characterId, sectionName); const repeatingId = cache[sectionName][optionName.toLowerCase()]; if (repeatingId) { return new RollAbilityMaker(`repeating_${sectionName}_${repeatingId}_${rollName}`, utils.toTitleCase(optionName), roll20); } return undefined; }; } module.exports = class AbilityMaker extends ShapedModule { addCommands(commandProcessor) { const roll20 = this.roll20; this.staticAbilityOptions = { DELETE: new AbilityDeleter(roll20), advantageTracker: new MultiCommandAbilityMaker([ { command: 'shaped-at', options: ['advantage'], abilityName: 'Advantage' }, { command: 'shaped-at', options: ['disadvantage'], abilityName: 'Disadvantage' }, { command: 'shaped-at', options: ['normal'], abilityName: 'Normal' }, ], roll20), advantageTrackerShort: new MultiCommandAbilityMaker([ { command: 'shaped-at', options: ['advantage'], abilityName: 'Adv' }, { command: 'shaped-at', options: ['disadvantage'], abilityName: 'Dis' }, { command: 'shaped-at', options: ['normal'], abilityName: 'Normal' }, ], roll20), advantageTrackerShortest: new MultiCommandAbilityMaker([ { command: 'shaped-at', options: ['advantage'], abilityName: 'Adv' }, { command: 'shaped-at', options: ['disadvantage'], abilityName: 'Dis' }, ], roll20), advantageTrackerQuery: new CommandAbilityMaker('shaped-at', ['?{Roll Option|Normal,normal|w/ Advantage,advantage|w/ Disadvantage,disadvantage}'], '(dis)Adv Query', roll20), initiative: new RollAbilityMaker('shaped_initiative', 'Init', roll20), abilityChecks: new RollAbilityMaker('shaped_ability_checks', 'Ability Checks', roll20), abilityChecksQuery: new RollAbilityMaker('shaped_ability_checks_query', 'Ability Checks', roll20), abilChecks: new RollAbilityMaker('shaped_ability_checks', 'AbilChecks', roll20), abilChecksQuery: new RollAbilityMaker('shaped_ability_checks_query', 'AbilChecks', roll20), savingThrows: new RollAbilityMaker('shaped_saving_throw', 'Saving Throws', roll20), savingThrowsQuery: new RollAbilityMaker('shaped_saving_throw_query', 'Saving Throws', roll20), saves: new RollAbilityMaker('shaped_saving_throw', 'Saves', roll20), savesQuery: new RollAbilityMaker('shaped_saving_throw_query', 'Saves', roll20), rests: new CommandAbilityMaker('shaped-rest', ['?{Rest type|Short,short|Long,long}'], 'Rests', roll20), attacks: new RepeatingAbilityMaker('attack', 'attack', 'Attacks', true, roll20), attacksMacro: new RepeatingSectionMacroMaker('shaped_attacks', 'attack', 'Attacks', roll20), spells: new RepeatingSectionMacroMaker('shaped_spells', 'spell', 'Spells', roll20), statblock: new RollAbilityMaker('shaped_statblock', 'Statblock', roll20), traits: new RepeatingAbilityMaker('trait', 'trait', 'Traits', false, roll20), traitsMacro: new RepeatingSectionMacroMaker('shaped_traits', 'trait', 'Traits', roll20), actions: new RepeatingAbilityMaker('action', 'action', 'Actions', true, roll20), actionsMacro: new RepeatingSectionMacroMaker('shaped_actions', 'action', 'Actions', roll20), reactions: new RepeatingAbilityMaker('reaction', 'action', 'Reactions', false, roll20), reactionsMacro: new RepeatingSectionMacroMaker('shaped_reactions', 'reaction', 'Reactions', roll20), legendaryActions: new RepeatingAbilityMaker('legendaryaction', 'action', 'Legendary Actions', false, roll20), legendaryActionsMacro: new RepeatingSectionMacroMaker('shaped_legendaryactions', 'legendaryaction', 'Legendary Actions', roll20), legendaryA: new RepeatingSectionMacroMaker('shaped_legendaryactions', 'legendaryaction', 'LegendaryA', roll20), lairActions: new RepeatingSectionMacroMaker('shaped_lairactions', 'lairaction', 'Lair Actions', roll20), lairA: new RepeatingSectionMacroMaker('shaped_lairactions', 'lairaction', 'LairA', roll20), regionalEffects: new RepeatingSectionMacroMaker('shaped_regionaleffects', 'regionaleffect', 'Regional Effects', roll20), regionalE: new RepeatingSectionMacroMaker('shaped_regionaleffects', 'regionaleffect', 'RegionalE', roll20), }; return commandProcessor.addCommand('abilities', this.addAbility.bind(this), false) .withSelection({ character: { min: 1, max: Infinity, }, }) .optionLookup('abilities', this.staticAbilityOptions) .optionLookup('abilities', getRepeatingSectionAbilityLookup('spell', 'spell', this.roll20)) .optionLookup('abilities', getRepeatingSectionAbilityLookup('trait', 'trait', this.roll20)) .option('mark', ShapedConfig.booleanValidator); } addAbilitiesByName(abilities, character) { const caches = {}; const options = { getCache(key) { return (caches[key] = caches[key] || {}); }, }; // Slightly backwards way of doing this that ensures that we run the items in the order they are listed above // rather than the order they are passed in the parameter. Ideally we'd allow users to configure this but // since we haven't implemented that functionality the order is determine by the order in the saved configuration // object which is quite hard to control. _.chain(this.staticAbilityOptions) .pick((value, key) => _.contains(abilities, key)) .each(abilityMaker => abilityMaker.run(character, options)); } addAbility(options) { if (_.isEmpty(options.abilities)) { this.reportError('No abilities specified. ' + 'Take a look at the documentation for a list of ability options.'); return; } const messages = _.map(options.selected.character, (character) => { const operationMessages = _.chain(options.abilities) .sortBy('sortKey') .map(maker => maker.run(character, options)) .value(); if (_.isEmpty(operationMessages)) { return `<li>${character.get('name')}: Nothing to do</li>`; } let message; message = `<li>Configured the following abilities for character ${character.get('name')}:<ul><li>`; message += operationMessages.join('</li><li>'); message += '</li></ul></li>'; return message; }); this.reportPlayer('Ability Creation', `<ul>${messages.join('')}</ul>`); } }; /***/ }, /* 17 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; const _ = __webpack_require__(2); const utils = __webpack_require__(7); const ShapedModule = __webpack_require__(13); const ShapedConfig = __webpack_require__(15); class ConfigUi extends ShapedModule { addCommands(commandProcessor) { const menus = { atMenu: new AdvantageTrackerMenu(this.myState.config, ShapedConfig.configOptionsSpec), tsMenu: new TokensMenu(this.myState.config, ShapedConfig.configOptionsSpec), barMenu: new TokenBarsMenu(this.myState.config, ShapedConfig.configOptionsSpec), auraMenu: new TokenAurasMenu(this.myState.config, ShapedConfig.configOptionsSpec), ncMenu: new NewCharacterMenu(this.myState.config, ShapedConfig.configOptionsSpec), taMenu: new TokenActionsMenu(this.myState.config, ShapedConfig.configOptionsSpec), hideMenu: new HideMenu(this.myState.config, ShapedConfig.configOptionsSpec), hrMenu: new NewCharacterHouseruleMenu(this.myState.config, ShapedConfig.configOptionsSpec), savesMenu: new SavesMenu(this.myState.config, ShapedConfig.configOptionsSpec), fortitudeMenu: new CustomSaveTypeMenu(this.myState.config, ShapedConfig.configOptionsSpec, 'fortitude'), reflexMenu: new CustomSaveTypeMenu(this.myState.config, ShapedConfig.configOptionsSpec, 'reflex'), willMenu: new CustomSaveTypeMenu(this.myState.config, ShapedConfig.configOptionsSpec, 'will'), textMenu: new NewCharacterTextSizeMenu(this.myState.config, ShapedConfig.configOptionsSpec), varsMenu: new VariantsMenu(this.myState.config, ShapedConfig.configOptionsSpec), seMenu: new SheetEnhancementsMenu(this.myState.config, ShapedConfig.configOptionsSpec), }; _.each(menus, menu => this.logger.wrapModule(menu)); return commandProcessor.addCommand('config', this.process.bind(this), true) .options(ShapedConfig.configOptionsSpec) .optionLookup('menu', menus); } process(options) { // drop "menu" options utils.deepExtend(this.myState.config, _.omit(options, 'menu')); if (options.menu) { this.reportPlayer('Configuration', options.menu[0].getMenu()); } else { const menu = new MainMenu(this.myState.config, ShapedConfig.configOptionsSpec); this.reportPlayer('Configuration', menu.getMenu()); } } } module.exports = ConfigUi; ///////////////////////////////////////////////// // Menu Base ///////////////////////////////////////////////// class ConfigMenu { constructor(config, specRoot) { this.config = config; this.specRoot = specRoot; } makeToggleSetting(params) { let currentVal = utils.getObjectFromPath(this.config, params.path); if (params.spec) { currentVal = _.invert(params.spec)[currentVal] === 'true'; } params.command = `${!currentVal}${!_.isUndefined(params.menuCmd) ? ` --${params.menuCmd}` : ''}`; params.linkText = this.makeBoolText(currentVal); params.tooltip = 'click to toggle'; params.buttonColor = currentVal ? '#65c4bd' : '#f84545'; return this.makeOptionRow(params); } makeQuerySetting(params) { const currentVal = _.invert(params.spec)[utils.getObjectFromPath(this.config, params.path)]; const cmd = this.getQueryCommand(params.path, params.title, params.spec); params.command = `${cmd}${!_.isUndefined(params.menuCmd) ? ` --${params.menuCmd}` : ''}`; params.linkText = this.makeText(currentVal); params.tooltip = 'click to change'; params.buttonColor = '#02baf2'; return this.makeOptionRow(params); } makeInputSetting(params) { const currentVal = utils.getObjectFromPath(this.config, params.path); params.command = `?{${params.prompt}|${currentVal}}${!_.isUndefined(params.menuCmd) ? ` --${params.menuCmd}` : ''}`; params.linkText = currentVal || '[not set]'; params.tooltip = 'click to edit'; params.buttonColor = params.linkText === '[not set]' ? '#f84545' : '#02baf2'; return this.makeOptionRow(params); } // noinspection JSUnusedGlobalSymbols makeColorSetting(params) { const currentVal = utils.getObjectFromPath(this.config, params.path); params.command = `?{${params.prompt}|${currentVal}}${!_.isUndefined(params.menuCmd) ? ` --${params.menuCmd}` : ''}`; params.linkText = currentVal || '[not set]'; params.tooltip = 'click to edit'; params.buttonColor = params.linkText === '[not set]' ? '#02baf2' : currentVal; params.buttonTextColor = utils.getContrastYIQ(params.buttonColor); return this.makeOptionRow(params); } backToMainMenuButton() { return utils.buildHTML('a', '&lt;-- Main Menu', { href: '!shaped-config', style: 'text-align: center; margin: 5px 0 0 0; padding: 2px 2px ; border-radius: 10px; white-space: nowrap; ' + 'overflow: hidden; text-overflow: ellipsis; background-color: #02baf2; border-color: #c0c0c0;', }); } backToTokenOptions() { return utils.buildHTML('a', '&lt;-- Token Options', { href: '!shaped-config --tsMenu', style: 'text-align: center; margin: 5px 0 0 0; padding: 2px 2px ; border-radius: 10px; white-space: nowrap; ' + 'overflow: hidden; text-overflow: ellipsis; background-color: #02baf2; border-color: #c0c0c0;', }); } backToNewCharOptions() { return utils.buildHTML('a', '&lt;-- New Character Options', { href: '!shaped-config --ncMenu', style: 'text-align: center; margin: 5px 0 0 0; padding: 2px 2px ; border-radius: 10px; white-space: nowrap; ' + 'overflow: hidden; text-overflow: ellipsis; background-color: #02baf2; border-color: #c0c0c0;', }); } backToHouseRuleOptions() { return utils.buildHTML('a', '&lt;-- Houserule Options', { href: '!shaped-config --hrMenu', style: 'text-align: center; margin: 5px 0 0 0; padding: 2px 2px ; border-radius: 10px; white-space: nowrap; ' + 'overflow: hidden; text-overflow: ellipsis; background-color: #02baf2; border-color: #c0c0c0;', }); } backToSavesOptions() { return utils.buildHTML('a', '&lt;-- Saves Options', { href: '!shaped-config --savesMenu', style: 'text-align: center; margin: 5px 0 0 0; padding: 2px 2px ; border-radius: 10px; white-space: nowrap; ' + 'overflow: hidden; text-overflow: ellipsis; background-color: #02baf2; border-color: #c0c0c0;', }); } getQueryCommand(path, title, optionsSpec) { let currentVal = _.invert(optionsSpec)[utils.getObjectFromPath(this.config, path)]; const optionList = _.keys(optionsSpec); // Fix up if we've somehow ended up with an illegal value if (_.isUndefined(currentVal)) { currentVal = _.first(optionList); utils.deepExtend(this.config, utils.createObjectFromPath(path, optionsSpec[currentVal])); } // move the current option to the front of the list optionList.splice(optionList.indexOf(currentVal), 1); optionList.unshift(currentVal); return `?{${title}|${optionList.join('|')}}`; } makeOptionRow(params) { const col1 = utils.buildHTML('td', params.title); const col2 = utils.buildHTML('td', this.makeOptionButton(params), { style: 'text-align:right;' }); return utils.buildHTML('tr', col1 + col2, { style: 'border: 1px solid gray;' }); } makeOptionButton(params) { if (_.isUndefined(params.width)) { params.width = 80; } let css = `text-align: center; width: ${params.width}px; margin: 2px 0 -3px 0; ` + 'padding: 2px 2px ; border-radius: 10px; border-color: #c0c0c0;' + `white-space: nowrap; overflow: hidden; text-overflow: ellipsis; background-color: ${params.buttonColor};`; if (params.buttonTextColor) { css += `color: ${params.buttonTextColor}`; } return utils.buildHTML('a', params.linkText, { style: css, href: `!shaped-config --${params.path} ${params.command}`, }); } makeText(value) { return utils.buildHTML('span', value, { style: 'padding: 0 2px;' }); } makeBoolText(value) { return value === true ? utils.buildHTML('span', 'on', { style: 'padding: 0 2px;' }) : utils.buildHTML('span', 'off', { style: 'padding: 0 2px;' }); } makeThreeColOptionTable(options) { return utils .buildHTML('tr', [ { tag: 'td', innerHtml: [ { tag: 'table', innerHtml: [ { tag: 'tr', innerHtml: [{ tag: 'th', innerHtml: options.tableTitle, attrs: { colspan: 3 } }], }, { tag: 'tr', innerHtml: [ { tag: 'td', innerHtml: options.colTitles[0], }, { tag: 'td', innerHtml: options.colTitles[1], }, { tag: 'td', innerHtml: options.colTitles[2], }, ], attrs: { style: 'line-height: 1;' }, }, { tag: 'tr', innerHtml: [ { tag: 'td', innerHtml: options.buttons[0], }, { tag: 'td', innerHtml: options.buttons[1], }, { tag: 'td', innerHtml: options.buttons[2], }, ], }, ], attrs: { style: 'width: 100%; text-align: center;' }, }, ], attrs: { colspan: '2' }, }, ], { style: 'border: 1px solid gray;' }); } get logWrap() { return this.constructor.name; } toJSON() { return {}; } } ///////////////////////////////////////////////// // Menus ///////////////////////////////////////////////// class MainMenu extends ConfigMenu { getMenu() { const optionRows = this.makeOptionRow({ title: 'Advantage Tracker', path: 'atMenu', command: '', linkText: 'view --&gt;', buttonColor: '#02baf2', }) + this.makeOptionRow({ title: 'Token Defaults', path: 'tsMenu', command: '', linkText: 'view --&gt;', buttonColor: '#02baf2', }) + this.makeOptionRow({ title: 'New Characters', path: 'ncMenu', command: '', linkText: 'view --&gt;', buttonColor: '#02baf2', }) + this.makeOptionRow({ title: 'Char. Sheet Enhancements', path: 'seMenu', command: '', linkText: 'view --&gt;', buttonColor: '#02baf2', }) + this.makeOptionRow({ title: 'Houserules & Variants', path: 'varsMenu', command: '', linkText: 'view --&gt;', buttonColor: '#02baf2', }); const th = utils.buildHTML('th', 'Main Menu', { colspan: '2' }); const tr = utils.buildHTML('tr', th, { style: 'margin-top: 5px;' }); return utils.buildHTML('table', tr + optionRows, { style: 'width: 100%; font-size: 0.9em;' }); } } class AdvantageTrackerMenu extends ConfigMenu { getMenu() { const ats = 'advTrackerSettings'; const menu = 'atMenu'; const optionRows = this.makeQuerySetting({ path: `${ats}.output`, title: 'Output', menuCmd: menu, spec: this.specRoot.advTrackerSettings.output(), }) + this.makeToggleSetting({ path: `${ats}.showMarkers`, title: 'Show Markers', menuCmd: menu, }) + this.makeToggleSetting({ path: `${ats}.ignoreNpcs`, title: 'Ignore NPCs', menuCmd: menu, }) + this.makeQuerySetting({ path: `${ats}.advantageMarker`, title: 'Advantage Marker', menuCmd: menu, spec: this.specRoot.advTrackerSettings.advantageMarker(), }) + this.makeQuerySetting({ path: `${ats}.disadvantageMarker`, title: 'Disadvantage Marker', menuCmd: menu, spec: this.specRoot.advTrackerSettings.disadvantageMarker(), }); const th = utils.buildHTML('th', 'Advantage Tracker Options', { colspan: '2' }); const tr = utils.buildHTML('tr', th, { style: 'margin-top: 5px;' }); const table = utils.buildHTML('table', tr + optionRows, { style: 'width: 100%; font-size: 0.9em;' }); return table + this.backToMainMenuButton(); } } class TokensMenu extends ConfigMenu { getMenu() { // config) { // this.config = config; const ts = 'tokenSettings'; const menu = 'tsMenu'; const optionRows = this.makeToggleSetting({ path: `${ts}.number`, title: 'Numbered Tokens', menuCmd: menu, }) + this.makeToggleSetting({ path: `${ts}.showName`, title: 'Show Name Tag', menuCmd: menu, }) + this.makeToggleSetting({ path: `${ts}.showNameToPlayers`, title: 'Show Name to Players', menuCmd: menu, }) + this.makeInputSetting({ path: `${ts}.light.radius`, title: 'Light Radius', prompt: 'Light Radius (empty to unset)', menuCmd: menu, }) + this.makeInputSetting({ path: `${ts}.light.dimRadius`, title: 'Dim Radius', prompt: 'Light Dim Radius (empty to unset)', menuCmd: menu, }) + this.makeToggleSetting({ path: `${ts}.light.otherPlayers`, title: 'Other players see light', menuCmd: menu, }) + this.makeToggleSetting({ path: `${ts}.light.hasSight`, title: 'Has Sight', menuCmd: menu, }) + this.makeInputSetting({ path: `${ts}.light.angle`, title: 'Light Angle', prompt: 'Light Angle', menuCmd: menu, }) + this.makeInputSetting({ path: `${ts}.light.losAngle`, title: 'LOS Angle', prompt: 'LOS Angle', menuCmd: menu, }) + this.makeInputSetting({ path: `${ts}.light.multiplier`, title: 'Light Muliplier', prompt: 'Light Muliplier', menuCmd: menu, }) + this.makeOptionRow({ title: 'Token Bar Options', path: 'barMenu', command: '', linkText: 'view --&gt;', buttonColor: '#02baf2', }) + this.makeOptionRow({ title: 'Token Aura Options', path: 'auraMenu', command: '', linkText: 'view --&gt;', buttonColor: '#02baf2', }); const th = utils.buildHTML('th', 'Token Options', { colspan: '2' }); const tr = utils.buildHTML('tr', th, { style: 'margin-top: 5px;' }); const table = utils.buildHTML('table', tr + optionRows, { style: 'width: 100%; font-size: 0.9em;' }); return table + this.backToMainMenuButton(); } } class TokenBarsMenu extends ConfigMenu { getMenu() { const ts = 'tokenSettings'; const menu = 'barMenu'; let optionRows = ''; for (let i = 1; i <= 3; i++) { const currAttr = utils.getObjectFromPath(this.config, `${ts}.bar${i}.attribute`); const currAttrEmptyHint = currAttr || '[not set]'; const currMax = utils.getObjectFromPath(this.config, `${ts}.bar${i}.max`); const currLink = utils.getObjectFromPath(this.config, `${ts}.bar${i}.link`); const attBtn = this.makeOptionButton({ path: `${ts}.bar${i}.attribute`, linkText: this.makeText(currAttrEmptyHint), tooltip: 'click to edit', buttonColor: currAttrEmptyHint === '[not set]' ? '#f84545' : '#02baf2', width: 60, command: `?{Bar ${i} Attribute (empty to unset)|${currAttr}} --${menu}`, }); const maxBtn = this.makeOptionButton({ path: `${ts}.bar${i}.max`, linkText: this.makeBoolText(currMax), tooltip: 'click to toggle', buttonColor: currMax ? '#65c4bd' : '#f84545', width: 60, command: `${!currMax} --${menu}`, }); const linkBtn = this.makeOptionButton({ path: `${ts}.bar${i}.link`, linkText: this.makeBoolText(currLink), tooltip: 'click to togle', buttonColor: currLink ? '#65c4bd' : '#f84545', width: 60, command: `${!currLink} --${menu}`, }); optionRows += this.makeThreeColOptionTable({ tableTitle: `Bar ${i}`, colTitles: ['Attribute', 'Max', 'Link'], buttons: [attBtn, maxBtn, linkBtn], }); } for (let i = 1; i <= 3; i++) { optionRows += this.makeToggleSetting({ path: `${ts}.bar${i}.showPlayers`, title: `Bar ${i} Show Players`, menuCmd: 'barMenu', }); } const th = utils.buildHTML('th', 'Token Bar Options', { colspan: '2' }); const tr = utils.buildHTML('tr', th, { style: 'margin-top: 5px;' }); const table = utils.buildHTML('table', tr + optionRows, { style: 'width: 100%; font-size: 0.9em;' }); return table + this.backToTokenOptions(); } } class TokenAurasMenu extends ConfigMenu { getMenu() { const ts = 'tokenSettings'; const menu = 'auraMenu'; let optionRows = ''; for (let i = 1; i <= 2; i++) { const currRad = utils.getObjectFromPath(this.config, `${ts}.aura${i}.radius`); const currRadEmptyHint = currRad || '[not set]'; const currColor = utils.getObjectFromPath(this.config, `${ts}.aura${i}.color`); const currSquare = utils.getObjectFromPath(this.config, `${ts}.aura${i}.square`); const radBtn = this.makeOptionButton({ path: `${ts}.aura${i}.radius`, linkText: this.makeText(currRadEmptyHint), tooltip: 'click to edit', buttonColor: currRadEmptyHint === '[not set]' ? '#f84545' : '#02baf2', width: 60, command: `?{Aura ${i} Radius (empty to unset)|${currRad}} --${menu}`, }); const colorBtn = this.makeOptionButton({ path: `tokenSettings.aura${i}.color`, linkText: this.makeText(currColor), tooltip: 'click to edit', buttonColor: currColor, buttonTextColor: utils.getContrastYIQ(currColor), width: 60, command: `?{Aura ${i} Color (hex colors)|${currColor}} --${menu}`, }); const squareBtn = this.makeOptionButton({ path: `tokenSettings.aura${i}.square`, linkText: this.makeBoolText(currSquare), tooltip: 'click to toggle', buttonColor: currSquare ? '#65c4bd' : '#f84545', width: 60, command: `${!currSquare} --${menu}`, }); optionRows += this.makeThreeColOptionTable({ tableTitle: `Aura ${i}`, colTitles: ['Range', 'Color', 'Square'], buttons: [radBtn, colorBtn, squareBtn], }); } for (let i = 1; i <= 2; i++) { optionRows += this.makeToggleSetting({ path: `${ts}.showAura${i}ToPlayers`, title: `Aura ${i} Show Players`, menuCmd: 'auraMenu', }); } const th = utils.buildHTML('th', 'Token Aura Options', { colspan: '2' }); const tr = utils.buildHTML('tr', th, { style: 'margin-top: 5px;' }); const table = utils.buildHTML('table', tr + optionRows, { style: 'width: 100%; font-size: 0.9em;' }); return table + this.backToTokenOptions(); } } class NewCharacterMenu extends ConfigMenu { getMenu() { const menu = 'ncMenu'; const ncs = 'newCharSettings'; let optionRows = this.makeToggleSetting({ path: `${ncs}.applyToAll`, title: 'Apply to all new chars?', menuCmd: menu }); const spec = this.specRoot.newCharSettings; const currSheetOut = _.invert(spec.sheetOutput())[utils.getObjectFromPath(this.config, `${ncs}.sheetOutput`)]; const currDSaveOut = _.invert(spec.deathSaveOutput())[utils.getObjectFromPath(this.config, `${ncs}.deathSaveOutput`)]; const currInitOut = _.invert(spec.initiativeOutput())[utils.getObjectFromPath(this.config, `${ncs}.initiativeOutput`)]; const sheetBtn = this.makeOptionButton({ path: `${ncs}.sheetOutput`, linkText: this.makeText(currSheetOut), tooltip: 'click to change', buttonColor: '#02baf2', width: 60, command: `${this.getQueryCommand(`${ncs}.sheetOutput`, 'Sheet Output', spec.sheetOutput())}` + ` --${menu}`, }); const dSaveBtn = this.makeOptionButton({ path: `${ncs}.deathSaveOutput`, linkText: this.makeText(currDSaveOut), tooltip: 'click to change', buttonColor: '#02baf2', width: 60, command: `${this.getQueryCommand(`${ncs}.deathSaveOutput`, 'Death Save Output', spec.deathSaveOutput())}` + ` --${menu}`, }); const initBtn = this.makeOptionButton({ path: `${ncs}.initiativeOutput`, linkText: this.makeText(currInitOut), tooltip: 'click to change', buttonColor: '#02baf2', width: 60, command: `${this.getQueryCommand(`${ncs}.initiativeOutput`, 'Initiative Output', spec.initiativeOutput())}` + ` --${menu}`, }); optionRows += this.makeThreeColOptionTable({ tableTitle: 'Output', colTitles: ['Sheet', 'Death Save', 'Initiative'], buttons: [sheetBtn, dSaveBtn, initBtn], }); optionRows += this.makeToggleSetting({ path: `${ncs}.showNameOnRollTemplate`, title: 'Show Name on Roll Template', menuCmd: menu, spec: spec.showNameOnRollTemplate(), }) + this.makeQuerySetting({ path: `${ncs}.rollOptions`, title: 'Roll Options', menuCmd: menu, spec: spec.rollOptions(), }) + this.makeToggleSetting({ path: `${ncs}.autoRevertAdvantage`, title: 'Revert Advantage', menuCmd: menu, }) + this.makeQuerySetting({ path: `${ncs}.initiativeRoll`, title: 'Init Roll', menuCmd: menu, spec: spec.initiativeRoll(), }) + this.makeToggleSetting({ path: `${ncs}.initiativeToTracker`, title: 'Init To Tracker', menuCmd: menu, spec: spec.initiativeToTracker(), }) + this.makeToggleSetting({ path: `${ncs}.breakInitiativeTies`, title: 'Break Init Ties', menuCmd: menu, spec: spec.breakInitiativeTies(), }) + this.makeToggleSetting({ path: `${ncs}.showTargetAC`, title: 'Show Target AC', menuCmd: menu, spec: spec.showTargetAC(), }) + this.makeToggleSetting({ path: `${ncs}.showTargetName`, title: 'Show Target Name', menuCmd: menu, spec: spec.showTargetName(), }) + this.makeToggleSetting({ path: `${ncs}.autoAmmo`, title: 'Auto Use Ammo', menuCmd: menu, spec: spec.autoAmmo(), }) + this.makeQuerySetting({ path: `${ncs}.tab`, title: 'Default tab', menuCmd: menu, spec: spec.tab(), }) + this.makeOptionRow({ title: 'Default Token Actions', path: 'taMenu', command: '', linkText: 'view --&gt;', buttonColor: '#02baf2', }) + this.makeOptionRow({ title: 'Houserule Settings', path: 'hrMenu', command: '', linkText: 'view --&gt;', buttonColor: '#02baf2', }) + this.makeOptionRow({ title: 'Hide Settings', path: 'hideMenu', command: '', linkText: 'view --&gt;', buttonColor: '#02baf2', }) + this.makeOptionRow({ title: 'Text sizes', path: 'textMenu', command: '', linkText: 'view --&gt;', buttonColor: '#02baf2', }); const th = utils.buildHTML('th', 'New Character Sheets', { colspan: '2' }); const tr = utils.buildHTML('tr', th, { style: 'margin-top: 5px;' }); const table = utils.buildHTML('table', tr + optionRows, { style: 'width: 100%; font-size: 0.9em;' }); return table + this.backToMainMenuButton(); } } class NewCharacterHouseruleMenu extends ConfigMenu { getMenu() { const hr = 'newCharSettings.houserules'; const menu = 'hrMenu'; const optionRows = this.makeQuerySetting({ path: `${hr}.baseDC`, title: 'Base DC', prompt: 'Base DC', menuCmd: menu, spec: this.specRoot.newCharSettings.houserules.baseDC(), }) + this.makeQuerySetting({ path: `${hr}.mediumArmorMaxDex`, title: 'Medium Armor Max Dex', menuCmd: menu, spec: this.specRoot.newCharSettings.houserules.mediumArmorMaxDex(), }) + this.makeToggleSetting({ path: `${hr}.expertiseAsAdvantage`, title: 'Expertise as advantage', menuCmd: menu, spec: this.specRoot.newCharSettings.houserules.expertiseAsAdvantage(), }) + this.makeOptionRow({ title: 'Saving Throws', path: 'savesMenu', command: '', linkText: 'view --&gt;', buttonColor: '#02baf2', }); const th = utils.buildHTML('th', 'Houserule Settings', { colspan: '2' }); const tr = utils.buildHTML('tr', th, { style: 'margin-top: 5px;' }); const table = utils.buildHTML('table', tr + optionRows, { style: 'width: 100%; font-size: 0.9em;' }); return table + this.backToNewCharOptions(); } } class HideMenu extends ConfigMenu { getMenu() { const hide = 'newCharSettings.hide'; const menu = 'hideMenu'; const optionRows = _.functions(this.specRoot.newCharSettings.hide).reduce((result, functionName) => { const title = utils.toTitleCase( functionName.replace(/([a-z])([A-Z]+)/g, (match, lower, upper) => `${lower} ${upper.toLowerCase()}`)); result += this.makeToggleSetting({ path: `${hide}.${functionName}`, title, menuCmd: menu, spec: this.specRoot.newCharSettings.hide[functionName](), }); return result; }, ''); const th = utils.buildHTML('th', 'Hide Settings', { colspan: '2' }); const tr = utils.buildHTML('tr', th, { style: 'margin-top: 5px;' }); const table = utils.buildHTML('table', tr + optionRows, { style: 'width: 100%; font-size: 0.9em;' }); return table + this.backToNewCharOptions(); } } class SavesMenu extends ConfigMenu { getMenu() { const saves = 'newCharSettings.houserules.saves'; const menu = 'savesMenu'; const optionRows = this.makeToggleSetting({ path: `${saves}.savingThrowsHalfProf`, title: 'Half Proficiency Saves', menuCmd: menu, }) + this.makeToggleSetting({ path: `${saves}.useCustomSaves`, title: 'Use Custom Saves', menuCmd: menu, spec: this.specRoot.newCharSettings.houserules.saves.useCustomSaves(), }) + this.makeToggleSetting({ path: `${saves}.useAverageOfAbilities`, title: 'Use Average of Highest Abils', menuCmd: menu, spec: this.specRoot.newCharSettings.houserules.saves.useAverageOfAbilities(), }) + this.makeOptionRow({ title: 'Fortitude', path: 'fortitudeMenu', command: '', linkText: 'view --&gt;', buttonColor: '#02baf2', }) + this.makeOptionRow({ title: 'Reflex', path: 'reflexMenu', command: '', linkText: 'view --&gt;', buttonColor: '#02baf2', }) + this.makeOptionRow({ title: 'Will', path: 'willMenu', command: '', linkText: 'view --&gt;', buttonColor: '#02baf2', }); const th = utils.buildHTML('th', 'Houserule Settings', { colspan: '2' }); const tr = utils.buildHTML('tr', th, { style: 'margin-top: 5px;' }); const table = utils.buildHTML('table', tr + optionRows, { style: 'width: 100%; font-size: 0.9em;' }); return table + this.backToHouseRuleOptions(); } } class CustomSaveTypeMenu extends ConfigMenu { constructor(config, specRoot, saveName) { super(config, specRoot); this.saveName = saveName; } getMenu() { const saves = `newCharSettings.houserules.saves.${this.saveName}`; const menu = `${this.saveName}Menu`; const spec = this.specRoot.newCharSettings.houserules.saves[this.saveName]; const optionRows = ['Strength', 'Dexterity', 'Constitution', 'Intelligence', 'Wisdom', 'Charisma'] .reduce((result, attr) => { const propName = `${this.saveName}${attr}`; result += this.makeToggleSetting({ path: `${saves}.${propName}`, title: attr, menuCmd: menu, spec: spec[propName](), }); return result; }, ''); const th = utils.buildHTML('th', `${this.saveName} Saves`, { colspan: '2' }); const tr = utils.buildHTML('tr', th, { style: 'margin-top: 5px;' }); const table = utils.buildHTML('table', tr + optionRows, { style: 'width: 100%; font-size: 0.9em;' }); return table + this.backToSavesOptions(); } } class NewCharacterTextSizeMenu extends ConfigMenu { getMenu() { const textSizes = 'newCharSettings.textSizes'; const menu = 'textMenu'; const optionRows = this.makeQuerySetting({ path: `${textSizes}.spellsTextSize`, title: 'Spells', menuCmd: menu, spec: this.specRoot.newCharSettings.textSizes.spellsTextSize(), }) + this.makeQuerySetting({ path: `${textSizes}.abilityChecksSize`, title: 'Ability Checks', menuCmd: menu, spec: this.specRoot.newCharSettings.textSizes.abilityChecksTextSize(), }) + this.makeQuerySetting({ path: `${textSizes}.savingThrowsSize`, title: 'Saving Throws', menuCmd: menu, spec: this.specRoot.newCharSettings.textSizes.savingThrowsTextSize(), }); const th = utils.buildHTML('th', 'Text sizes', { colspan: '2' }); const tr = utils.buildHTML('tr', th, { style: 'margin-top: 5px;' }); const table = utils.buildHTML('table', tr + optionRows, { style: 'width: 100%; font-size: 0.9em;' }); return table + this.backToNewCharOptions(); } } class VariantsMenu extends ConfigMenu { getMenu() { const root = 'variants'; const menu = 'varsMenu'; const optionRows = this.makeToggleSetting({ path: `${root}.rests.longNoHpFullHd`, title: 'Long Rest: No HP, full HD', menuCmd: menu, }); const th = utils.buildHTML('th', 'Houserules & Variants', { colspan: '2' }); const tr = utils.buildHTML('tr', th, { style: 'margin-top: 5px;' }); const table = utils.buildHTML('table', tr + optionRows, { style: 'width: 100%; font-size: 0.9em;' }); return table + this.backToMainMenuButton(); } } class SheetEnhancementsMenu extends ConfigMenu { getMenu() { const root = 'sheetEnhancements'; const menu = 'seMenu'; const optionRows = this.makeToggleSetting({ path: `${root}.rollHPOnDrop`, title: 'Roll HP On Drop', menuCmd: menu, }) + this.makeToggleSetting({ path: `${root}.autoHD`, title: 'Process HD Automatically', menuCmd: menu, }) + this.makeToggleSetting({ path: `${root}.autoSpellSlots`, title: 'Process Spell Slots Automatically', menuCmd: menu, }) + this.makeToggleSetting({ path: `${root}.autoTraits`, title: 'Process Traits automatically', menuCmd: menu, }); const th = utils.buildHTML('th', 'Character Sheet Enhancements', { colspan: '2' }); const tr = utils.buildHTML('tr', th, { style: 'margin-top: 5px;' }); const table = utils.buildHTML('table', tr + optionRows, { style: 'width: 100%; font-size: 0.9em;' }); return table + this.backToMainMenuButton(); } } class TokenActionsMenu extends ConfigMenu { getMenu() { const root = 'newCharSettings.tokenActions'; const menu = 'taMenu'; const spec = this.specRoot.newCharSettings.tokenActions; const optionRows = this.makeQuerySetting({ path: `${root}.advantageTracker`, title: 'Advantage Tracker', menuCmd: menu, spec: spec.advantageTracker(), }) + this.makeToggleSetting({ path: `${root}.initiative`, title: 'Initiative', menuCmd: menu, }) + this.makeQuerySetting({ path: `${root}.abilityChecks`, title: 'Ability Checks', menuCmd: menu, spec: spec.abilityChecks(), }) + this.makeQuerySetting({ path: `${root}.savingThrows`, title: 'Saves', menuCmd: menu, spec: spec.savingThrows(), }) + this.makeToggleSetting({ path: `${root}.rests`, title: 'Rests', menuCmd: menu, }) + this.makeQuerySetting({ path: `${root}.attacks`, title: 'Attacks', menuCmd: menu, spec: spec.attacks(), }) + this.makeToggleSetting({ path: `${root}.spells`, title: 'Spells', menuCmd: menu, }) + this.makeToggleSetting({ path: `${root}.statblock`, title: 'Statblock', menuCmd: menu, }) + this.makeQuerySetting({ path: `${root}.traits`, title: 'Traits', menuCmd: menu, spec: spec.traits(), }) + this.makeQuerySetting({ path: `${root}.actions`, title: 'Actions', menuCmd: menu, spec: spec.actions(), }) + this.makeQuerySetting({ path: `${root}.reactions`, title: 'Reactions', menuCmd: menu, spec: spec.reactions(), }) + this.makeQuerySetting({ path: `${root}.legendaryActions`, title: 'Legendary Actions', menuCmd: menu, spec: spec.legendaryActions(), }) + this.makeQuerySetting({ path: `${root}.lairActions`, title: 'Lair Actions', menuCmd: menu, spec: spec.lairActions(), }) + this.makeQuerySetting({ path: `${root}.regionalEffects`, title: 'Regional Effects', menuCmd: menu, spec: spec.regionalEffects(), }); const th = utils.buildHTML('th', 'Default Token Actions', { colspan: '2' }); const tr = utils.buildHTML('tr', th, { style: 'margin-top: 5px;' }); const table = utils.buildHTML('table', tr + optionRows, { style: 'width: 100%; font-size: 0.9em;' }); return table + this.backToMainMenuButton(); } } /***/ }, /* 18 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; const _ = __webpack_require__(2); const utils = __webpack_require__(7); const ShapedModule = __webpack_require__(13); const ShapedConfig = __webpack_require__(15); const rollOptions = { normal: { rollSetting: '{{ignore=[[0', message: 'normally', rollInfo: '', shaped_d20: '', }, advantage: { rollSetting: 'adv {{ignore=[[0', message: 'with advantage', rollInfo: '{{advantage=1}}', shaped_d20: '2d20@{d20_mod}kh1', }, disadvantage: { rollSetting: 'dis {{ignore=[[0', message: 'with disadvantage', rollInfo: '{{disadvantage=1}}', shaped_d20: '2d20@{d20_mod}kl1', }, roll2: { rollSetting: '{{roll2=[[d20@{d20_mod}', message: 'two dice', rollInfo: '', shaped_d20: '', }, }; class AdvantageTracker extends ShapedModule { addCommands(commandProcessor) { return commandProcessor.addCommand('at', this.process.bind(this), false) .option('advantage', ShapedConfig.booleanValidator) .option('disadvantage', ShapedConfig.booleanValidator) .option('normal', ShapedConfig.booleanValidator) .option('revert', ShapedConfig.booleanValidator) .option('persist', ShapedConfig.booleanValidator) .option('id', ShapedConfig.getCharacterValidator(this.roll20), false) .withSelection({ character: { min: 0, max: Infinity, }, }); } process(options) { let type = undefined; // const at = new AdvantageTracker(this.logger, this.myState, this.roll20); if (!_.isUndefined(options.id)) { // if an ID is passed, overwrite any selection, and only process for the passed charId options.selected.character = [options.id]; } if (_.isEmpty(options.selected.character)) { this.reportError('Advantage Tracker was called, but no token was selected, and no character id was passed.'); } else { if (options.normal) { type = 'normal'; } else if (options.advantage) { type = 'advantage'; } else if (options.disadvantage) { type = 'disadvantage'; } if (!_.isUndefined(type)) { this.setRollOption(type, options.selected.character); } if (options.revert) { this.setAutoRevert(true, options.selected.character); } else if (options.persist) { this.setAutoRevert(false, options.selected.character); } } } handleRollOptionChange(msg) { const char = []; char.push(msg.get('_characterid')); const br = this.buildResources(_.uniq(_.union(char))); if (!_.isEmpty(br)) { this.setStatusMarkers(br[0].tokens, msg.get('current') === rollOptions.advantage.rollSetting, msg.get('current') === rollOptions.disadvantage.rollSetting); switch (msg.get('current')) { case rollOptions.normal.rollSetting: this.sendChatNotification(br[0], 'normal'); break; case rollOptions.advantage.rollSetting: this.sendChatNotification(br[0], 'advantage'); break; case rollOptions.disadvantage.rollSetting: this.sendChatNotification(br[0], 'disadvantage'); break; default: break; } } } handleTokenChange(token) { this.logger.debug('AT: Updating New Token'); if (this.shouldShowMarkers() && token.get('represents') !== '') { const character = this.roll20.getObj('character', token.get('represents')); const setting = this.roll20.getAttrByName(character.id, 'roll_setting'); if (this.shouldIgnoreNpcs()) { if (this.roll20.getAttrByName(character.id, 'is_npc') === '1') { return; } } token.set(`status_${this.disadvantageMarker()}`, setting === rollOptions.disadvantage.rollSetting); token.set(`status_${this.advantageMarker()}`, setting === rollOptions.advantage.rollSetting); } } buildResources(characterIds) { let res = _.chain(characterIds) .map((charId) => this.roll20.getObj('character', charId)) .reject(_.isUndefined) .map((char) => ({ character: char, tokens: this.roll20.filterObjs((obj) => obj.get('_type') === 'graphic' && char.id === obj.get('represents')), })) .value(); if (this.shouldIgnoreNpcs()) { res = _.chain(res) .filter((c) => { const isNpc = this.roll20.getAttrByName(c.character.id, 'is_npc'); return isNpc && parseInt(isNpc, 10) === 0; }) .value(); } return res; } setStatusMarkers(tokens, showAdvantage, showDisadvantage) { if (this.shouldShowMarkers()) { _.each(tokens, (token) => { token.set(`status_${this.advantageMarker()}`, showAdvantage); token.set(`status_${this.disadvantageMarker()}`, showDisadvantage); }); } } setAutoRevert(value, selectedChars) { const resources = this.buildResources(_.chain(selectedChars).map(c => c.get('_id')).value()); _.each(resources, (resource) => { const charId = resource.character.get('_id'); this.roll20.setAttrByName(charId, 'auto_revert_advantage', value ? 'on' : 0); }); } setRollOption(type, selectedChars) { const resources = this.buildResources(_.chain(selectedChars).map(c => c.get('_id')).value()); _.each(resources, (resource) => { const charId = resource.character.get('_id'); this.setStatusMarkers(resource.tokens, type === 'advantage', type === 'disadvantage'); if (this.roll20.getAttrByName(charId, 'roll_setting') === rollOptions[type].rollSetting) { return; } this.roll20.setAttrByName(charId, 'roll_setting', rollOptions[type].rollSetting); this.roll20.setAttrByName(charId, 'roll_info', rollOptions[type].rollInfo); this.roll20.setAttrByName(charId, 'shaped_d20', rollOptions[type].shaped_d20); this.sendChatNotification(resource, type); }); } sendChatNotification(resource, type) { if (this.outputOption() !== 'silent') { let msg = ` &{template:5e-shaped} {{character_name=${resource.character.get('name')}}} ` + `@{${resource.character.get('name')}|show_character_name} {{title=${utils.toTitleCase(type)}}} ` + `{{text_top=${resource.character.get('name')} is rolling ${rollOptions[type].message}!}}`; if (this.outputOption() === 'whisper') { msg = `/w gm ${msg}`; } this.roll20.sendChat('Shaped AdvantageTracker', msg); } } outputOption() { return this.myState.config.advTrackerSettings.output; } shouldShowMarkers() { return this.myState.config.advTrackerSettings.showMarkers; } shouldIgnoreNpcs() { return this.myState.config.advTrackerSettings.ignoreNpcs; } advantageMarker() { return this.myState.config.advTrackerSettings.advantageMarker; } disadvantageMarker() { return this.myState.config.advTrackerSettings.disadvantageMarker; } } module.exports = AdvantageTracker; /***/ }, /* 19 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; const _ = __webpack_require__(2); const ShapedModule = __webpack_require__(13); const ShapedConfig = __webpack_require__(15); class RestManager extends ShapedModule { addCommands(commandProcessor) { return commandProcessor.addCommand('rest', this.handleRest.bind(this), false) .option('long', ShapedConfig.booleanValidator) .option('short', ShapedConfig.booleanValidator) .option('id', ShapedConfig.getCharacterValidator(this.roll20), false) .withSelection({ character: { min: 0, max: Infinity, }, }); } handleRest(options) { let chars = options.selected.character; if (!_.isUndefined(options.id)) { // if an ID is passed, overwrite any selection, and only process for the passed charId // NB this id will have been hydrated into a character object by the option processing so it's // already an object. The name should really change but it's baked into the sheet now so it's // too much hassle to change. chars = [options.id]; } if (options.long) { // handle long rest this.doLongRest(chars); } else if (options.short) { // handle short rest this.doShortRest(chars); } else { this.reportError('please specify long (!shaped-rest --long) or short (!shaped-rest --short) rest'); } } /** * Performs all of the short rest actions for the specified character * @param {Object[]} selectedChars - The characters to perform short rest actions on */ doShortRest(selectedChars) { _.each(selectedChars, (currentChar) => { const charId = currentChar.id; const charName = currentChar.get('name'); this.logger.debug(`Processing short rest for ${charName}:`); const traits = this.rechargeTraits(charId, 'short'); const msg = this.buildRestMessage('Short Rest', charName, charId, traits); this.roll20.sendChat(`character|${charId}`, msg); }); } /** * Performs all of the long rest actions for the specified character - including short rest actions * @param {Object[]} selectedChars - The characters to perform long rest actions on */ doLongRest(selectedChars) { _.each(selectedChars, (currentChar) => { const charId = currentChar.id; const charName = currentChar.get('name'); let healed = 0; this.logger.debug(`Processing long rest for ${charName}:`); let traits = this.rechargeTraits(charId, 'short'); traits = traits.concat(this.rechargeTraits(charId, 'long')); if (!this.myState.config.variants.rests.longNoHpFullHd) { healed = this.resetHP(currentChar); } const hd = this.regainHitDie(charId); const slots = this.regainSpellSlots(charId); const exhaus = this.reduceExhaustion(charId); const msg = this.buildRestMessage('Long Rest', charName, charId, traits, healed, hd, slots, exhaus); this.roll20.sendChat(`character|${charId}`, msg); }); } /** * Builds the rest message using the sheet's roll template to report the results of a rest * @param {string} restType - The type of rest performed; either 'Long Rest' or 'Short Rest' * @param {string} charName - The name of the character * @param {string} charId - The Roll20 character ID * @param {Object[]} traitNames - An array of the trait names that have been recharged * @param {int} healed - The number of HP healed * @param {Object[]} hdRegained - Array of objects each representing a die type and the number regained * @param {boolean} spellSlots - Whether or not spell slots were recharged * @param {boolean} exhaustion - Whether or not a level of exhaustoin was removed */ buildRestMessage(restType, charName, charId, traitNames, healed, hdRegained, spellSlots, exhaustion) { let msg = `&{template:5e-shaped} {{title=${restType}}} {{character_name=${charName}}}`; if (this.roll20.getAttrByName(charId, 'show_character_name') === '@{show_character_name_yes}') { msg += '{{show_character_name=1}}'; } if (hdRegained) { _.each(hdRegained, hd => { if (hd.quant > 0) { msg += `{{Hit Die Regained (${hd.die})=${hd.quant}}}`; } }); } if (traitNames) { msg += `{{Traits Recharged=${traitNames.join(', ')}}}`; } if (healed > 0) { msg += `{{heal=[[${healed}]]}}`; } if (spellSlots) { msg += '{{text_center=Spell Slots Regained}}'; } if (exhaustion) { msg += '{{text_top=Removed 1 Level Of Exhaustion}}'; } return msg; } /** * Recharges all of the repeating 'traits' section items that have a 'recharge' defined * @param {string} charId - the Roll20 character ID * @param {string} restType - the type of rest being performed; either 'Short Rest' or 'Long Rest' * @returns {Array} - An array of the trait names that were recharged */ rechargeTraits(charId, restType) { const traitNames = []; _.chain(this.roll20.findObjs({ type: 'attribute', characterid: charId })) .map(attribute => (attribute.get('name').match(/^repeating_trait_([^_]+)_recharge$/) || [])[1]) .reject(_.isUndefined) .uniq() .each(attId => { const traitPre = `repeating_trait_${attId}`; const rechargeAtt = this.roll20.getAttrByName(charId, `${traitPre}_recharge`); if (rechargeAtt.toLowerCase().indexOf(restType) !== -1) { const attName = this.roll20.getAttrByName(charId, `${traitPre}_name`); this.logger.debug(`Recharging '${attName}'`); traitNames.push(attName); const max = this.roll20.getAttrByName(charId, `${traitPre}_uses`, 'max'); if (max === undefined) { this.logger.error(`Tried to recharge the trait '${attName}' for character with id ${charId}, ` + 'but there were no uses defined.'); } else { this.roll20.setAttrByName(charId, `${traitPre}_uses`, max); } } }); return traitNames; } /** * Resets the HP of the specified character to its maximum value * @param {Object} character - the Roll20 character * @returns {int} - the number of HP that were healed */ resetHP(character) { const charId = character.id; this.logger.debug('Resetting HP to max'); const max = parseInt(this.roll20.getAttrByName(charId, 'HP', 'max'), 10); if (_.isNaN(max)) { this.reportError(`Can't recharge HP for character ${character.get('name')} because max HP is not set`); return 0; } const current = parseInt(this.roll20.getAttrByName(charId, 'HP', 'current') || 0, 10); this.roll20.setAttrByName(charId, 'HP', max); return max - current; } /** * Adds Hit die to the specified character based on PHB rules * @param {string} charId - the Roll20 character ID * @returns {Array} - Array of objects each representing a die type and the number regained */ regainHitDie(charId) { const hitDieRegained = []; this.logger.debug('Regaining Hit Die'); _.chain(this.roll20.findObjs({ type: 'attribute', characterid: charId })) .filter(attribute => (attribute.get('name').match(/^hd_d\d{1,2}$/))) .uniq() .each(hdAttr => { const max = parseInt(hdAttr.get('max'), 10); if (max > 0) { const oldCurrent = parseInt(hdAttr.get('current') || 0, 10); let newCurrent = oldCurrent; let regained = max === 1 ? 1 : Math.floor(max / 2); if (this.myState.config.variants.rests.longNoHpFullHd) { regained = max - oldCurrent; } newCurrent += regained; newCurrent = newCurrent > max ? max : newCurrent; this.roll20.setAttrByName(charId, hdAttr.get('name'), newCurrent); hitDieRegained.push({ die: hdAttr.get('name').replace(/hd_/, ''), quant: newCurrent - oldCurrent, }); } }); return hitDieRegained; } /** * Resets all (non warlock) spell slots of the specified character to their maximum values * @param {string} charId - the Roll20 character ID * @returns {boolean} - true if any spell slots were recharged; false otherwise */ regainSpellSlots(charId) { let slotsFound = false; this.logger.debug('Regaining Spell Slots'); _.chain(this.roll20.findObjs({ type: 'attribute', characterid: charId })) .filter(attribute => (attribute.get('name').match(/^spell_slots_l\d$/))) .uniq() .each(slotAttr => { const max = parseInt(slotAttr.get('max'), 10); if (max > 0) { this.roll20.setAttrByName(charId, slotAttr.get('name'), max); slotsFound = true; } }); return slotsFound; } /** * Reduces the specified character's level of exhaustion by 1 * @param {string} charId - the Roll20 character ID * @returns {boolean} - true if a level of exhaustion was reduced; false otherwise */ reduceExhaustion(charId) { this.logger.debug('Reducing Exhaustion'); const currentLevel = parseInt(this.roll20.getAttrByName(charId, 'exhaustion_level'), 10); if (currentLevel > 0) { this.roll20.setAttrByName(charId, 'exhaustion_level', currentLevel - 1); return true; } return false; } } module.exports = RestManager; /***/ }, /* 20 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; const _ = __webpack_require__(2); const ShapedModule = __webpack_require__(13); class TraitManager extends ShapedModule { addCommands(commandProcessor) { // no commands for this module return commandProcessor; } /** * Handles the click event of a trait when 'autoTraits' is true * Consumes one use of the clicked trait * @param {object} options - The message options */ handleTraitClick(options) { const traitId = _.chain(this.roll20.findObjs({ type: 'attribute', characterid: options.character.id })) .map(attribute => (attribute.get('name').match(/^repeating_trait_([^_]+)_name$/) || [])[1]) .reject(_.isUndefined) .uniq() .find(attId => this.roll20.getAttrByName(options.character.id, `repeating_trait_${attId}_name`) === options.title) .value(); const usesAttr = this.roll20.getAttrObjectByName(options.character.id, `repeating_trait_${traitId}_uses`); if (usesAttr) { if (usesAttr.get('current') > 0) { usesAttr.set('current', parseInt(usesAttr.get('current'), 10) - 1); } else { this.reportPublic('Trait Police', `${options.characterName} can't use ${options.title} because ` + 'they don\'t have any uses left.'); } } } } module.exports = TraitManager; /***/ }, /* 21 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; const _ = __webpack_require__(2); const ShapedModule = __webpack_require__(13); class AmmoManager extends ShapedModule { addCommands(commandProcessor) { return commandProcessor; } consumeAmmo(options, msg) { const ammoAttr = _.chain(this.roll20.findObjs({ type: 'attribute', characterid: options.character.id })) .filter(attribute => attribute.get('name').indexOf('repeating_ammo') === 0) .groupBy(attribute => attribute.get('name').replace(/(repeating_ammo_[^_]+).*/, '$1')) .find(attributeList => _.find(attributeList, attribute => attribute.get('name').match(/.*name$/) && attribute.get('current') === options.ammoName) ) .find(attribute => attribute.get('name').match(/.*qty$/)) .value(); if (!ammoAttr) { this.logger.error('No ammo attribute found corresponding to name $$$', options.ammoName); return; } let ammoUsed = 1; if (options.ammo) { const rollRef = options.ammo.match(/\$\[\[(\d+)\]\]/); if (rollRef) { const rollExpr = msg.inlinerolls[rollRef[1]].expression; const match = rollExpr.match(/\d+-(\d+)/); if (match) { ammoUsed = match[1]; } } } const val = parseInt(ammoAttr.get('current'), 10) || 0; ammoAttr.set('current', Math.max(0, val - ammoUsed)); } } module.exports = AmmoManager; /***/ }, /* 22 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; const _ = __webpack_require__(2); function getRenameMapper(newName, upperCaseValue) { return function renameMapper(key, value, output) { output[newName] = upperCaseValue && value ? value.toUpperCase() : value; }; } function upperCaseMapper(key, value, output) { output[key] = value ? value.toUpperCase() : value; } function identityMapper(key, value, output) { output[key] = value; } function booleanMapper(key, value, output) { if (value) { output[key] = 'Yes'; } } function durationMapper(key, value, output, spellObj) { let newDuration = spellObj.concentration ? 'CONCENTRATION_' : ''; newDuration += value.toUpperCase().replace(/\s/g, '_'); output[key] = newDuration; } function spellLevelMapper(key, value, output) { let spellLevel; if (value === 0) { spellLevel = 'CANTRIP'; } else { switch (value % 10) { case 1: spellLevel = `${value}ST_LEVEL`; break; case 2: spellLevel = `${value}ND_LEVEL`; break; case 3: spellLevel = `${value}RD_LEVEL`; break; default: spellLevel = `${value}TH_LEVEL`; break; } } output.spell_level = spellLevel; } function camelCaseFixMapper(key, value, output) { const newKey = key.replace(/[A-Z]/g, letter => `_${letter.toLowerCase()}`); output[newKey] = value; } function castingStatMapper(key, value, output) { if (value) { output.add_casting_modifier = 'Yes'; } } function castingTimeMapper(key, value, output) { output.casting_time = value && value.toUpperCase().replace(/\s/g, '_'); } function secondaryCastingStatMapper(key, value, output) { if (value) { output.add_second_casting_modifier = 'Yes'; } } function componentMapper(key, value, output) { const components = _.chain(value) .omit('materialCost') .map((propValue, propName) => { if (propName !== 'materialMaterial') { return propName.toUpperCase().slice(0, 1); } output.materials = propValue; return null; }) .compact() .value() .join('_'); if (components) { output.components = `COMPONENTS_${components}`; } } const saveAttackMappings = { ability: getRenameMapper('saving_throw_vs_ability', true), type: identityMapper, damage: identityMapper, damageBonus: camelCaseFixMapper, damageType: camelCaseFixMapper, saveSuccess: getRenameMapper('saving_throw_success'), saveFailure: getRenameMapper('saving_throw_failure'), higherLevelDice: camelCaseFixMapper, higherLevelDie: camelCaseFixMapper, secondaryDamage: getRenameMapper('second_damage'), secondaryDamageBonus: getRenameMapper('second_damage_bonus'), secondaryDamageType: getRenameMapper('second_damage_type'), higherLevelSecondaryDice: getRenameMapper('second_higher_level_dice'), higherLevelSecondaryDie: getRenameMapper('second_higher_level_die'), condition: getRenameMapper('saving_throw_condition'), castingStat: castingStatMapper, secondaryCastingStat: secondaryCastingStatMapper, }; function getObjectMapper(mappings) { return function objectMapper(key, value, output) { _.each(value, (propVal, propName) => { const mapper = mappings[propName]; if (!mapper) { throw new Error('Unrecognised property when attempting to convert to srd format: ' + `[${propName}] ${JSON.stringify(output)}`); } mapper(propName, propVal, output, value); }); }; } const spellMapper = getObjectMapper({ name: identityMapper, duration: durationMapper, level: spellLevelMapper, school: upperCaseMapper, emote: identityMapper, range: identityMapper, castingTime: castingTimeMapper, target: identityMapper, description(key, value, output) { output.content = value + (output.content ? `\n${output.content}` : ''); }, higherLevel(key, value, output) { output.content = output.content ? `${output.content}\n` : ''; output.content += value; }, ritual: booleanMapper, concentration: booleanMapper, save: getObjectMapper(saveAttackMappings), attack: getObjectMapper(saveAttackMappings), damage: getObjectMapper(saveAttackMappings), heal: getObjectMapper({ amount: getRenameMapper('heal'), castingStat: castingStatMapper, higherLevelDice: camelCaseFixMapper, higherLevelDie: camelCaseFixMapper, higherLevelAmount: getRenameMapper('higher_level_heal'), bonus: getRenameMapper('heal_bonus'), }), components: componentMapper, prepared(key, value, output) { if (value) { output.is_prepared = 'on'; } }, classes: _.noop, aoe: _.noop, source: _.noop, effects: _.noop, domains: _.noop, oaths: _.noop, circles: _.noop, patrons: _.noop, }); const monsterMapper = getObjectMapper({ name: getRenameMapper('character_name'), size: identityMapper, type: identityMapper, alignment: identityMapper, AC: getRenameMapper('ac_srd'), HP: getRenameMapper('hp_srd'), speed: getRenameMapper('npc_speed'), strength: identityMapper, dexterity: identityMapper, constitution: identityMapper, intelligence: identityMapper, wisdom: identityMapper, charisma: identityMapper, skills: getRenameMapper('skills_srd'), spells(key, value, output) { const splitSpells = _.partition(value, _.isObject); if (!_.isEmpty(splitSpells[1])) { output.spells_srd = splitSpells[1].join(', '); } if (!_.isEmpty(splitSpells[0])) { output.spells = splitSpells[0]; _.each(output.spells, spell => (spell.prepared = true)); } }, savingThrows: getRenameMapper('saving_throws_srd'), damageResistances: getRenameMapper('damage_resistances'), damageImmunities: getRenameMapper('damage_immunities'), conditionImmunities: getRenameMapper('condition_immunities'), damageVulnerabilities: getRenameMapper('damage_vulnerabilities'), senses: identityMapper, languages: identityMapper, challenge: identityMapper, traits: identityMapper, actions: identityMapper, reactions: identityMapper, regionalEffects: identityMapper, regionalEffectsFade: identityMapper, legendaryPoints: identityMapper, legendaryActions: identityMapper, lairActions: identityMapper, }); const pronounTokens = { '{{GENDER_PRONOUN_HE_SHE}}': 'nominative', '{{GENDER_PRONOUN_HIM_HER}}': 'accusative', '{{GENDER_PRONOUN_HIS_HER}}': 'possessive', '{{GENDER_PRONOUN_HIMSELF_HERSELF}}': 'reflexive', }; module.exports = { convertMonster(npcObject) { const output = {}; monsterMapper(null, npcObject, output); const actionTraitTemplate = _.template('**<%=data.name%>' + '<% if(data.recharge) { print(" (" + data.recharge + ")") } %>**: <%=data.text%>', { variable: 'data' }); const legendaryTemplate = _.template('**<%=data.name%>' + '<% if(data.cost && data.cost > 1){ print(" (Costs " + data.cost + " actions)") }%>**: <%=data.text%>', { variable: 'data' }); function lairRegionalTemplate(item) { return `**${item}`; } const simpleSectionTemplate = _.template('<%=data.title%>\n<% print(data.items.join("\\n")); %>', { variable: 'data' }); const legendarySectionTemplate = _.template('<%=data.title%>\n' + 'The <%=data.name%> can take <%=data.legendaryPoints%> legendary actions, choosing from the options below. ' + 'It can take only one legendary action at a time and only at the end of another creature\'s turn. ' + 'The <%=data.name%> regains spent legendary actions at the start of its turn.\n' + '<% print(data.items.join("\\n")) %>', { variable: 'data' }); const regionalSectionTemplate = _.template('<%=data.title%>\n<% print(data.items.join("\\n")); %>\n' + '**<%=data.regionalEffectsFade%>', { variable: 'data' }); const srdContentSections = [ { prop: 'traits', itemTemplate: actionTraitTemplate, sectionTemplate: simpleSectionTemplate }, { prop: 'actions', itemTemplate: actionTraitTemplate, sectionTemplate: simpleSectionTemplate }, { prop: 'reactions', itemTemplate: actionTraitTemplate, sectionTemplate: simpleSectionTemplate }, { prop: 'legendaryActions', itemTemplate: legendaryTemplate, sectionTemplate: legendarySectionTemplate }, { prop: 'lairActions', itemTemplate: lairRegionalTemplate, sectionTemplate: simpleSectionTemplate }, { prop: 'regionalEffects', itemTemplate: lairRegionalTemplate, sectionTemplate: regionalSectionTemplate }, ]; function makeDataObject(propertyName, itemList) { return { title: propertyName.replace(/([A-Z])/g, ' $1').replace(/^[a-z]/, letter => letter.toUpperCase()), name: output.character_name, legendaryPoints: output.legendaryPoints, regionalEffectsFade: output.regionalEffectsFade, items: itemList, }; } output.is_npc = 1; output.edit_mode = 'off'; output.content_srd = _.chain(srdContentSections) .map(sectionSpec => { const items = output[sectionSpec.prop]; delete output[sectionSpec.prop]; return _.map(items, sectionSpec.itemTemplate); }) .map((sectionItems, sectionIndex) => { const sectionSpec = srdContentSections[sectionIndex]; if (!_.isEmpty(sectionItems)) { return sectionSpec.sectionTemplate(makeDataObject(sectionSpec.prop, sectionItems)); } return null; }) .compact() .value() .join('\n'); delete output.legendaryPoints; return output; }, convertSpells(spellObjects, pronounInfo) { return _.map(spellObjects, spellObject => { const converted = {}; spellMapper(null, spellObject, converted); if (converted.emote) { _.each(pronounTokens, (pronounType, token) => { const replacement = pronounInfo[pronounType]; converted.emote = converted.emote.replace(new RegExp(token, 'g'), replacement); }); } return converted; }); }, }; /***/ }, /* 23 */ /***/ function(module, exports) { function sanitise(statblock, logger) { 'use strict'; logger.debug('Pre-sanitise: $$$', statblock); statblock = statblock .replace(/\s+([\.,;:])/g, '$1') .replace(/\n+/g, '#') .replace(/–/g, '-') .replace(/−/g, '-') // Watch out: this and the line above containing funny unicode versions of '-' .replace(/<br[^>]*>/g, '#') .replace(/#+/g, '#') .replace(/\s*#\s*/g, '#') .replace(/(<([^>]+)>)/gi, '') .replace(/legendary actions/gi, 'Legendary Actions') .replace(/(\S)\sACTIONS/, '$1#ACTIONS') .replace(/#(?=[a-z]|DC)/g, ' ') .replace(/\s+/g, ' ') .replace(/#Hit:/gi, 'Hit:') .replace(/Hit:#/gi, 'Hit: ') .replace(/#Each /gi, 'Each ') .replace(/#On a successful save/gi, 'On a successful save') .replace(/DC#(\d+)/g, 'DC $1') .replace('LanguagesChallenge', 'Languages -\nChallenge') .replace('\' Speed', 'Speed') .replace(/(\w+) s([\s\.,])/g, '$1s$2') .replace(/#Medium or/gi, ' Medium or') .replace(/take#(\d+)/gi, 'take $1') .replace(/#/g, '\n') .replace(/&gt;/g, '>') .replace(/&lt;/g, '<') .replace(/&amp;/g, '&'); logger.debug('First stage cleaned statblock: $$$', statblock); // Sometimes the texts ends up like 'P a r a l y z i n g T o u c h . M e l e e S p e l l A t t a c k : + 1 t o h i t // In this case we can fix the title case stuff, because we can find the word boundaries. That will at least meaning // that the core statblock parsing will work. If this happens inside the lowercase body text, however, there's nothing // we can do about it because you need to understand the natural language to reinsert the word breaks properly. statblock = statblock.replace(/([A-Z])(\s[a-z]){2,}/g, (match, p1) => p1 + match.slice(1).replace(/\s([a-z])/g, '$1') ); // Conversely, sometimes words get mushed together. Again, we can only fix this for title case things, but that's // better than nothing statblock = statblock.replace(/([A-Z][a-z]+)(?=[A-Z])/g, '$1 '); // This covers abilites that end up as 'C O N' or similar statblock = statblock.replace(/^[A-Z]\s?[A-Z]\s?[A-Z](?=\s|$)/mg, match => match.replace(/\s/g, '')); statblock = statblock.replace(/^[A-Z ]+$/m, match => match.replace(/([A-Z])([A-Z]+)(?=\s|$)/g, (innerMatch, p1, p2) => p1 + p2.toLowerCase()) ); statblock = statblock.replace(/(\d+)\s*?plus\s*?((?:\d+d\d+)|(?:\d+))/gi, '$2 + $1'); /* eslint-disable quote-props */ const replaceObj = { 'Jly': 'fly', ',1\'': ',*', 'jday': '/day', 'abol eth': 'aboleth', 'ACT IONS': 'ACTIONS', 'Afrightened': 'A frightened', 'Alesser': 'A lesser', 'Athl etics': 'Athletics', 'blindn ess': 'blindness', 'blind sight': 'blindsight', 'bofh': 'both', 'brea stplate': 'breastplate', 'Can trips': 'Cantrips', 'choos in g': 'choosing', 'com muni cate': 'communicate', 'Constituti on': 'Constitution', 'creatu re': 'creature', 'darkvi sion': 'darkvision', 'dea ls': 'deals', 'di sease': 'disease', 'di stance': 'distance', 'fa lls': 'falls', 'fe et': 'feet', 'exha les': 'exhales', 'ex istence': 'existence', 'lfthe': 'If the', 'Ifthe': 'If the', 'ifthe': 'if the', 'lnt': 'Int', 'magica lly': 'magically', 'Med icine': 'Medicine', 'minlilte': 'minute', 'natura l': 'natural', 'ofeach': 'of each', 'ofthe': 'of the', 'on\'e': 'one', 'on ly': 'only', '0n': 'on', 'pass ive': 'passive', 'Perce ption': 'Perception', 'radi us': 'radius', 'ra nge': 'range', 'rega ins': 'regains', 'rest.oration': 'restoration', 'savin g': 'saving', 'si lvery': 'silvery', 's lashing': 'slashing', 'slas hing': 'slashing', 'slash in g': 'slashing', 'slash ing': 'slashing', 'Spel/casting': 'Spellcasting', 'successfu l': 'successful', 'ta rget': 'target', ' Th e ': ' The ', 't_urns': 'turns', 'unti l': 'until', 'withi n': 'within', 'tohit': 'to hit', 'At wi ll': 'At will', 'per-son': 'person', 'ab ility': 'ability', 'spe ll': 'spell', }; /* eslint-enable quote-props */ const re = new RegExp(Object.keys(replaceObj).join('|'), 'g'); statblock = statblock.replace(re, (matched) => replaceObj[matched]); statblock = statblock .replace(/,\./gi, ',') .replace(/:\./g, ':') .replace(/(\W)l(\W)/g, '$11$2') .replace(/\.([\w])/g, '. $1') .replace(/1</g, '*') .replace(/(\w)ii/g, '$1ll') .replace(/([a-z\/])1/g, '$1l') .replace(/([a-z])\/([a-z])/g, '$1l$2') .replace(/(^| )l /gm, '$11 ') .replace(/ft\s\./gi, 'ft.') .replace(/ft\.\s,/gi, 'ft') .replace(/ft\./gi, 'ft') .replace(/(\d+) ft\/(\d+) ft/gi, '$1/$2 ft') .replace(/lOd/g, '10d') .replace(/dl0/gi, 'd10') .replace(/dlO/gi, 'd10') .replace(/dl2/gi, 'd12') .replace(/S(\d+)d(\d+)/gi, '5$1d$2') .replace(/l(\d+)d(\d+)/gi, '1$1d$2') .replace(/ld(\d+)/gi, '1d$1') .replace(/l(\d+)d\s+(\d+)/gi, '1$1d$2') .replace(/(\d+)d\s+(\d+)/gi, '$1d$2') .replace(/(\d+)\s+d(\d+)/gi, '$1d$2') .replace(/(\d+)\s+d(\d+)/gi, '$1d$2') .replace(/(\d+)d(\d)\s(\d)/gi, '$1d$2$3') .replace(/(\d+)j(?:Day|day)/gi, '$1/Day') .replace(/(\d+)f(?:Day|day)/gi, '$1/Day') .replace(/(\d+)j(\d+)/gi, '$1/$2') .replace(/(\d+)f(\d+)/gi, '$1/$2') .replace(/{/gi, '(') .replace(/}/gi, ')') .replace(/(\d+)\((\d+) ft/gi, '$1/$2 ft') .replace(/• /gi, '') .replace(/’/gi, '\''); logger.debug('Final stage cleaned statblock: $$$', statblock); return statblock; } module.exports = sanitise; /***/ }, /* 24 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; const _ = __webpack_require__(2); const levelStrings = ['Cantrips ', '1st level ', '2nd level ', '3rd level ']; _.each(_.range(4, 10), level => (levelStrings[level] = `${level}th level `)); const spellcastingHandler = { splitRegex: /(Cantrips|(?:1st|2nd|3rd|[4-9]th)\s*level)\.?\s*\(([^\)]+)\)\s*:/i, makeLevelDetailsObject(match) { const levelMatch = match[1].match(/\d/); return { level: levelMatch ? parseInt(levelMatch[0], 10) : 0, slots: match[2], }; }, setLevelDetailsString(levelDetails) { levelDetails.newText = `${levelStrings[levelDetails.level]}(${levelDetails.slots}): `; levelDetails.newText += levelDetails.spells.join(', '); }, }; const innateHandler = { splitRegex: /(At\s?will|\d\s?\/\s?day)(?:\s?each)?\s?:/i, makeLevelDetailsObject(match) { const usesMatch = match[1].match(/\d/); return { uses: usesMatch ? parseInt(usesMatch[0], 10) : 0, slots: match[2], }; }, setLevelDetailsString(levelDetails) { levelDetails.newText = levelDetails.uses === 0 ? 'At will' : `${levelDetails.uses}/day`; if (levelDetails.spells.length > 1) { levelDetails.newText += ' each'; } levelDetails.newText += ': '; levelDetails.newText += levelDetails.spells.join(', '); }, }; function processSpellcastingTrait(monster, traitName, traitHandler, entityLookup) { const trait = _.findWhere(monster.traits, { name: traitName }); if (trait) { let spellList = trait.text.substring(trait.text.indexOf(':') + 1).replace('\n', ' '); const castingDetails = trait.text.substring(0, trait.text.indexOf(':')); const levelDetails = []; let match; while ((match = traitHandler.splitRegex.exec(spellList)) !== null) { if (_.last(levelDetails)) { _.last(levelDetails).spells = spellList.slice(0, match.index); } levelDetails.push(traitHandler.makeLevelDetailsObject(match)); spellList = spellList.slice(match.index + match[0].length); } if (_.last(levelDetails)) { _.last(levelDetails).spells = spellList; } let hasCastBeforeCombat = false; const spellDetailsByLevel = _.chain(levelDetails) .each(perLevelDetails => { perLevelDetails.spells = _.chain(perLevelDetails.spells.replace(',*', '*,').split(',')) .map(_.partial(_.result, _, 'trim')) .map(spellName => { const spellNameMatch = spellName.match(/([^\(\*]+)(?:\(([^\)]+)\))?(\*)?/); hasCastBeforeCombat = hasCastBeforeCombat || !!spellNameMatch[3]; return { name: spellNameMatch[1].trim(), restriction: spellNameMatch[2], castBeforeCombat: !!spellNameMatch[3], toString() { return this.name + (this.restriction ? ` (${this.restriction})` : '') + (this.castBeforeCombat ? '*' : ''); }, toSpellArrayItem() { return this.name; }, }; }) .each(spell => { spell.object = entityLookup.findEntity('spells', spell.name, true); if (spell.object) { spell.name = spell.object.name; spell.toSpellArrayItem = function toSpellArrayItem() { return this.object; }; } }) .value(); }) .each(traitHandler.setLevelDetailsString) .value(); trait.text = `${castingDetails}:\n${_.pluck(spellDetailsByLevel, 'newText').join('\n')}`; if (hasCastBeforeCombat) { trait.text += `\n* The ${monster.name.toLowerCase()} casts these spells on itself before combat.`; } const spells = _.chain(spellDetailsByLevel) .pluck('spells') .flatten() .map(_.partial(_.result, _, 'toSpellArrayItem')) .union(monster.spells ? monster.spells : []) .sortBy('name') .sortBy('level') .value(); if (!_.isEmpty(spells)) { monster.spells = spells; } } return []; } module.exports = function mpp(monsters, entityLookup) { _.each(monsters, monster => { processSpellcastingTrait(monster, 'Spellcasting', spellcastingHandler, entityLookup); processSpellcastingTrait(monster, 'Innate Spellcasting', innateHandler, entityLookup); }); }; /***/ } /******/ ]);
src/components/log.js
LaserWeb/lw.controller
import React from 'react'; import ReactDOM from 'react-dom'; // level STD, INFO, WARN, DANGER, SUCCESS const CommandHistory_ICON = ['terminal', 'info-circle', 'exclamation-triangle', 'exclamation-circle', 'check-circle']; const CommandHistory_CLASS = ['default', 'info', 'warning', 'danger', 'success']; function createCommandLogLine(message, level = 0, icon = undefined) { if (icon === undefined) icon = level; level = isNaN(level) ? level : CommandHistory_CLASS[level]; icon = isNaN(icon) ? icon : CommandHistory_ICON[icon]; let line = document.createElement('code'); line.className = level; line.innerHTML = `<i class="fa fa-${icon}"></i> ${message}`; return line; } export default class Log extends React.Component { componentDidMount() { if (!window.commandLog) window.commandLog = document.createElement('div'); ReactDOM.findDOMNode(this).appendChild(window.commandLog); } componentWillUnmount() { if (window.commandLog) ReactDOM.findDOMNode(this).removeChild(window.commandLog); } static write(message, level, icon) { if (!window.commandLog) window.commandLog = document.createElement('div'); window.commandLog.appendChild(createCommandLogLine(message, level, icon)); if (window.commandLog.parentNode) { let node = window.commandLog.parentNode; node.scrollTop = node.scrollHeight; } } static stringify(arg) { if (typeof arg === 'string') return arg; else if (Array.isArray(arg)) return arg.map(Log.stringify).join(' '); else return JSON.stringify(arg); } static log(...args) { Log.write(Log.stringify(args)); } static warn(...args) { Log.write(Log.stringify(args), 2); } static error(...args) { Log.write(Log.stringify(args), 3); } static dir(message, items, level) { Log.write(`<details><summary>${message}</summary><p>${Log.stringify(items)}</p></details>`, level); } render() { return <div className="log" {...this.props} />; } } Log.STD = 0; Log.INFO = 1; Log.WARN = 2; Log.DANGER = 3; Log.SUCCESS = 4;
src/scripts/models.js
TxsAdamWest/etsyReact
import React from 'react' import ReactDOM from 'react-dom' import Backbone from 'backbone' //Step 1 - Load dependencies jQuery, Underscore, Backbone. //Step 2 - Define Router and routes. //Step 3 - Connect to api for 1st time via collection. //Step 4 - Render Home View. // console.log("Hello world!") export const AllListingsCollection = Backbone.Collection.extend({ url: "https://openapi.etsy.com/v2/listings/active.js", _key: "k4v6u445o5n237im8b03002u", parse: function(rawJson){ console.log(rawJson) return rawJson.results } }) export const ListingModel = Backbone.Model.extend({ url: function() { return "https://openapi.etsy.com/v2/listings/" + this.listingId + ".js" }, _key: "k4v6u445o5n237im8b03002u", parse: function(rawJson){ return rawJson.results[0] }, initialize: function(listingId) { this.listingId = listingId console.log(this.listingId, "<<<< Listing Model fired!") } })
frontend/src/Settings/Notifications/Notifications/AddNotificationModal.js
Radarr/Radarr
import PropTypes from 'prop-types'; import React from 'react'; import Modal from 'Components/Modal/Modal'; import AddNotificationModalContentConnector from './AddNotificationModalContentConnector'; function AddNotificationModal({ isOpen, onModalClose, ...otherProps }) { return ( <Modal isOpen={isOpen} onModalClose={onModalClose} > <AddNotificationModalContentConnector {...otherProps} onModalClose={onModalClose} /> </Modal> ); } AddNotificationModal.propTypes = { isOpen: PropTypes.bool.isRequired, onModalClose: PropTypes.func.isRequired }; export default AddNotificationModal;
ajax/libs/vue/0.12.7/vue.js
gokuale/cdnjs
/** * Vue.js v0.12.7 * (c) 2015 Evan You * Released under the MIT License. */ (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["Vue"] = factory(); else root["Vue"] = 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__) { var _ = __webpack_require__(1) var extend = _.extend /** * The exposed Vue constructor. * * API conventions: * - public API methods/properties are prefiexed with `$` * - internal methods/properties are prefixed with `_` * - non-prefixed properties are assumed to be proxied user * data. * * @constructor * @param {Object} [options] * @public */ function Vue (options) { this._init(options) } /** * Mixin global API */ extend(Vue, __webpack_require__(9)) /** * Vue and every constructor that extends Vue has an * associated options object, which can be accessed during * compilation steps as `this.constructor.options`. * * These can be seen as the default options of every * Vue instance. */ Vue.options = { replace: true, directives: __webpack_require__(28), elementDirectives: __webpack_require__(50), filters: __webpack_require__(53), transitions: {}, components: {}, partials: {} } /** * Build up the prototype */ var p = Vue.prototype /** * $data has a setter which does a bunch of * teardown/setup work */ Object.defineProperty(p, '$data', { get: function () { return this._data }, set: function (newData) { if (newData !== this._data) { this._setData(newData) } } }) /** * Mixin internal instance methods */ extend(p, __webpack_require__(55)) extend(p, __webpack_require__(56)) extend(p, __webpack_require__(57)) extend(p, __webpack_require__(58)) extend(p, __webpack_require__(60)) /** * Mixin public API methods */ extend(p, __webpack_require__(61)) extend(p, __webpack_require__(62)) extend(p, __webpack_require__(63)) extend(p, __webpack_require__(64)) extend(p, __webpack_require__(65)) module.exports = _.Vue = Vue /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { var lang = __webpack_require__(3) var extend = lang.extend extend(exports, lang) extend(exports, __webpack_require__(4)) extend(exports, __webpack_require__(5)) extend(exports, __webpack_require__(2)) extend(exports, __webpack_require__(7)) extend(exports, __webpack_require__(8)) /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var extend = _.extend /** * Option overwriting strategies are functions that handle * how to merge a parent option value and a child option * value into the final value. * * All strategy functions follow the same signature: * * @param {*} parentVal * @param {*} childVal * @param {Vue} [vm] */ var strats = Object.create(null) /** * Helper that recursively merges two data objects together. */ function mergeData (to, from) { var key, toVal, fromVal for (key in from) { toVal = to[key] fromVal = from[key] if (!to.hasOwnProperty(key)) { to.$add(key, fromVal) } else if (_.isObject(toVal) && _.isObject(fromVal)) { mergeData(toVal, fromVal) } } return to } /** * Data */ strats.data = function (parentVal, childVal, vm) { if (!vm) { // in a Vue.extend merge, both should be functions if (!childVal) { return parentVal } if (typeof childVal !== 'function') { _.warn( 'The "data" option should be a function ' + 'that returns a per-instance value in component ' + 'definitions.' ) return parentVal } if (!parentVal) { return childVal } // when parentVal & childVal are both present, // we need to return a function that returns the // merged result of both functions... no need to // check if parentVal is a function here because // it has to be a function to pass previous merges. return function mergedDataFn () { return mergeData( childVal.call(this), parentVal.call(this) ) } } else if (parentVal || childVal) { return function mergedInstanceDataFn () { // instance merge var instanceData = typeof childVal === 'function' ? childVal.call(vm) : childVal var defaultData = typeof parentVal === 'function' ? parentVal.call(vm) : undefined if (instanceData) { return mergeData(instanceData, defaultData) } else { return defaultData } } } } /** * El */ strats.el = function (parentVal, childVal, vm) { if (!vm && childVal && typeof childVal !== 'function') { _.warn( 'The "el" option should be a function ' + 'that returns a per-instance value in component ' + 'definitions.' ) return } var ret = childVal || parentVal // invoke the element factory if this is instance merge return vm && typeof ret === 'function' ? ret.call(vm) : ret } /** * Hooks and param attributes are merged as arrays. */ strats.created = strats.ready = strats.attached = strats.detached = strats.beforeCompile = strats.compiled = strats.beforeDestroy = strats.destroyed = strats.props = function (parentVal, childVal) { return childVal ? parentVal ? parentVal.concat(childVal) : _.isArray(childVal) ? childVal : [childVal] : parentVal } /** * 0.11 deprecation warning */ strats.paramAttributes = function () { /* istanbul ignore next */ _.warn( '"paramAttributes" option has been deprecated in 0.12. ' + 'Use "props" instead.' ) } /** * Assets * * When a vm is present (instance creation), we need to do * a three-way merge between constructor options, instance * options and parent options. */ strats.directives = strats.filters = strats.transitions = strats.components = strats.partials = strats.elementDirectives = function (parentVal, childVal) { var res = Object.create(parentVal) return childVal ? extend(res, childVal) : res } /** * Events & Watchers. * * Events & watchers hashes should not overwrite one * another, so we merge them as arrays. */ strats.watch = strats.events = function (parentVal, childVal) { if (!childVal) return parentVal if (!parentVal) return childVal var ret = {} extend(ret, parentVal) for (var key in childVal) { var parent = ret[key] var child = childVal[key] if (parent && !_.isArray(parent)) { parent = [parent] } ret[key] = parent ? parent.concat(child) : [child] } return ret } /** * Other object hashes. */ strats.methods = strats.computed = function (parentVal, childVal) { if (!childVal) return parentVal if (!parentVal) return childVal var ret = Object.create(parentVal) extend(ret, childVal) return ret } /** * Default strategy. */ var defaultStrat = function (parentVal, childVal) { return childVal === undefined ? parentVal : childVal } /** * Make sure component options get converted to actual * constructors. * * @param {Object} components */ function guardComponents (components) { if (components) { var def for (var key in components) { if (_.commonTagRE.test(key)) { _.warn( 'Do not use built-in HTML elements as component ' + 'name: ' + key ) } def = components[key] if (_.isPlainObject(def)) { def.name = key components[key] = _.Vue.extend(def) } } } } /** * Ensure all props option syntax are normalized into the * Object-based format. * * @param {Object} options */ function guardProps (options) { var props = options.props if (_.isPlainObject(props)) { options.props = Object.keys(props).map(function (key) { var val = props[key] if (!_.isPlainObject(val)) { val = { type: val } } val.name = key return val }) } else if (_.isArray(props)) { options.props = props.map(function (prop) { return typeof prop === 'string' ? { name: prop } : prop }) } } /** * Merge two option objects into a new one. * Core utility used in both instantiation and inheritance. * * @param {Object} parent * @param {Object} child * @param {Vue} [vm] - if vm is present, indicates this is * an instantiation merge. */ exports.mergeOptions = function merge (parent, child, vm) { guardComponents(child.components) guardProps(child) var options = {} var key if (child.mixins) { for (var i = 0, l = child.mixins.length; i < l; i++) { parent = merge(parent, child.mixins[i], vm) } } for (key in parent) { mergeField(key) } for (key in child) { if (!(parent.hasOwnProperty(key))) { mergeField(key) } } function mergeField (key) { var strat = strats[key] || defaultStrat options[key] = strat(parent[key], child[key], vm, key) } return options } /** * Resolve an asset. * This function is used because child instances need access * to assets defined in its ancestor chain. * * @param {Object} options * @param {String} type * @param {String} id * @return {Object|Function} */ exports.resolveAsset = function resolve (options, type, id) { var asset = options[type][id] while (!asset && options._parent) { options = options._parent.$options asset = options[type][id] } return asset } /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { /** * Check is a string starts with $ or _ * * @param {String} str * @return {Boolean} */ exports.isReserved = function (str) { var c = (str + '').charCodeAt(0) return c === 0x24 || c === 0x5F } /** * Guard text output, make sure undefined outputs * empty string * * @param {*} value * @return {String} */ exports.toString = function (value) { return value == null ? '' : value.toString() } /** * Check and convert possible numeric numbers before * setting back to data * * @param {*} value * @return {*|Number} */ exports.toNumber = function (value) { return ( isNaN(value) || value === null || typeof value === 'boolean' ) ? value : Number(value) } /** * Convert string boolean literals into real booleans. * * @param {*} value * @return {*|Boolean} */ exports.toBoolean = function (value) { return value === 'true' ? true : value === 'false' ? false : value } /** * Strip quotes from a string * * @param {String} str * @return {String | false} */ exports.stripQuotes = function (str) { var a = str.charCodeAt(0) var b = str.charCodeAt(str.length - 1) return a === b && (a === 0x22 || a === 0x27) ? str.slice(1, -1) : false } /** * Camelize a hyphen-delmited string. * * @param {String} str * @return {String} */ exports.camelize = function (str) { return str.replace(/-(\w)/g, toUpper) } function toUpper (_, c) { return c ? c.toUpperCase() : '' } /** * Hyphenate a camelCase string. * * @param {String} str * @return {String} */ exports.hyphenate = function (str) { return str .replace(/([a-z\d])([A-Z])/g, '$1-$2') .toLowerCase() } /** * Converts hyphen/underscore/slash delimitered names into * camelized classNames. * * e.g. my-component => MyComponent * some_else => SomeElse * some/comp => SomeComp * * @param {String} str * @return {String} */ var classifyRE = /(?:^|[-_\/])(\w)/g exports.classify = function (str) { return str.replace(classifyRE, toUpper) } /** * Simple bind, faster than native * * @param {Function} fn * @param {Object} ctx * @return {Function} */ exports.bind = function (fn, ctx) { return function (a) { var l = arguments.length return l ? l > 1 ? fn.apply(ctx, arguments) : fn.call(ctx, a) : fn.call(ctx) } } /** * Convert an Array-like object to a real Array. * * @param {Array-like} list * @param {Number} [start] - start index * @return {Array} */ exports.toArray = function (list, start) { start = start || 0 var i = list.length - start var ret = new Array(i) while (i--) { ret[i] = list[i + start] } return ret } /** * Mix properties into target object. * * @param {Object} to * @param {Object} from */ exports.extend = function (to, from) { for (var key in from) { to[key] = from[key] } return to } /** * Quick object check - this is primarily used to tell * Objects from primitive values when we know the value * is a JSON-compliant type. * * @param {*} obj * @return {Boolean} */ exports.isObject = function (obj) { return obj !== null && typeof obj === 'object' } /** * Strict object type check. Only returns true * for plain JavaScript objects. * * @param {*} obj * @return {Boolean} */ var toString = Object.prototype.toString exports.isPlainObject = function (obj) { return toString.call(obj) === '[object Object]' } /** * Array type check. * * @param {*} obj * @return {Boolean} */ exports.isArray = Array.isArray /** * Define a non-enumerable property * * @param {Object} obj * @param {String} key * @param {*} val * @param {Boolean} [enumerable] */ exports.define = function (obj, key, val, enumerable) { Object.defineProperty(obj, key, { value: val, enumerable: !!enumerable, writable: true, configurable: true }) } /** * Debounce a function so it only gets called after the * input stops arriving after the given wait period. * * @param {Function} func * @param {Number} wait * @return {Function} - the debounced function */ exports.debounce = function (func, wait) { var timeout, args, context, timestamp, result var later = function () { var last = Date.now() - timestamp if (last < wait && last >= 0) { timeout = setTimeout(later, wait - last) } else { timeout = null result = func.apply(context, args) if (!timeout) context = args = null } } return function () { context = this args = arguments timestamp = Date.now() if (!timeout) { timeout = setTimeout(later, wait) } return result } } /** * Manual indexOf because it's slightly faster than * native. * * @param {Array} arr * @param {*} obj */ exports.indexOf = function (arr, obj) { for (var i = 0, l = arr.length; i < l; i++) { if (arr[i] === obj) return i } return -1 } /** * Make a cancellable version of an async callback. * * @param {Function} fn * @return {Function} */ exports.cancellable = function (fn) { var cb = function () { if (!cb.cancelled) { return fn.apply(this, arguments) } } cb.cancel = function () { cb.cancelled = true } return cb } /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { // can we use __proto__? exports.hasProto = '__proto__' in {} // Browser environment sniffing var inBrowser = exports.inBrowser = typeof window !== 'undefined' && Object.prototype.toString.call(window) !== '[object Object]' exports.isIE9 = inBrowser && navigator.userAgent.toLowerCase().indexOf('msie 9.0') > 0 exports.isAndroid = inBrowser && navigator.userAgent.toLowerCase().indexOf('android') > 0 // Transition property/event sniffing if (inBrowser && !exports.isIE9) { var isWebkitTrans = window.ontransitionend === undefined && window.onwebkittransitionend !== undefined var isWebkitAnim = window.onanimationend === undefined && window.onwebkitanimationend !== undefined exports.transitionProp = isWebkitTrans ? 'WebkitTransition' : 'transition' exports.transitionEndEvent = isWebkitTrans ? 'webkitTransitionEnd' : 'transitionend' exports.animationProp = isWebkitAnim ? 'WebkitAnimation' : 'animation' exports.animationEndEvent = isWebkitAnim ? 'webkitAnimationEnd' : 'animationend' } /** * Defer a task to execute it asynchronously. Ideally this * should be executed as a microtask, so we leverage * MutationObserver if it's available, and fallback to * setTimeout(0). * * @param {Function} cb * @param {Object} ctx */ exports.nextTick = (function () { var callbacks = [] var pending = false var timerFunc function handle () { pending = false var copies = callbacks.slice(0) callbacks = [] for (var i = 0; i < copies.length; i++) { copies[i]() } } /* istanbul ignore if */ if (typeof MutationObserver !== 'undefined') { var counter = 1 var observer = new MutationObserver(handle) var textNode = document.createTextNode(counter) observer.observe(textNode, { characterData: true }) timerFunc = function () { counter = (counter + 1) % 2 textNode.data = counter } } else { timerFunc = setTimeout } return function (cb, ctx) { var func = ctx ? function () { cb.call(ctx) } : cb callbacks.push(func) if (pending) return pending = true timerFunc(handle, 0) } })() /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var config = __webpack_require__(6) /** * Query an element selector if it's not an element already. * * @param {String|Element} el * @return {Element} */ exports.query = function (el) { if (typeof el === 'string') { var selector = el el = document.querySelector(el) if (!el) { _.warn('Cannot find element: ' + selector) } } return el } /** * Check if a node is in the document. * Note: document.documentElement.contains should work here * but always returns false for comment nodes in phantomjs, * making unit tests difficult. This is fixed byy doing the * contains() check on the node's parentNode instead of * the node itself. * * @param {Node} node * @return {Boolean} */ exports.inDoc = function (node) { var doc = document.documentElement var parent = node && node.parentNode return doc === node || doc === parent || !!(parent && parent.nodeType === 1 && (doc.contains(parent))) } /** * Extract an attribute from a node. * * @param {Node} node * @param {String} attr */ exports.attr = function (node, attr) { attr = config.prefix + attr var val = node.getAttribute(attr) if (val !== null) { node.removeAttribute(attr) } return val } /** * Insert el before target * * @param {Element} el * @param {Element} target */ exports.before = function (el, target) { target.parentNode.insertBefore(el, target) } /** * Insert el after target * * @param {Element} el * @param {Element} target */ exports.after = function (el, target) { if (target.nextSibling) { exports.before(el, target.nextSibling) } else { target.parentNode.appendChild(el) } } /** * Remove el from DOM * * @param {Element} el */ exports.remove = function (el) { el.parentNode.removeChild(el) } /** * Prepend el to target * * @param {Element} el * @param {Element} target */ exports.prepend = function (el, target) { if (target.firstChild) { exports.before(el, target.firstChild) } else { target.appendChild(el) } } /** * Replace target with el * * @param {Element} target * @param {Element} el */ exports.replace = function (target, el) { var parent = target.parentNode if (parent) { parent.replaceChild(el, target) } } /** * Add event listener shorthand. * * @param {Element} el * @param {String} event * @param {Function} cb */ exports.on = function (el, event, cb) { el.addEventListener(event, cb) } /** * Remove event listener shorthand. * * @param {Element} el * @param {String} event * @param {Function} cb */ exports.off = function (el, event, cb) { el.removeEventListener(event, cb) } /** * Add class with compatibility for IE & SVG * * @param {Element} el * @param {Strong} cls */ exports.addClass = function (el, cls) { if (el.classList) { el.classList.add(cls) } else { var cur = ' ' + (el.getAttribute('class') || '') + ' ' if (cur.indexOf(' ' + cls + ' ') < 0) { el.setAttribute('class', (cur + cls).trim()) } } } /** * Remove class with compatibility for IE & SVG * * @param {Element} el * @param {Strong} cls */ exports.removeClass = function (el, cls) { if (el.classList) { el.classList.remove(cls) } else { var cur = ' ' + (el.getAttribute('class') || '') + ' ' var tar = ' ' + cls + ' ' while (cur.indexOf(tar) >= 0) { cur = cur.replace(tar, ' ') } el.setAttribute('class', cur.trim()) } } /** * Extract raw content inside an element into a temporary * container div * * @param {Element} el * @param {Boolean} asFragment * @return {Element} */ exports.extractContent = function (el, asFragment) { var child var rawContent /* istanbul ignore if */ if ( exports.isTemplate(el) && el.content instanceof DocumentFragment ) { el = el.content } if (el.hasChildNodes()) { trim(el, el.firstChild) trim(el, el.lastChild) rawContent = asFragment ? document.createDocumentFragment() : document.createElement('div') /* eslint-disable no-cond-assign */ while (child = el.firstChild) { /* eslint-enable no-cond-assign */ rawContent.appendChild(child) } } return rawContent } function trim (content, node) { if (node && node.nodeType === 3 && !node.data.trim()) { content.removeChild(node) } } /** * Check if an element is a template tag. * Note if the template appears inside an SVG its tagName * will be in lowercase. * * @param {Element} el */ exports.isTemplate = function (el) { return el.tagName && el.tagName.toLowerCase() === 'template' } /** * Create an "anchor" for performing dom insertion/removals. * This is used in a number of scenarios: * - block instance * - v-html * - v-if * - component * - repeat * * @param {String} content * @param {Boolean} persist - IE trashes empty textNodes on * cloneNode(true), so in certain * cases the anchor needs to be * non-empty to be persisted in * templates. * @return {Comment|Text} */ exports.createAnchor = function (content, persist) { return config.debug ? document.createComment(content) : document.createTextNode(persist ? ' ' : '') } /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { module.exports = { /** * The prefix to look for when parsing directives. * * @type {String} */ prefix: 'v-', /** * Whether to print debug messages. * Also enables stack trace for warnings. * * @type {Boolean} */ debug: false, /** * Whether to suppress warnings. * * @type {Boolean} */ silent: false, /** * Whether allow observer to alter data objects' * __proto__. * * @type {Boolean} */ proto: true, /** * Whether to parse mustache tags in templates. * * @type {Boolean} */ interpolate: true, /** * Whether to use async rendering. */ async: true, /** * Whether to warn against errors caught when evaluating * expressions. */ warnExpressionErrors: true, /** * Internal flag to indicate the delimiters have been * changed. * * @type {Boolean} */ _delimitersChanged: true, /** * List of asset types that a component can own. * * @type {Array} */ _assetTypes: [ 'component', 'directive', 'elementDirective', 'filter', 'transition', 'partial' ], /** * prop binding modes */ _propBindingModes: { ONE_WAY: 0, TWO_WAY: 1, ONE_TIME: 2 }, /** * Max circular updates allowed in a batcher flush cycle. */ _maxUpdateCount: 100 } /** * Interpolation delimiters. * We need to mark the changed flag so that the text parser * knows it needs to recompile the regex. * * @type {Array<String>} */ var delimiters = ['{{', '}}'] Object.defineProperty(module.exports, 'delimiters', { get: function () { return delimiters }, set: function (val) { delimiters = val this._delimitersChanged = true } }) /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) /** * Check if an element is a component, if yes return its * component id. * * @param {Element} el * @param {Object} options * @return {String|undefined} */ exports.commonTagRE = /^(div|p|span|img|a|br|ul|ol|li|h1|h2|h3|h4|h5|code|pre)$/ exports.checkComponent = function (el, options) { var tag = el.tagName.toLowerCase() if (tag === 'component') { // dynamic syntax var exp = el.getAttribute('is') el.removeAttribute('is') return exp } else if ( !exports.commonTagRE.test(tag) && _.resolveAsset(options, 'components', tag) ) { return tag /* eslint-disable no-cond-assign */ } else if (tag = _.attr(el, 'component')) { /* eslint-enable no-cond-assign */ return tag } } /** * Set a prop's initial value on a vm and its data object. * The vm may have inherit:true so we need to make sure * we don't accidentally overwrite parent value. * * @param {Vue} vm * @param {Object} prop * @param {*} value */ exports.initProp = function (vm, prop, value) { if (exports.assertProp(prop, value)) { var key = prop.path if (key in vm) { _.define(vm, key, value, true) } else { vm[key] = value } vm._data[key] = value } } /** * Assert whether a prop is valid. * * @param {Object} prop * @param {*} value */ exports.assertProp = function (prop, value) { var options = prop.options var type = options.type var valid = true var expectedType if (type) { if (type === String) { expectedType = 'string' valid = typeof value === expectedType } else if (type === Number) { expectedType = 'number' valid = typeof value === 'number' } else if (type === Boolean) { expectedType = 'boolean' valid = typeof value === 'boolean' } else if (type === Function) { expectedType = 'function' valid = typeof value === 'function' } else if (type === Object) { expectedType = 'object' valid = _.isPlainObject(value) } else if (type === Array) { expectedType = 'array' valid = _.isArray(value) } else { valid = value instanceof type } } if (!valid) { _.warn( 'Invalid prop: type check failed for ' + prop.path + '="' + prop.raw + '".' + ' Expected ' + formatType(expectedType) + ', got ' + formatValue(value) + '.' ) return false } var validator = options.validator if (validator) { if (!validator.call(null, value)) { _.warn( 'Invalid prop: custom validator check failed for ' + prop.path + '="' + prop.raw + '"' ) return false } } return true } function formatType (val) { return val ? val.charAt(0).toUpperCase() + val.slice(1) : 'custom type' } function formatValue (val) { return Object.prototype.toString.call(val).slice(8, -1) } /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { var config = __webpack_require__(6) /** * Enable debug utilities. The enableDebug() function and * all _.log() & _.warn() calls will be dropped in the * minified production build. */ enableDebug() function enableDebug () { var hasConsole = typeof console !== 'undefined' /** * Log a message. * * @param {String} msg */ exports.log = function (msg) { if (hasConsole && config.debug) { console.log('[Vue info]: ' + msg) } } /** * We've got a problem here. * * @param {String} msg */ exports.warn = function (msg, e) { if (hasConsole && (!config.silent || config.debug)) { console.warn('[Vue warn]: ' + msg) /* istanbul ignore if */ if (config.debug) { console.warn((e || new Error('Warning Stack Trace')).stack) } } } /** * Assert asset exists */ exports.assertAsset = function (val, type, id) { /* istanbul ignore if */ if (type === 'directive') { if (id === 'with') { exports.warn( 'v-with has been deprecated in ^0.12.0. ' + 'Use props instead.' ) return } if (id === 'events') { exports.warn( 'v-events has been deprecated in ^0.12.0. ' + 'Pass down methods as callback props instead.' ) return } } if (!val) { exports.warn('Failed to resolve ' + type + ': ' + id) } } } /***/ }, /* 9 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var config = __webpack_require__(6) /** * Expose useful internals */ exports.util = _ exports.nextTick = _.nextTick exports.config = __webpack_require__(6) exports.compiler = __webpack_require__(10) exports.parsers = { path: __webpack_require__(23), text: __webpack_require__(13), template: __webpack_require__(25), directive: __webpack_require__(15), expression: __webpack_require__(22) } /** * Each instance constructor, including Vue, has a unique * cid. This enables us to create wrapped "child * constructors" for prototypal inheritance and cache them. */ exports.cid = 0 var cid = 1 /** * Class inehritance * * @param {Object} extendOptions */ exports.extend = function (extendOptions) { extendOptions = extendOptions || {} var Super = this var Sub = createClass( extendOptions.name || Super.options.name || 'VueComponent' ) Sub.prototype = Object.create(Super.prototype) Sub.prototype.constructor = Sub Sub.cid = cid++ Sub.options = _.mergeOptions( Super.options, extendOptions ) Sub['super'] = Super // allow further extension Sub.extend = Super.extend // create asset registers, so extended classes // can have their private assets too. config._assetTypes.forEach(function (type) { Sub[type] = Super[type] }) return Sub } /** * A function that returns a sub-class constructor with the * given name. This gives us much nicer output when * logging instances in the console. * * @param {String} name * @return {Function} */ function createClass (name) { return new Function( 'return function ' + _.classify(name) + ' (options) { this._init(options) }' )() } /** * Plugin system * * @param {Object} plugin */ exports.use = function (plugin) { // additional parameters var args = _.toArray(arguments, 1) args.unshift(this) if (typeof plugin.install === 'function') { plugin.install.apply(plugin, args) } else { plugin.apply(null, args) } return this } /** * Create asset registration methods with the following * signature: * * @param {String} id * @param {*} definition */ config._assetTypes.forEach(function (type) { exports[type] = function (id, definition) { if (!definition) { return this.options[type + 's'][id] } else { if ( type === 'component' && _.isPlainObject(definition) ) { definition.name = id definition = _.Vue.extend(definition) } this.options[type + 's'][id] = definition } } }) /***/ }, /* 10 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) _.extend(exports, __webpack_require__(11)) _.extend(exports, __webpack_require__(27)) /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var compileProps = __webpack_require__(12) var config = __webpack_require__(6) var textParser = __webpack_require__(13) var dirParser = __webpack_require__(15) var templateParser = __webpack_require__(25) var resolveAsset = _.resolveAsset var componentDef = __webpack_require__(26) // terminal directives var terminalDirectives = [ 'repeat', 'if' ] /** * Compile a template and return a reusable composite link * function, which recursively contains more link functions * inside. This top level compile function would normally * be called on instance root nodes, but can also be used * for partial compilation if the partial argument is true. * * The returned composite link function, when called, will * return an unlink function that tearsdown all directives * created during the linking phase. * * @param {Element|DocumentFragment} el * @param {Object} options * @param {Boolean} partial * @param {Vue} [host] - host vm of transcluded content * @return {Function} */ exports.compile = function (el, options, partial, host) { // link function for the node itself. var nodeLinkFn = partial || !options._asComponent ? compileNode(el, options) : null // link function for the childNodes var childLinkFn = !(nodeLinkFn && nodeLinkFn.terminal) && el.tagName !== 'SCRIPT' && el.hasChildNodes() ? compileNodeList(el.childNodes, options) : null /** * A composite linker function to be called on a already * compiled piece of DOM, which instantiates all directive * instances. * * @param {Vue} vm * @param {Element|DocumentFragment} el * @return {Function|undefined} */ return function compositeLinkFn (vm, el) { // cache childNodes before linking parent, fix #657 var childNodes = _.toArray(el.childNodes) // link var dirs = linkAndCapture(function () { if (nodeLinkFn) nodeLinkFn(vm, el, host) if (childLinkFn) childLinkFn(vm, childNodes, host) }, vm) return makeUnlinkFn(vm, dirs) } } /** * Apply a linker to a vm/element pair and capture the * directives created during the process. * * @param {Function} linker * @param {Vue} vm */ function linkAndCapture (linker, vm) { var originalDirCount = vm._directives.length linker() return vm._directives.slice(originalDirCount) } /** * Linker functions return an unlink function that * tearsdown all directives instances generated during * the process. * * We create unlink functions with only the necessary * information to avoid retaining additional closures. * * @param {Vue} vm * @param {Array} dirs * @param {Vue} [context] * @param {Array} [contextDirs] * @return {Function} */ function makeUnlinkFn (vm, dirs, context, contextDirs) { return function unlink (destroying) { teardownDirs(vm, dirs, destroying) if (context && contextDirs) { teardownDirs(context, contextDirs) } } } /** * Teardown partial linked directives. * * @param {Vue} vm * @param {Array} dirs * @param {Boolean} destroying */ function teardownDirs (vm, dirs, destroying) { var i = dirs.length while (i--) { dirs[i]._teardown() if (!destroying) { vm._directives.$remove(dirs[i]) } } } /** * Compile link props on an instance. * * @param {Vue} vm * @param {Element} el * @param {Object} options * @return {Function} */ exports.compileAndLinkProps = function (vm, el, props) { var propsLinkFn = compileProps(el, props) var propDirs = linkAndCapture(function () { propsLinkFn(vm, null) }, vm) return makeUnlinkFn(vm, propDirs) } /** * Compile the root element of an instance. * * 1. attrs on context container (context scope) * 2. attrs on the component template root node, if * replace:true (child scope) * * If this is a block instance, we only need to compile 1. * * This function does compile and link at the same time, * since root linkers can not be reused. It returns the * unlink function for potential context directives on the * container. * * @param {Vue} vm * @param {Element} el * @param {Object} options * @return {Function} */ exports.compileAndLinkRoot = function (vm, el, options) { var containerAttrs = options._containerAttrs var replacerAttrs = options._replacerAttrs var contextLinkFn, replacerLinkFn // only need to compile other attributes for // non-block instances if (el.nodeType !== 11) { // for components, container and replacer need to be // compiled separately and linked in different scopes. if (options._asComponent) { // 2. container attributes if (containerAttrs) { contextLinkFn = compileDirectives(containerAttrs, options) } if (replacerAttrs) { // 3. replacer attributes replacerLinkFn = compileDirectives(replacerAttrs, options) } } else { // non-component, just compile as a normal element. replacerLinkFn = compileDirectives(el, options) } } // link context scope dirs var context = vm._context var contextDirs if (context && contextLinkFn) { contextDirs = linkAndCapture(function () { contextLinkFn(context, el) }, context) } // link self var selfDirs = linkAndCapture(function () { if (replacerLinkFn) replacerLinkFn(vm, el) }, vm) // return the unlink function that tearsdown context // container directives. return makeUnlinkFn(vm, selfDirs, context, contextDirs) } /** * Compile a node and return a nodeLinkFn based on the * node type. * * @param {Node} node * @param {Object} options * @return {Function|null} */ function compileNode (node, options) { var type = node.nodeType if (type === 1 && node.tagName !== 'SCRIPT') { return compileElement(node, options) } else if (type === 3 && config.interpolate && node.data.trim()) { return compileTextNode(node, options) } else { return null } } /** * Compile an element and return a nodeLinkFn. * * @param {Element} el * @param {Object} options * @return {Function|null} */ function compileElement (el, options) { var linkFn var hasAttrs = el.hasAttributes() // check terminal directives (repeat & if) if (hasAttrs) { linkFn = checkTerminalDirectives(el, options) } // check element directives if (!linkFn) { linkFn = checkElementDirectives(el, options) } // check component if (!linkFn) { linkFn = checkComponent(el, options) } // normal directives if (!linkFn && hasAttrs) { linkFn = compileDirectives(el, options) } // if the element is a textarea, we need to interpolate // its content on initial render. if (el.tagName === 'TEXTAREA') { var realLinkFn = linkFn linkFn = function (vm, el) { el.value = vm.$interpolate(el.value) if (realLinkFn) realLinkFn(vm, el) } linkFn.terminal = true } return linkFn } /** * Compile a textNode and return a nodeLinkFn. * * @param {TextNode} node * @param {Object} options * @return {Function|null} textNodeLinkFn */ function compileTextNode (node, options) { var tokens = textParser.parse(node.data) if (!tokens) { return null } var frag = document.createDocumentFragment() var el, token for (var i = 0, l = tokens.length; i < l; i++) { token = tokens[i] el = token.tag ? processTextToken(token, options) : document.createTextNode(token.value) frag.appendChild(el) } return makeTextNodeLinkFn(tokens, frag, options) } /** * Process a single text token. * * @param {Object} token * @param {Object} options * @return {Node} */ function processTextToken (token, options) { var el if (token.oneTime) { el = document.createTextNode(token.value) } else { if (token.html) { el = document.createComment('v-html') setTokenType('html') } else { // IE will clean up empty textNodes during // frag.cloneNode(true), so we have to give it // something here... el = document.createTextNode(' ') setTokenType('text') } } function setTokenType (type) { token.type = type token.def = resolveAsset(options, 'directives', type) token.descriptor = dirParser.parse(token.value)[0] } return el } /** * Build a function that processes a textNode. * * @param {Array<Object>} tokens * @param {DocumentFragment} frag */ function makeTextNodeLinkFn (tokens, frag) { return function textNodeLinkFn (vm, el) { var fragClone = frag.cloneNode(true) var childNodes = _.toArray(fragClone.childNodes) var token, value, node for (var i = 0, l = tokens.length; i < l; i++) { token = tokens[i] value = token.value if (token.tag) { node = childNodes[i] if (token.oneTime) { value = vm.$eval(value) if (token.html) { _.replace(node, templateParser.parse(value, true)) } else { node.data = value } } else { vm._bindDir(token.type, node, token.descriptor, token.def) } } } _.replace(el, fragClone) } } /** * Compile a node list and return a childLinkFn. * * @param {NodeList} nodeList * @param {Object} options * @return {Function|undefined} */ function compileNodeList (nodeList, options) { var linkFns = [] var nodeLinkFn, childLinkFn, node for (var i = 0, l = nodeList.length; i < l; i++) { node = nodeList[i] nodeLinkFn = compileNode(node, options) childLinkFn = !(nodeLinkFn && nodeLinkFn.terminal) && node.tagName !== 'SCRIPT' && node.hasChildNodes() ? compileNodeList(node.childNodes, options) : null linkFns.push(nodeLinkFn, childLinkFn) } return linkFns.length ? makeChildLinkFn(linkFns) : null } /** * Make a child link function for a node's childNodes. * * @param {Array<Function>} linkFns * @return {Function} childLinkFn */ function makeChildLinkFn (linkFns) { return function childLinkFn (vm, nodes, host) { var node, nodeLinkFn, childrenLinkFn for (var i = 0, n = 0, l = linkFns.length; i < l; n++) { node = nodes[n] nodeLinkFn = linkFns[i++] childrenLinkFn = linkFns[i++] // cache childNodes before linking parent, fix #657 var childNodes = _.toArray(node.childNodes) if (nodeLinkFn) { nodeLinkFn(vm, node, host) } if (childrenLinkFn) { childrenLinkFn(vm, childNodes, host) } } } } /** * Check for element directives (custom elements that should * be resovled as terminal directives). * * @param {Element} el * @param {Object} options */ function checkElementDirectives (el, options) { var tag = el.tagName.toLowerCase() if (_.commonTagRE.test(tag)) return var def = resolveAsset(options, 'elementDirectives', tag) if (def) { return makeTerminalNodeLinkFn(el, tag, '', options, def) } } /** * Check if an element is a component. If yes, return * a component link function. * * @param {Element} el * @param {Object} options * @param {Boolean} hasAttrs * @return {Function|undefined} */ function checkComponent (el, options, hasAttrs) { var componentId = _.checkComponent(el, options, hasAttrs) if (componentId) { var componentLinkFn = function (vm, el, host) { vm._bindDir('component', el, { expression: componentId }, componentDef, host) } componentLinkFn.terminal = true return componentLinkFn } } /** * Check an element for terminal directives in fixed order. * If it finds one, return a terminal link function. * * @param {Element} el * @param {Object} options * @return {Function} terminalLinkFn */ function checkTerminalDirectives (el, options) { if (_.attr(el, 'pre') !== null) { return skip } var value, dirName for (var i = 0, l = terminalDirectives.length; i < l; i++) { dirName = terminalDirectives[i] if ((value = _.attr(el, dirName)) !== null) { return makeTerminalNodeLinkFn(el, dirName, value, options) } } } function skip () {} skip.terminal = true /** * Build a node link function for a terminal directive. * A terminal link function terminates the current * compilation recursion and handles compilation of the * subtree in the directive. * * @param {Element} el * @param {String} dirName * @param {String} value * @param {Object} options * @param {Object} [def] * @return {Function} terminalLinkFn */ function makeTerminalNodeLinkFn (el, dirName, value, options, def) { var descriptor = dirParser.parse(value)[0] // no need to call resolveAsset since terminal directives // are always internal def = def || options.directives[dirName] var fn = function terminalNodeLinkFn (vm, el, host) { vm._bindDir(dirName, el, descriptor, def, host) } fn.terminal = true return fn } /** * Compile the directives on an element and return a linker. * * @param {Element|Object} elOrAttrs * - could be an object of already-extracted * container attributes. * @param {Object} options * @return {Function} */ function compileDirectives (elOrAttrs, options) { var attrs = _.isPlainObject(elOrAttrs) ? mapToList(elOrAttrs) : elOrAttrs.attributes var i = attrs.length var dirs = [] var attr, name, value, dir, dirName, dirDef while (i--) { attr = attrs[i] name = attr.name value = attr.value if (name.indexOf(config.prefix) === 0) { dirName = name.slice(config.prefix.length) dirDef = resolveAsset(options, 'directives', dirName) _.assertAsset(dirDef, 'directive', dirName) if (dirDef) { dirs.push({ name: dirName, descriptors: dirParser.parse(value), def: dirDef }) } } else if (config.interpolate) { dir = collectAttrDirective(name, value, options) if (dir) { dirs.push(dir) } } } // sort by priority, LOW to HIGH if (dirs.length) { dirs.sort(directiveComparator) return makeNodeLinkFn(dirs) } } /** * Convert a map (Object) of attributes to an Array. * * @param {Object} map * @return {Array} */ function mapToList (map) { var list = [] for (var key in map) { list.push({ name: key, value: map[key] }) } return list } /** * Build a link function for all directives on a single node. * * @param {Array} directives * @return {Function} directivesLinkFn */ function makeNodeLinkFn (directives) { return function nodeLinkFn (vm, el, host) { // reverse apply because it's sorted low to high var i = directives.length var dir, j, k while (i--) { dir = directives[i] if (dir._link) { // custom link fn dir._link(vm, el) } else { k = dir.descriptors.length for (j = 0; j < k; j++) { vm._bindDir(dir.name, el, dir.descriptors[j], dir.def, host) } } } } } /** * Check an attribute for potential dynamic bindings, * and return a directive object. * * @param {String} name * @param {String} value * @param {Object} options * @return {Object} */ function collectAttrDirective (name, value, options) { var tokens = textParser.parse(value) if (tokens) { var def = options.directives.attr var i = tokens.length var allOneTime = true while (i--) { var token = tokens[i] if (token.tag && !token.oneTime) { allOneTime = false } } return { def: def, _link: allOneTime ? function (vm, el) { el.setAttribute(name, vm.$interpolate(value)) } : function (vm, el) { var value = textParser.tokensToExp(tokens, vm) var desc = dirParser.parse(name + ':' + value)[0] vm._bindDir('attr', el, desc, def) } } } } /** * Directive priority sort comparator * * @param {Object} a * @param {Object} b */ function directiveComparator (a, b) { a = a.def.priority || 0 b = b.def.priority || 0 return a > b ? 1 : -1 } /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var textParser = __webpack_require__(13) var propDef = __webpack_require__(16) var propBindingModes = __webpack_require__(6)._propBindingModes // regexes var identRE = __webpack_require__(23).identRE var dataAttrRE = /^data-/ var settablePathRE = /^[A-Za-z_$][\w$]*(\.[A-Za-z_$][\w$]*|\[[^\[\]]+\])*$/ var literalValueRE = /^(true|false)$|^\d.*/ /** * Compile param attributes on a root element and return * a props link function. * * @param {Element|DocumentFragment} el * @param {Array} propOptions * @return {Function} propsLinkFn */ module.exports = function compileProps (el, propOptions) { var props = [] var i = propOptions.length var options, name, value, path, prop, literal, single while (i--) { options = propOptions[i] name = options.name // props could contain dashes, which will be // interpreted as minus calculations by the parser // so we need to camelize the path here path = _.camelize(name.replace(dataAttrRE, '')) if (!identRE.test(path)) { _.warn( 'Invalid prop key: "' + name + '". Prop keys ' + 'must be valid identifiers.' ) } value = el.getAttribute(_.hyphenate(name)) // create a prop descriptor prop = { name: name, raw: value, path: path, options: options, mode: propBindingModes.ONE_WAY } if (value !== null) { // important so that this doesn't get compiled // again as a normal attribute binding el.removeAttribute(name) var tokens = textParser.parse(value) if (tokens) { if (el && el.nodeType === 1) { el.removeAttribute(name) } prop.dynamic = true prop.parentPath = textParser.tokensToExp(tokens) // check prop binding type. single = tokens.length === 1 literal = literalValueRE.test(prop.parentPath) // one time: {{* prop}} if (literal || (single && tokens[0].oneTime)) { prop.mode = propBindingModes.ONE_TIME } else if ( !literal && (single && tokens[0].twoWay) ) { if (settablePathRE.test(prop.parentPath)) { prop.mode = propBindingModes.TWO_WAY } else { _.warn( 'Cannot bind two-way prop with non-settable ' + 'parent path: ' + prop.parentPath ) } } } } else if (options && options.required) { _.warn('Missing required prop: ' + name) } props.push(prop) } return makePropsLinkFn(props) } /** * Build a function that applies props to a vm. * * @param {Array} props * @return {Function} propsLinkFn */ function makePropsLinkFn (props) { return function propsLinkFn (vm, el) { // store resolved props info vm._props = {} var i = props.length var prop, path, options, value while (i--) { prop = props[i] path = prop.path vm._props[path] = prop options = prop.options if (prop.raw === null) { // initialize absent prop vm._data[path] = options.type === Boolean ? false : options.hasOwnProperty('default') ? options.default : undefined } else if (prop.dynamic) { // dynamic prop if (vm._context) { if (prop.mode === propBindingModes.ONE_TIME) { // one time binding value = vm._context.$get(prop.parentPath) _.initProp(vm, prop, value) } else { // dynamic binding vm._bindDir('prop', el, prop, propDef) } } else { _.warn( 'Cannot bind dynamic prop on a root instance' + ' with no parent: ' + prop.name + '="' + prop.raw + '"' ) } } else { // literal, cast it and just set once value = options.type === Boolean && prop.raw === '' ? true : _.toBoolean(_.toNumber(prop.raw)) _.initProp(vm, prop, value) } } } } /***/ }, /* 13 */ /***/ function(module, exports, __webpack_require__) { var Cache = __webpack_require__(14) var config = __webpack_require__(6) var dirParser = __webpack_require__(15) var regexEscapeRE = /[-.*+?^${}()|[\]\/\\]/g var cache, tagRE, htmlRE, firstChar, lastChar /** * Escape a string so it can be used in a RegExp * constructor. * * @param {String} str */ function escapeRegex (str) { return str.replace(regexEscapeRE, '\\$&') } /** * Compile the interpolation tag regex. * * @return {RegExp} */ function compileRegex () { config._delimitersChanged = false var open = config.delimiters[0] var close = config.delimiters[1] firstChar = open.charAt(0) lastChar = close.charAt(close.length - 1) var firstCharRE = escapeRegex(firstChar) var lastCharRE = escapeRegex(lastChar) var openRE = escapeRegex(open) var closeRE = escapeRegex(close) tagRE = new RegExp( firstCharRE + '?' + openRE + '(.+?)' + closeRE + lastCharRE + '?', 'g' ) htmlRE = new RegExp( '^' + firstCharRE + openRE + '.*' + closeRE + lastCharRE + '$' ) // reset cache cache = new Cache(1000) } /** * Parse a template text string into an array of tokens. * * @param {String} text * @return {Array<Object> | null} * - {String} type * - {String} value * - {Boolean} [html] * - {Boolean} [oneTime] */ exports.parse = function (text) { if (config._delimitersChanged) { compileRegex() } var hit = cache.get(text) if (hit) { return hit } text = text.replace(/\n/g, '') if (!tagRE.test(text)) { return null } var tokens = [] var lastIndex = tagRE.lastIndex = 0 var match, index, value, first, oneTime, twoWay /* eslint-disable no-cond-assign */ while (match = tagRE.exec(text)) { /* eslint-enable no-cond-assign */ index = match.index // push text token if (index > lastIndex) { tokens.push({ value: text.slice(lastIndex, index) }) } // tag token first = match[1].charCodeAt(0) oneTime = first === 42 // * twoWay = first === 64 // @ value = oneTime || twoWay ? match[1].slice(1) : match[1] tokens.push({ tag: true, value: value.trim(), html: htmlRE.test(match[0]), oneTime: oneTime, twoWay: twoWay }) lastIndex = index + match[0].length } if (lastIndex < text.length) { tokens.push({ value: text.slice(lastIndex) }) } cache.put(text, tokens) return tokens } /** * Format a list of tokens into an expression. * e.g. tokens parsed from 'a {{b}} c' can be serialized * into one single expression as '"a " + b + " c"'. * * @param {Array} tokens * @param {Vue} [vm] * @return {String} */ exports.tokensToExp = function (tokens, vm) { return tokens.length > 1 ? tokens.map(function (token) { return formatToken(token, vm) }).join('+') : formatToken(tokens[0], vm, true) } /** * Format a single token. * * @param {Object} token * @param {Vue} [vm] * @param {Boolean} single * @return {String} */ function formatToken (token, vm, single) { return token.tag ? vm && token.oneTime ? '"' + vm.$eval(token.value) + '"' : inlineFilters(token.value, single) : '"' + token.value + '"' } /** * For an attribute with multiple interpolation tags, * e.g. attr="some-{{thing | filter}}", in order to combine * the whole thing into a single watchable expression, we * have to inline those filters. This function does exactly * that. This is a bit hacky but it avoids heavy changes * to directive parser and watcher mechanism. * * @param {String} exp * @param {Boolean} single * @return {String} */ var filterRE = /[^|]\|[^|]/ function inlineFilters (exp, single) { if (!filterRE.test(exp)) { return single ? exp : '(' + exp + ')' } else { var dir = dirParser.parse(exp)[0] if (!dir.filters) { return '(' + exp + ')' } else { return 'this._applyFilters(' + dir.expression + // value ',null,' + // oldValue (null for read) JSON.stringify(dir.filters) + // filter descriptors ',false)' // write? } } } /***/ }, /* 14 */ /***/ function(module, exports, __webpack_require__) { /** * A doubly linked list-based Least Recently Used (LRU) * cache. Will keep most recently used items while * discarding least recently used items when its limit is * reached. This is a bare-bone version of * Rasmus Andersson's js-lru: * * https://github.com/rsms/js-lru * * @param {Number} limit * @constructor */ function Cache (limit) { this.size = 0 this.limit = limit this.head = this.tail = undefined this._keymap = {} } var p = Cache.prototype /** * Put <value> into the cache associated with <key>. * Returns the entry which was removed to make room for * the new entry. Otherwise undefined is returned. * (i.e. if there was enough room already). * * @param {String} key * @param {*} value * @return {Entry|undefined} */ p.put = function (key, value) { var entry = { key: key, value: value } this._keymap[key] = entry if (this.tail) { this.tail.newer = entry entry.older = this.tail } else { this.head = entry } this.tail = entry if (this.size === this.limit) { return this.shift() } else { this.size++ } } /** * Purge the least recently used (oldest) entry from the * cache. Returns the removed entry or undefined if the * cache was empty. */ p.shift = function () { var entry = this.head if (entry) { this.head = this.head.newer this.head.older = undefined entry.newer = entry.older = undefined this._keymap[entry.key] = undefined } return entry } /** * Get and register recent use of <key>. Returns the value * associated with <key> or undefined if not in cache. * * @param {String} key * @param {Boolean} returnEntry * @return {Entry|*} */ p.get = function (key, returnEntry) { var entry = this._keymap[key] if (entry === undefined) return if (entry === this.tail) { return returnEntry ? entry : entry.value } // HEAD--------------TAIL // <.older .newer> // <--- add direction -- // A B C <D> E if (entry.newer) { if (entry === this.head) { this.head = entry.newer } entry.newer.older = entry.older // C <-- E. } if (entry.older) { entry.older.newer = entry.newer // C. --> E } entry.newer = undefined // D --x entry.older = this.tail // D. --> E if (this.tail) { this.tail.newer = entry // E. <-- D } this.tail = entry return returnEntry ? entry : entry.value } module.exports = Cache /***/ }, /* 15 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var Cache = __webpack_require__(14) var cache = new Cache(1000) var argRE = /^[^\{\?]+$|^'[^']*'$|^"[^"]*"$/ var filterTokenRE = /[^\s'"]+|'[^']+'|"[^"]+"/g var reservedArgRE = /^in$|^-?\d+/ /** * Parser state */ var str var c, i, l var inSingle var inDouble var curly var square var paren var begin var argIndex var dirs var dir var lastFilterIndex var arg /** * Push a directive object into the result Array */ function pushDir () { dir.raw = str.slice(begin, i).trim() if (dir.expression === undefined) { dir.expression = str.slice(argIndex, i).trim() } else if (lastFilterIndex !== begin) { pushFilter() } if (i === 0 || dir.expression) { dirs.push(dir) } } /** * Push a filter to the current directive object */ function pushFilter () { var exp = str.slice(lastFilterIndex, i).trim() var filter if (exp) { filter = {} var tokens = exp.match(filterTokenRE) filter.name = tokens[0] if (tokens.length > 1) { filter.args = tokens.slice(1).map(processFilterArg) } } if (filter) { (dir.filters = dir.filters || []).push(filter) } lastFilterIndex = i + 1 } /** * Check if an argument is dynamic and strip quotes. * * @param {String} arg * @return {Object} */ function processFilterArg (arg) { var stripped = reservedArgRE.test(arg) ? arg : _.stripQuotes(arg) return { value: stripped || arg, dynamic: !stripped } } /** * Parse a directive string into an Array of AST-like * objects representing directives. * * Example: * * "click: a = a + 1 | uppercase" will yield: * { * arg: 'click', * expression: 'a = a + 1', * filters: [ * { name: 'uppercase', args: null } * ] * } * * @param {String} str * @return {Array<Object>} */ exports.parse = function (s) { var hit = cache.get(s) if (hit) { return hit } // reset parser state str = s inSingle = inDouble = false curly = square = paren = begin = argIndex = 0 lastFilterIndex = 0 dirs = [] dir = {} arg = null for (i = 0, l = str.length; i < l; i++) { c = str.charCodeAt(i) if (inSingle) { // check single quote if (c === 0x27) inSingle = !inSingle } else if (inDouble) { // check double quote if (c === 0x22) inDouble = !inDouble } else if ( c === 0x2C && // comma !paren && !curly && !square ) { // reached the end of a directive pushDir() // reset & skip the comma dir = {} begin = argIndex = lastFilterIndex = i + 1 } else if ( c === 0x3A && // colon !dir.expression && !dir.arg ) { // argument arg = str.slice(begin, i).trim() // test for valid argument here // since we may have caught stuff like first half of // an object literal or a ternary expression. if (argRE.test(arg)) { argIndex = i + 1 dir.arg = _.stripQuotes(arg) || arg } } else if ( c === 0x7C && // pipe str.charCodeAt(i + 1) !== 0x7C && str.charCodeAt(i - 1) !== 0x7C ) { if (dir.expression === undefined) { // first filter, end of expression lastFilterIndex = i + 1 dir.expression = str.slice(argIndex, i).trim() } else { // already has filter pushFilter() } } else { switch (c) { case 0x22: inDouble = true; break // " case 0x27: inSingle = true; break // ' case 0x28: paren++; break // ( case 0x29: paren--; break // ) case 0x5B: square++; break // [ case 0x5D: square--; break // ] case 0x7B: curly++; break // { case 0x7D: curly--; break // } } } } if (i === 0 || begin !== i) { pushDir() } cache.put(s, dirs) return dirs } /***/ }, /* 16 */ /***/ function(module, exports, __webpack_require__) { // NOTE: the prop internal directive is compiled and linked // during _initScope(), before the created hook is called. // The purpose is to make the initial prop values available // inside `created` hooks and `data` functions. var _ = __webpack_require__(1) var Watcher = __webpack_require__(17) var bindingModes = __webpack_require__(6)._propBindingModes module.exports = { bind: function () { var child = this.vm var parent = child._context // passed in from compiler directly var prop = this._descriptor var childKey = prop.path var parentKey = prop.parentPath // simple lock to avoid circular updates. // without this it would stabilize too, but this makes // sure it doesn't cause other watchers to re-evaluate. var locked = false function withLock (fn) { return function (val) { if (!locked) { locked = true fn(val) _.nextTick(function () { locked = false }) } } } this.parentWatcher = new Watcher( parent, parentKey, withLock(function (val) { if (_.assertProp(prop, val)) { child[childKey] = val } }) ) // set the child initial value. // !!! We need to set it also on raw data here, because // props are initialized before data is fully observed var value = this.parentWatcher.value if (childKey === '$data') { child._data = value } else { _.initProp(child, prop, value) } // only setup two-way binding if this is not a one-way // binding. if (prop.mode === bindingModes.TWO_WAY) { // important: defer the child watcher creation until // the created hook (after data observation) var self = this child.$once('hook:created', function () { self.childWatcher = new Watcher( child, childKey, withLock(function (val) { parent.$set(parentKey, val) }) ) }) } }, unbind: function () { if (this.parentWatcher) { this.parentWatcher.teardown() } if (this.childWatcher) { this.childWatcher.teardown() } } } /***/ }, /* 17 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var config = __webpack_require__(6) var Observer = __webpack_require__(18) var expParser = __webpack_require__(22) var batcher = __webpack_require__(24) var uid = 0 /** * A watcher parses an expression, collects dependencies, * and fires callback when the expression value changes. * This is used for both the $watch() api and directives. * * @param {Vue} vm * @param {String} expression * @param {Function} cb * @param {Object} options * - {Array} filters * - {Boolean} twoWay * - {Boolean} deep * - {Boolean} user * - {Function} [preProcess] * @constructor */ function Watcher (vm, expOrFn, cb, options) { var isFn = typeof expOrFn === 'function' this.vm = vm vm._watchers.push(this) this.expression = isFn ? '' : expOrFn this.cb = cb this.id = ++uid // uid for batching this.active = true options = options || {} this.deep = !!options.deep this.user = !!options.user this.twoWay = !!options.twoWay this.filters = options.filters this.preProcess = options.preProcess this.deps = [] this.newDeps = [] // parse expression for getter/setter if (isFn) { this.getter = expOrFn this.setter = undefined } else { var res = expParser.parse(expOrFn, options.twoWay) this.getter = res.get this.setter = res.set } this.value = this.get() // state for avoiding false triggers for deep and Array // watchers during vm._digest() this.queued = this.shallow = false } var p = Watcher.prototype /** * Add a dependency to this directive. * * @param {Dep} dep */ p.addDep = function (dep) { var newDeps = this.newDeps var old = this.deps if (_.indexOf(newDeps, dep) < 0) { newDeps.push(dep) var i = _.indexOf(old, dep) if (i < 0) { dep.addSub(this) } else { old[i] = null } } } /** * Evaluate the getter, and re-collect dependencies. */ p.get = function () { this.beforeGet() var vm = this.vm var value try { value = this.getter.call(vm, vm) } catch (e) { if (config.warnExpressionErrors) { _.warn( 'Error when evaluating expression "' + this.expression + '". ' + (config.debug ? '' : 'Turn on debug mode to see stack trace.' ), e ) } } // "touch" every property so they are all tracked as // dependencies for deep watching if (this.deep) { traverse(value) } if (this.preProcess) { value = this.preProcess(value) } if (this.filters) { value = vm._applyFilters(value, null, this.filters, false) } this.afterGet() return value } /** * Set the corresponding value with the setter. * * @param {*} value */ p.set = function (value) { var vm = this.vm if (this.filters) { value = vm._applyFilters( value, this.value, this.filters, true) } try { this.setter.call(vm, vm, value) } catch (e) { if (config.warnExpressionErrors) { _.warn( 'Error when evaluating setter "' + this.expression + '"', e ) } } } /** * Prepare for dependency collection. */ p.beforeGet = function () { Observer.setTarget(this) } /** * Clean up for dependency collection. */ p.afterGet = function () { Observer.setTarget(null) var i = this.deps.length while (i--) { var dep = this.deps[i] if (dep) { dep.removeSub(this) } } this.deps = this.newDeps this.newDeps = [] } /** * Subscriber interface. * Will be called when a dependency changes. * * @param {Boolean} shallow */ p.update = function (shallow) { if (!config.async) { this.run() } else { // if queued, only overwrite shallow with non-shallow, // but not the other way around. this.shallow = this.queued ? shallow ? this.shallow : false : !!shallow this.queued = true batcher.push(this) } } /** * Batcher job interface. * Will be called by the batcher. */ p.run = function () { if (this.active) { var value = this.get() if ( value !== this.value || // Deep watchers and Array watchers should fire even // when the value is the same, because the value may // have mutated; but only do so if this is a // non-shallow update (caused by a vm digest). ((_.isArray(value) || this.deep) && !this.shallow) ) { var oldValue = this.value this.value = value this.cb(value, oldValue) } this.queued = this.shallow = false } } /** * Remove self from all dependencies' subcriber list. */ p.teardown = function () { if (this.active) { // remove self from vm's watcher list // we can skip this if the vm if being destroyed // which can improve teardown performance. if (!this.vm._isBeingDestroyed) { this.vm._watchers.$remove(this) } var i = this.deps.length while (i--) { this.deps[i].removeSub(this) } this.active = false this.vm = this.cb = this.value = null } } /** * Recrusively traverse an object to evoke all converted * getters, so that every nested property inside the object * is collected as a "deep" dependency. * * @param {Object} obj */ function traverse (obj) { var key, val, i for (key in obj) { val = obj[key] if (_.isArray(val)) { i = val.length while (i--) traverse(val[i]) } else if (_.isObject(val)) { traverse(val) } } } module.exports = Watcher /***/ }, /* 18 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var config = __webpack_require__(6) var Dep = __webpack_require__(19) var arrayMethods = __webpack_require__(20) var arrayKeys = Object.getOwnPropertyNames(arrayMethods) __webpack_require__(21) /** * Observer class that are attached to each observed * object. Once attached, the observer converts target * object's property keys into getter/setters that * collect dependencies and dispatches updates. * * @param {Array|Object} value * @constructor */ function Observer (value) { this.value = value this.active = true this.deps = [] _.define(value, '__ob__', this) if (_.isArray(value)) { var augment = config.proto && _.hasProto ? protoAugment : copyAugment augment(value, arrayMethods, arrayKeys) this.observeArray(value) } else { this.walk(value) } } // Static methods /** * Attempt to create an observer instance for a value, * returns the new observer if successfully observed, * or the existing observer if the value already has one. * * @param {*} value * @param {Vue} [vm] * @return {Observer|undefined} * @static */ Observer.create = function (value, vm) { var ob if ( value && value.hasOwnProperty('__ob__') && value.__ob__ instanceof Observer ) { ob = value.__ob__ } else if ( _.isObject(value) && !Object.isFrozen(value) && !value._isVue ) { ob = new Observer(value) } if (ob && vm) { ob.addVm(vm) } return ob } /** * Set the target watcher that is currently being evaluated. * * @param {Watcher} watcher */ Observer.setTarget = function (watcher) { Dep.target = watcher } // Instance methods var p = Observer.prototype /** * Walk through each property and convert them into * getter/setters. This method should only be called when * value type is Object. Properties prefixed with `$` or `_` * and accessor properties are ignored. * * @param {Object} obj */ p.walk = function (obj) { var keys = Object.keys(obj) var i = keys.length var key, prefix while (i--) { key = keys[i] prefix = key.charCodeAt(0) if (prefix !== 0x24 && prefix !== 0x5F) { // skip $ or _ this.convert(key, obj[key]) } } } /** * Try to carete an observer for a child value, * and if value is array, link dep to the array. * * @param {*} val * @return {Dep|undefined} */ p.observe = function (val) { return Observer.create(val) } /** * Observe a list of Array items. * * @param {Array} items */ p.observeArray = function (items) { var i = items.length while (i--) { this.observe(items[i]) } } /** * Convert a property into getter/setter so we can emit * the events when the property is accessed/changed. * * @param {String} key * @param {*} val */ p.convert = function (key, val) { var ob = this var childOb = ob.observe(val) var dep = new Dep() if (childOb) { childOb.deps.push(dep) } Object.defineProperty(ob.value, key, { enumerable: true, configurable: true, get: function () { if (ob.active) { dep.depend() } return val }, set: function (newVal) { if (newVal === val) return // remove dep from old value var oldChildOb = val && val.__ob__ if (oldChildOb) { oldChildOb.deps.$remove(dep) } val = newVal // add dep to new value var newChildOb = ob.observe(newVal) if (newChildOb) { newChildOb.deps.push(dep) } dep.notify() } }) } /** * Notify change on all self deps on an observer. * This is called when a mutable value mutates. e.g. * when an Array's mutating methods are called, or an * Object's $add/$delete are called. */ p.notify = function () { var deps = this.deps for (var i = 0, l = deps.length; i < l; i++) { deps[i].notify() } } /** * Add an owner vm, so that when $add/$delete mutations * happen we can notify owner vms to proxy the keys and * digest the watchers. This is only called when the object * is observed as an instance's root $data. * * @param {Vue} vm */ p.addVm = function (vm) { (this.vms || (this.vms = [])).push(vm) } /** * Remove an owner vm. This is called when the object is * swapped out as an instance's $data object. * * @param {Vue} vm */ p.removeVm = function (vm) { this.vms.$remove(vm) } // helpers /** * Augment an target Object or Array by intercepting * the prototype chain using __proto__ * * @param {Object|Array} target * @param {Object} proto */ function protoAugment (target, src) { target.__proto__ = src } /** * Augment an target Object or Array by defining * hidden properties. * * @param {Object|Array} target * @param {Object} proto */ function copyAugment (target, src, keys) { var i = keys.length var key while (i--) { key = keys[i] _.define(target, key, src[key]) } } module.exports = Observer /***/ }, /* 19 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) /** * A dep is an observable that can have multiple * directives subscribing to it. * * @constructor */ function Dep () { this.subs = [] } // the current target watcher being evaluated. // this is globally unique because there could be only one // watcher being evaluated at any time. Dep.target = null var p = Dep.prototype /** * Add a directive subscriber. * * @param {Directive} sub */ p.addSub = function (sub) { this.subs.push(sub) } /** * Remove a directive subscriber. * * @param {Directive} sub */ p.removeSub = function (sub) { this.subs.$remove(sub) } /** * Add self as a dependency to the target watcher. */ p.depend = function () { if (Dep.target) { Dep.target.addDep(this) } } /** * Notify all subscribers of a new value. */ p.notify = function () { // stablize the subscriber list first var subs = _.toArray(this.subs) for (var i = 0, l = subs.length; i < l; i++) { subs[i].update() } } module.exports = Dep /***/ }, /* 20 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var arrayProto = Array.prototype var arrayMethods = Object.create(arrayProto) /** * Intercept mutating methods and emit events */ ;[ 'push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse' ] .forEach(function (method) { // cache original method var original = arrayProto[method] _.define(arrayMethods, method, function mutator () { // avoid leaking arguments: // http://jsperf.com/closure-with-arguments var i = arguments.length var args = new Array(i) while (i--) { args[i] = arguments[i] } var result = original.apply(this, args) var ob = this.__ob__ var inserted switch (method) { case 'push': inserted = args break case 'unshift': inserted = args break case 'splice': inserted = args.slice(2) break } if (inserted) ob.observeArray(inserted) // notify change ob.notify() return result }) }) /** * Swap the element at the given index with a new value * and emits corresponding event. * * @param {Number} index * @param {*} val * @return {*} - replaced element */ _.define( arrayProto, '$set', function $set (index, val) { if (index >= this.length) { this.length = index + 1 } return this.splice(index, 1, val)[0] } ) /** * Convenience method to remove the element at given index. * * @param {Number} index * @param {*} val */ _.define( arrayProto, '$remove', function $remove (index) { /* istanbul ignore if */ if (!this.length) return if (typeof index !== 'number') { index = _.indexOf(this, index) } if (index > -1) { return this.splice(index, 1) } } ) module.exports = arrayMethods /***/ }, /* 21 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var objProto = Object.prototype /** * Add a new property to an observed object * and emits corresponding event * * @param {String} key * @param {*} val * @public */ _.define( objProto, '$add', function $add (key, val) { if (this.hasOwnProperty(key)) return var ob = this.__ob__ if (!ob || _.isReserved(key)) { this[key] = val return } ob.convert(key, val) ob.notify() if (ob.vms) { var i = ob.vms.length while (i--) { var vm = ob.vms[i] vm._proxy(key) vm._digest() } } } ) /** * Set a property on an observed object, calling add to * ensure the property is observed. * * @param {String} key * @param {*} val * @public */ _.define( objProto, '$set', function $set (key, val) { this.$add(key, val) this[key] = val } ) /** * Deletes a property from an observed object * and emits corresponding event * * @param {String} key * @public */ _.define( objProto, '$delete', function $delete (key) { if (!this.hasOwnProperty(key)) return delete this[key] var ob = this.__ob__ if (!ob || _.isReserved(key)) { return } ob.notify() if (ob.vms) { var i = ob.vms.length while (i--) { var vm = ob.vms[i] vm._unproxy(key) vm._digest() } } } ) /***/ }, /* 22 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var Path = __webpack_require__(23) var Cache = __webpack_require__(14) var expressionCache = new Cache(1000) var allowedKeywords = 'Math,Date,this,true,false,null,undefined,Infinity,NaN,' + 'isNaN,isFinite,decodeURI,decodeURIComponent,encodeURI,' + 'encodeURIComponent,parseInt,parseFloat' var allowedKeywordsRE = new RegExp('^(' + allowedKeywords.replace(/,/g, '\\b|') + '\\b)') // keywords that don't make sense inside expressions var improperKeywords = 'break,case,class,catch,const,continue,debugger,default,' + 'delete,do,else,export,extends,finally,for,function,if,' + 'import,in,instanceof,let,return,super,switch,throw,try,' + 'var,while,with,yield,enum,await,implements,package,' + 'proctected,static,interface,private,public' var improperKeywordsRE = new RegExp('^(' + improperKeywords.replace(/,/g, '\\b|') + '\\b)') var wsRE = /\s/g var newlineRE = /\n/g var saveRE = /[\{,]\s*[\w\$_]+\s*:|('[^']*'|"[^"]*")|new |typeof |void /g var restoreRE = /"(\d+)"/g var pathTestRE = /^[A-Za-z_$][\w$]*(\.[A-Za-z_$][\w$]*|\['.*?'\]|\[".*?"\]|\[\d+\]|\[[A-Za-z_$][\w$]*\])*$/ var pathReplaceRE = /[^\w$\.]([A-Za-z_$][\w$]*(\.[A-Za-z_$][\w$]*|\['.*?'\]|\[".*?"\])*)/g var booleanLiteralRE = /^(true|false)$/ /** * Save / Rewrite / Restore * * When rewriting paths found in an expression, it is * possible for the same letter sequences to be found in * strings and Object literal property keys. Therefore we * remove and store these parts in a temporary array, and * restore them after the path rewrite. */ var saved = [] /** * Save replacer * * The save regex can match two possible cases: * 1. An opening object literal * 2. A string * If matched as a plain string, we need to escape its * newlines, since the string needs to be preserved when * generating the function body. * * @param {String} str * @param {String} isString - str if matched as a string * @return {String} - placeholder with index */ function save (str, isString) { var i = saved.length saved[i] = isString ? str.replace(newlineRE, '\\n') : str return '"' + i + '"' } /** * Path rewrite replacer * * @param {String} raw * @return {String} */ function rewrite (raw) { var c = raw.charAt(0) var path = raw.slice(1) if (allowedKeywordsRE.test(path)) { return raw } else { path = path.indexOf('"') > -1 ? path.replace(restoreRE, restore) : path return c + 'scope.' + path } } /** * Restore replacer * * @param {String} str * @param {String} i - matched save index * @return {String} */ function restore (str, i) { return saved[i] } /** * Rewrite an expression, prefixing all path accessors with * `scope.` and generate getter/setter functions. * * @param {String} exp * @param {Boolean} needSet * @return {Function} */ function compileExpFns (exp, needSet) { if (improperKeywordsRE.test(exp)) { _.warn( 'Avoid using reserved keywords in expression: ' + exp ) } // reset state saved.length = 0 // save strings and object literal keys var body = exp .replace(saveRE, save) .replace(wsRE, '') // rewrite all paths // pad 1 space here becaue the regex matches 1 extra char body = (' ' + body) .replace(pathReplaceRE, rewrite) .replace(restoreRE, restore) var getter = makeGetter(body) if (getter) { return { get: getter, body: body, set: needSet ? makeSetter(body) : null } } } /** * Compile getter setters for a simple path. * * @param {String} exp * @return {Function} */ function compilePathFns (exp) { var getter, path if (exp.indexOf('[') < 0) { // really simple path path = exp.split('.') path.raw = exp getter = Path.compileGetter(path) } else { // do the real parsing path = Path.parse(exp) getter = path.get } return { get: getter, // always generate setter for simple paths set: function (obj, val) { Path.set(obj, path, val) } } } /** * Build a getter function. Requires eval. * * We isolate the try/catch so it doesn't affect the * optimization of the parse function when it is not called. * * @param {String} body * @return {Function|undefined} */ function makeGetter (body) { try { return new Function('scope', 'return ' + body + ';') } catch (e) { _.warn( 'Invalid expression. ' + 'Generated function body: ' + body ) } } /** * Build a setter function. * * This is only needed in rare situations like "a[b]" where * a settable path requires dynamic evaluation. * * This setter function may throw error when called if the * expression body is not a valid left-hand expression in * assignment. * * @param {String} body * @return {Function|undefined} */ function makeSetter (body) { try { return new Function('scope', 'value', body + '=value;') } catch (e) { _.warn('Invalid setter function body: ' + body) } } /** * Check for setter existence on a cache hit. * * @param {Function} hit */ function checkSetter (hit) { if (!hit.set) { hit.set = makeSetter(hit.body) } } /** * Parse an expression into re-written getter/setters. * * @param {String} exp * @param {Boolean} needSet * @return {Function} */ exports.parse = function (exp, needSet) { exp = exp.trim() // try cache var hit = expressionCache.get(exp) if (hit) { if (needSet) { checkSetter(hit) } return hit } // we do a simple path check to optimize for them. // the check fails valid paths with unusal whitespaces, // but that's too rare and we don't care. // also skip boolean literals and paths that start with // global "Math" var res = exports.isSimplePath(exp) ? compilePathFns(exp) : compileExpFns(exp, needSet) expressionCache.put(exp, res) return res } /** * Check if an expression is a simple path. * * @param {String} exp * @return {Boolean} */ exports.isSimplePath = function (exp) { return pathTestRE.test(exp) && // don't treat true/false as paths !booleanLiteralRE.test(exp) && // Math constants e.g. Math.PI, Math.E etc. exp.slice(0, 5) !== 'Math.' } /***/ }, /* 23 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var Cache = __webpack_require__(14) var pathCache = new Cache(1000) var identRE = exports.identRE = /^[$_a-zA-Z]+[\w$]*$/ /** * Path-parsing algorithm scooped from Polymer/observe-js */ var pathStateMachine = { 'beforePath': { 'ws': ['beforePath'], 'ident': ['inIdent', 'append'], '[': ['beforeElement'], 'eof': ['afterPath'] }, 'inPath': { 'ws': ['inPath'], '.': ['beforeIdent'], '[': ['beforeElement'], 'eof': ['afterPath'] }, 'beforeIdent': { 'ws': ['beforeIdent'], 'ident': ['inIdent', 'append'] }, 'inIdent': { 'ident': ['inIdent', 'append'], '0': ['inIdent', 'append'], 'number': ['inIdent', 'append'], 'ws': ['inPath', 'push'], '.': ['beforeIdent', 'push'], '[': ['beforeElement', 'push'], 'eof': ['afterPath', 'push'], ']': ['inPath', 'push'] }, 'beforeElement': { 'ws': ['beforeElement'], '0': ['afterZero', 'append'], 'number': ['inIndex', 'append'], "'": ['inSingleQuote', 'append', ''], '"': ['inDoubleQuote', 'append', ''], 'ident': ['inIdent', 'append', '*'] }, 'afterZero': { 'ws': ['afterElement', 'push'], ']': ['inPath', 'push'] }, 'inIndex': { '0': ['inIndex', 'append'], 'number': ['inIndex', 'append'], 'ws': ['afterElement'], ']': ['inPath', 'push'] }, 'inSingleQuote': { "'": ['afterElement'], 'eof': 'error', 'else': ['inSingleQuote', 'append'] }, 'inDoubleQuote': { '"': ['afterElement'], 'eof': 'error', 'else': ['inDoubleQuote', 'append'] }, 'afterElement': { 'ws': ['afterElement'], ']': ['inPath', 'push'] } } function noop () {} /** * Determine the type of a character in a keypath. * * @param {Char} ch * @return {String} type */ function getPathCharType (ch) { if (ch === undefined) { return 'eof' } var code = ch.charCodeAt(0) switch (code) { case 0x5B: // [ case 0x5D: // ] case 0x2E: // . case 0x22: // " case 0x27: // ' case 0x30: // 0 return ch case 0x5F: // _ case 0x24: // $ return 'ident' case 0x20: // Space case 0x09: // Tab case 0x0A: // Newline case 0x0D: // Return case 0xA0: // No-break space case 0xFEFF: // Byte Order Mark case 0x2028: // Line Separator case 0x2029: // Paragraph Separator return 'ws' } // a-z, A-Z if ( (code >= 0x61 && code <= 0x7A) || (code >= 0x41 && code <= 0x5A) ) { return 'ident' } // 1-9 if (code >= 0x31 && code <= 0x39) { return 'number' } return 'else' } /** * Parse a string path into an array of segments * Todo implement cache * * @param {String} path * @return {Array|undefined} */ function parsePath (path) { var keys = [] var index = -1 var mode = 'beforePath' var c, newChar, key, type, transition, action, typeMap var actions = { push: function () { if (key === undefined) { return } keys.push(key) key = undefined }, append: function () { if (key === undefined) { key = newChar } else { key += newChar } } } function maybeUnescapeQuote () { var nextChar = path[index + 1] if ((mode === 'inSingleQuote' && nextChar === "'") || (mode === 'inDoubleQuote' && nextChar === '"')) { index++ newChar = nextChar actions.append() return true } } while (mode) { index++ c = path[index] if (c === '\\' && maybeUnescapeQuote()) { continue } type = getPathCharType(c) typeMap = pathStateMachine[mode] transition = typeMap[type] || typeMap['else'] || 'error' if (transition === 'error') { return // parse error } mode = transition[0] action = actions[transition[1]] || noop newChar = transition[2] newChar = newChar === undefined ? c : newChar === '*' ? newChar + c : newChar action() if (mode === 'afterPath') { keys.raw = path return keys } } } /** * Format a accessor segment based on its type. * * @param {String} key * @return {Boolean} */ function formatAccessor (key) { if (identRE.test(key)) { // identifier return '.' + key } else if (+key === key >>> 0) { // bracket index return '[' + key + ']' } else if (key.charAt(0) === '*') { return '[o' + formatAccessor(key.slice(1)) + ']' } else { // bracket string return '["' + key.replace(/"/g, '\\"') + '"]' } } /** * Compiles a getter function with a fixed path. * The fixed path getter supresses errors. * * @param {Array} path * @return {Function} */ exports.compileGetter = function (path) { var body = 'return o' + path.map(formatAccessor).join('') return new Function('o', body) } /** * External parse that check for a cache hit first * * @param {String} path * @return {Array|undefined} */ exports.parse = function (path) { var hit = pathCache.get(path) if (!hit) { hit = parsePath(path) if (hit) { hit.get = exports.compileGetter(hit) pathCache.put(path, hit) } } return hit } /** * Get from an object from a path string * * @param {Object} obj * @param {String} path */ exports.get = function (obj, path) { path = exports.parse(path) if (path) { return path.get(obj) } } /** * Set on an object from a path * * @param {Object} obj * @param {String | Array} path * @param {*} val */ exports.set = function (obj, path, val) { var original = obj if (typeof path === 'string') { path = exports.parse(path) } if (!path || !_.isObject(obj)) { return false } var last, key for (var i = 0, l = path.length; i < l; i++) { last = obj key = path[i] if (key.charAt(0) === '*') { key = original[key.slice(1)] } if (i < l - 1) { obj = obj[key] if (!_.isObject(obj)) { obj = {} last.$add(key, obj) warnNonExistent(path) } } else { if (_.isArray(obj)) { obj.$set(key, val) } else if (key in obj) { obj[key] = val } else { obj.$add(key, val) warnNonExistent(path) } } } return true } function warnNonExistent (path) { _.warn( 'You are setting a non-existent path "' + path.raw + '" ' + 'on a vm instance. Consider pre-initializing the property ' + 'with the "data" option for more reliable reactivity ' + 'and better performance.' ) } /***/ }, /* 24 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var config = __webpack_require__(6) // we have two separate queues: one for directive updates // and one for user watcher registered via $watch(). // we want to guarantee directive updates to be called // before user watchers so that when user watchers are // triggered, the DOM would have already been in updated // state. var queue = [] var userQueue = [] var has = {} var waiting = false var flushing = false var internalQueueDepleted = false /** * Reset the batcher's state. */ function reset () { queue = [] userQueue = [] has = {} waiting = flushing = internalQueueDepleted = false } /** * Flush both queues and run the jobs. */ function flush () { flushing = true run(queue) internalQueueDepleted = true run(userQueue) reset() } /** * Run the jobs in a single queue. * * @param {Array} queue */ function run (queue) { // do not cache length because more jobs might be pushed // as we run existing jobs for (var i = 0; i < queue.length; i++) { queue[i].run() } } /** * Push a job into the job queue. * Jobs with duplicate IDs will be skipped unless it's * pushed when the queue is being flushed. * * @param {Object} job * properties: * - {String|Number} id * - {Function} run */ exports.push = function (job) { var id = job.id if (!id || !has[id] || flushing) { if (!has[id]) { has[id] = 1 } else { has[id]++ // detect possible infinite update loops if (has[id] > config._maxUpdateCount) { _.warn( 'You may have an infinite update loop for the ' + 'watcher with expression: "' + job.expression + '".' ) return } } // A user watcher callback could trigger another // directive update during the flushing; at that time // the directive queue would already have been run, so // we call that update immediately as it is pushed. if (flushing && !job.user && internalQueueDepleted) { job.run() return } ;(job.user ? userQueue : queue).push(job) if (!waiting) { waiting = true _.nextTick(flush) } } } /***/ }, /* 25 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var Cache = __webpack_require__(14) var templateCache = new Cache(1000) var idSelectorCache = new Cache(1000) var map = { _default: [0, '', ''], legend: [1, '<fieldset>', '</fieldset>'], tr: [2, '<table><tbody>', '</tbody></table>'], col: [ 2, '<table><tbody></tbody><colgroup>', '</colgroup></table>' ] } 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.g = map.defs = map.symbol = map.use = map.image = 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" ' + 'xmlns:xlink="http://www.w3.org/1999/xlink" ' + 'xmlns:ev="http://www.w3.org/2001/xml-events"' + 'version="1.1">', '</svg>' ] var tagRE = /<([\w:]+)/ var entityRE = /&\w+;/ /** * Convert a string template to a DocumentFragment. * Determines correct wrapping by tag types. Wrapping * strategy found in jQuery & component/domify. * * @param {String} templateString * @return {DocumentFragment} */ function stringToFragment (templateString) { // try a cache hit first var hit = templateCache.get(templateString) if (hit) { return hit } var frag = document.createDocumentFragment() var tagMatch = templateString.match(tagRE) var entityMatch = entityRE.test(templateString) if (!tagMatch && !entityMatch) { // text only, return a single text node. frag.appendChild( document.createTextNode(templateString) ) } else { var tag = tagMatch && tagMatch[1] var wrap = map[tag] || map._default var depth = wrap[0] var prefix = wrap[1] var suffix = wrap[2] var node = document.createElement('div') node.innerHTML = prefix + templateString.trim() + suffix while (depth--) { node = node.lastChild } var child /* eslint-disable no-cond-assign */ while (child = node.firstChild) { /* eslint-enable no-cond-assign */ frag.appendChild(child) } } templateCache.put(templateString, frag) return frag } /** * Convert a template node to a DocumentFragment. * * @param {Node} node * @return {DocumentFragment} */ function nodeToFragment (node) { // if its a template tag and the browser supports it, // its content is already a document fragment. if ( _.isTemplate(node) && node.content instanceof DocumentFragment ) { return node.content } // script template if (node.tagName === 'SCRIPT') { return stringToFragment(node.textContent) } // normal node, clone it to avoid mutating the original var clone = exports.clone(node) var frag = document.createDocumentFragment() var child /* eslint-disable no-cond-assign */ while (child = clone.firstChild) { /* eslint-enable no-cond-assign */ frag.appendChild(child) } return frag } // Test for the presence of the Safari template cloning bug // https://bugs.webkit.org/show_bug.cgi?id=137755 var hasBrokenTemplate = _.inBrowser ? (function () { var a = document.createElement('div') a.innerHTML = '<template>1</template>' return !a.cloneNode(true).firstChild.innerHTML })() : false // Test for IE10/11 textarea placeholder clone bug var hasTextareaCloneBug = _.inBrowser ? (function () { var t = document.createElement('textarea') t.placeholder = 't' return t.cloneNode(true).value === 't' })() : false /** * 1. Deal with Safari cloning nested <template> bug by * manually cloning all template instances. * 2. Deal with IE10/11 textarea placeholder bug by setting * the correct value after cloning. * * @param {Element|DocumentFragment} node * @return {Element|DocumentFragment} */ exports.clone = function (node) { var res = node.cloneNode(true) var i, original, cloned /* istanbul ignore if */ if (hasBrokenTemplate) { original = node.querySelectorAll('template') if (original.length) { cloned = res.querySelectorAll('template') i = cloned.length while (i--) { cloned[i].parentNode.replaceChild( original[i].cloneNode(true), cloned[i] ) } } } /* istanbul ignore if */ if (hasTextareaCloneBug) { if (node.tagName === 'TEXTAREA') { res.value = node.value } else { original = node.querySelectorAll('textarea') if (original.length) { cloned = res.querySelectorAll('textarea') i = cloned.length while (i--) { cloned[i].value = original[i].value } } } } return res } /** * Process the template option and normalizes it into a * a DocumentFragment that can be used as a partial or a * instance template. * * @param {*} template * Possible values include: * - DocumentFragment object * - Node object of type Template * - id selector: '#some-template-id' * - template string: '<div><span>{{msg}}</span></div>' * @param {Boolean} clone * @param {Boolean} noSelector * @return {DocumentFragment|undefined} */ exports.parse = function (template, clone, noSelector) { var node, frag // if the template is already a document fragment, // do nothing if (template instanceof DocumentFragment) { return clone ? template.cloneNode(true) : template } if (typeof template === 'string') { // id selector if (!noSelector && template.charAt(0) === '#') { // id selector can be cached too frag = idSelectorCache.get(template) if (!frag) { node = document.getElementById(template.slice(1)) if (node) { frag = nodeToFragment(node) // save selector to cache idSelectorCache.put(template, frag) } } } else { // normal string template frag = stringToFragment(template) } } else if (template.nodeType) { // a direct node frag = nodeToFragment(template) } return frag && clone ? exports.clone(frag) : frag } /***/ }, /* 26 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var templateParser = __webpack_require__(25) module.exports = { isLiteral: true, /** * Setup. Two possible usages: * * - static: * v-component="comp" * * - dynamic: * v-component="{{currentView}}" */ bind: function () { if (!this.el.__vue__) { // create a ref anchor this.anchor = _.createAnchor('v-component') _.replace(this.el, this.anchor) // check keep-alive options. // If yes, instead of destroying the active vm when // hiding (v-if) or switching (dynamic literal) it, // we simply remove it from the DOM and save it in a // cache object, with its constructor id as the key. this.keepAlive = this._checkParam('keep-alive') != null // wait for event before insertion this.readyEvent = this._checkParam('wait-for') // check ref this.refID = _.attr(this.el, 'ref') if (this.keepAlive) { this.cache = {} } // check inline-template if (this._checkParam('inline-template') !== null) { // extract inline template as a DocumentFragment this.template = _.extractContent(this.el, true) } // component resolution related state this._pendingCb = this.ctorId = this.Ctor = null // if static, build right now. if (!this._isDynamicLiteral) { this.resolveCtor(this.expression, _.bind(this.initStatic, this)) } else { // check dynamic component params this.transMode = this._checkParam('transition-mode') } } else { _.warn( 'Do not create a component that only contains ' + 'a single other component - they will be mounted to ' + 'the same element and cause conflict. Wrap it with ' + 'an outer element.' ) } }, /** * Initialize a static component. */ initStatic: function () { var child = this.build() var anchor = this.anchor this.setCurrent(child) if (!this.readyEvent) { child.$before(anchor) } else { child.$once(this.readyEvent, function () { child.$before(anchor) }) } }, /** * Public update, called by the watcher in the dynamic * literal scenario, e.g. v-component="{{view}}" */ update: function (value) { this.setComponent(value) }, /** * Switch dynamic components. May resolve the component * asynchronously, and perform transition based on * specified transition mode. Accepts a few additional * arguments specifically for vue-router. * * @param {String} value * @param {Object} data * @param {Function} afterBuild * @param {Function} afterTransition */ setComponent: function (value, data, afterBuild, afterTransition) { this.invalidatePending() if (!value) { // just remove current this.unbuild(true) this.remove(this.childVM, afterTransition) this.unsetCurrent() } else { this.resolveCtor(value, _.bind(function () { this.unbuild(true) var newComponent = this.build(data) /* istanbul ignore if */ if (afterBuild) afterBuild(newComponent) var self = this if (this.readyEvent) { newComponent.$once(this.readyEvent, function () { self.transition(newComponent, afterTransition) }) } else { this.transition(newComponent, afterTransition) } }, this)) } }, /** * Resolve the component constructor to use when creating * the child vm. */ resolveCtor: function (id, cb) { var self = this this._pendingCb = _.cancellable(function (ctor) { self.ctorId = id self.Ctor = ctor cb() }) this.vm._resolveComponent(id, this._pendingCb) }, /** * When the component changes or unbinds before an async * constructor is resolved, we need to invalidate its * pending callback. */ invalidatePending: function () { if (this._pendingCb) { this._pendingCb.cancel() this._pendingCb = null } }, /** * Instantiate/insert a new child vm. * If keep alive and has cached instance, insert that * instance; otherwise build a new one and cache it. * * @param {Object} [data] * @return {Vue} - the created instance */ build: function (data) { if (this.keepAlive) { var cached = this.cache[this.ctorId] if (cached) { return cached } } if (this.Ctor) { var parent = this._host || this.vm var el = templateParser.clone(this.el) var child = parent.$addChild({ el: el, data: data, template: this.template, // if no inline-template, then the compiled // linker can be cached for better performance. _linkerCachable: !this.template, _asComponent: true, _isRouterView: this._isRouterView, _context: this.vm }, this.Ctor) if (this.keepAlive) { this.cache[this.ctorId] = child } return child } }, /** * Teardown the current child, but defers cleanup so * that we can separate the destroy and removal steps. * * @param {Boolean} defer */ unbuild: function (defer) { var child = this.childVM if (!child || this.keepAlive) { return } // the sole purpose of `deferCleanup` is so that we can // "deactivate" the vm right now and perform DOM removal // later. child.$destroy(false, defer) }, /** * Remove current destroyed child and manually do * the cleanup after removal. * * @param {Function} cb */ remove: function (child, cb) { var keepAlive = this.keepAlive if (child) { child.$remove(function () { if (!keepAlive) child._cleanup() if (cb) cb() }) } else if (cb) { cb() } }, /** * Actually swap the components, depending on the * transition mode. Defaults to simultaneous. * * @param {Vue} target * @param {Function} [cb] */ transition: function (target, cb) { var self = this var current = this.childVM this.unsetCurrent() this.setCurrent(target) switch (self.transMode) { case 'in-out': target.$before(self.anchor, function () { self.remove(current, cb) }) break case 'out-in': self.remove(current, function () { if (!target._isDestroyed) { target.$before(self.anchor, cb) } }) break default: self.remove(current) target.$before(self.anchor, cb) } }, /** * Set childVM and parent ref */ setCurrent: function (child) { this.childVM = child var refID = child._refID || this.refID if (refID) { this.vm.$[refID] = child } }, /** * Unset childVM and parent ref */ unsetCurrent: function () { var child = this.childVM this.childVM = null var refID = (child && child._refID) || this.refID if (refID) { this.vm.$[refID] = null } }, /** * Unbind. */ unbind: function () { this.invalidatePending() // Do not defer cleanup when unbinding this.unbuild() this.unsetCurrent() // destroy all keep-alive cached instances if (this.cache) { for (var key in this.cache) { this.cache[key].$destroy() } this.cache = null } } } /***/ }, /* 27 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var config = __webpack_require__(6) var templateParser = __webpack_require__(25) /** * Process an element or a DocumentFragment based on a * instance option object. This allows us to transclude * a template node/fragment before the instance is created, * so the processed fragment can then be cloned and reused * in v-repeat. * * @param {Element} el * @param {Object} options * @return {Element|DocumentFragment} */ exports.transclude = function (el, options) { // extract container attributes to pass them down // to compiler, because they need to be compiled in // parent scope. we are mutating the options object here // assuming the same object will be used for compile // right after this. if (options) { options._containerAttrs = extractAttrs(el) } // for template tags, what we want is its content as // a documentFragment (for block instances) if (_.isTemplate(el)) { el = templateParser.parse(el) } if (options) { if (options._asComponent && !options.template) { options.template = '<content></content>' } if (options.template) { options._content = _.extractContent(el) el = transcludeTemplate(el, options) } } if (el instanceof DocumentFragment) { // anchors for block instance // passing in `persist: true` to avoid them being // discarded by IE during template cloning _.prepend(_.createAnchor('v-start', true), el) el.appendChild(_.createAnchor('v-end', true)) } return el } /** * Process the template option. * If the replace option is true this will swap the $el. * * @param {Element} el * @param {Object} options * @return {Element|DocumentFragment} */ function transcludeTemplate (el, options) { var template = options.template var frag = templateParser.parse(template, true) if (!frag) { _.warn('Invalid template option: ' + template) } else { var replacer = frag.firstChild var tag = replacer.tagName && replacer.tagName.toLowerCase() if (options.replace) { /* istanbul ignore if */ if (el === document.body) { _.warn( 'You are mounting an instance with a template to ' + '<body>. This will replace <body> entirely. You ' + 'should probably use `replace: false` here.' ) } if ( // multi-children template frag.childNodes.length > 1 || // non-element template replacer.nodeType !== 1 || // when root node is <component>, is an element // directive, or has v-repeat, the instance could // end up having multiple top-level nodes, thus // becoming a block instance. tag === 'component' || _.resolveAsset(options, 'elementDirectives', tag) || replacer.hasAttribute(config.prefix + 'repeat') ) { return frag } else { options._replacerAttrs = extractAttrs(replacer) mergeAttrs(el, replacer) return replacer } } else { el.appendChild(frag) return el } } } /** * Helper to extract a component container's attribute names * into a map. * * @param {Element} el * @return {Object} */ function extractAttrs (el) { if (el.nodeType === 1 && el.hasAttributes()) { var attrs = el.attributes var res = {} var i = attrs.length while (i--) { res[attrs[i].name] = attrs[i].value } return res } } /** * Merge the attributes of two elements, and make sure * the class names are merged properly. * * @param {Element} from * @param {Element} to */ function mergeAttrs (from, to) { var attrs = from.attributes var i = attrs.length var name, value while (i--) { name = attrs[i].name value = attrs[i].value if (!to.hasAttribute(name)) { to.setAttribute(name, value) } else if (name === 'class') { to.className = to.className + ' ' + value } } } /***/ }, /* 28 */ /***/ function(module, exports, __webpack_require__) { // manipulation directives exports.text = __webpack_require__(30) exports.html = __webpack_require__(31) exports.attr = __webpack_require__(32) exports.show = __webpack_require__(33) exports['class'] = __webpack_require__(35) exports.el = __webpack_require__(36) exports.ref = __webpack_require__(37) exports.cloak = __webpack_require__(38) exports.style = __webpack_require__(29) exports.transition = __webpack_require__(39) // event listener directives exports.on = __webpack_require__(42) exports.model = __webpack_require__(43) // logic control directives exports.repeat = __webpack_require__(48) exports['if'] = __webpack_require__(49) // internal directives that should not be used directly // but we still want to expose them for advanced usage. exports._component = __webpack_require__(26) exports._prop = __webpack_require__(16) /***/ }, /* 29 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var prefixes = ['-webkit-', '-moz-', '-ms-'] var camelPrefixes = ['Webkit', 'Moz', 'ms'] var importantRE = /!important;?$/ var camelRE = /([a-z])([A-Z])/g var testEl = null var propCache = {} module.exports = { deep: true, update: function (value) { if (this.arg) { this.setProp(this.arg, value) } else { if (typeof value === 'object') { this.objectHandler(value) } else { this.el.style.cssText = value } } }, objectHandler: function (value) { // cache object styles so that only changed props // are actually updated. var cache = this.cache || (this.cache = {}) var prop, val for (prop in cache) { if (!(prop in value)) { this.setProp(prop, null) delete cache[prop] } } for (prop in value) { val = value[prop] if (val !== cache[prop]) { cache[prop] = val this.setProp(prop, val) } } }, setProp: function (prop, value) { prop = normalize(prop) if (!prop) return // unsupported prop // cast possible numbers/booleans into strings if (value != null) value += '' if (value) { var isImportant = importantRE.test(value) ? 'important' : '' if (isImportant) { value = value.replace(importantRE, '').trim() } this.el.style.setProperty(prop, value, isImportant) } else { this.el.style.removeProperty(prop) } } } /** * Normalize a CSS property name. * - cache result * - auto prefix * - camelCase -> dash-case * * @param {String} prop * @return {String} */ function normalize (prop) { if (propCache[prop]) { return propCache[prop] } var res = prefix(prop) propCache[prop] = propCache[res] = res return res } /** * Auto detect the appropriate prefix for a CSS property. * https://gist.github.com/paulirish/523692 * * @param {String} prop * @return {String} */ function prefix (prop) { prop = prop.replace(camelRE, '$1-$2').toLowerCase() var camel = _.camelize(prop) var upper = camel.charAt(0).toUpperCase() + camel.slice(1) if (!testEl) { testEl = document.createElement('div') } if (camel in testEl.style) { return prop } var i = prefixes.length var prefixed while (i--) { prefixed = camelPrefixes[i] + upper if (prefixed in testEl.style) { return prefixes[i] + prop } } } /***/ }, /* 30 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) module.exports = { bind: function () { this.attr = this.el.nodeType === 3 ? 'data' : 'textContent' }, update: function (value) { this.el[this.attr] = _.toString(value) } } /***/ }, /* 31 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var templateParser = __webpack_require__(25) module.exports = { bind: function () { // a comment node means this is a binding for // {{{ inline unescaped html }}} if (this.el.nodeType === 8) { // hold nodes this.nodes = [] // replace the placeholder with proper anchor this.anchor = _.createAnchor('v-html') _.replace(this.el, this.anchor) } }, update: function (value) { value = _.toString(value) if (this.nodes) { this.swap(value) } else { this.el.innerHTML = value } }, swap: function (value) { // remove old nodes var i = this.nodes.length while (i--) { _.remove(this.nodes[i]) } // convert new value to a fragment // do not attempt to retrieve from id selector var frag = templateParser.parse(value, true, true) // save a reference to these nodes so we can remove later this.nodes = _.toArray(frag.childNodes) _.before(frag, this.anchor) } } /***/ }, /* 32 */ /***/ function(module, exports, __webpack_require__) { // xlink var xlinkNS = 'http://www.w3.org/1999/xlink' var xlinkRE = /^xlink:/ module.exports = { priority: 850, update: function (value) { if (this.arg) { this.setAttr(this.arg, value) } else if (typeof value === 'object') { this.objectHandler(value) } }, objectHandler: function (value) { // cache object attrs so that only changed attrs // are actually updated. var cache = this.cache || (this.cache = {}) var attr, val for (attr in cache) { if (!(attr in value)) { this.setAttr(attr, null) delete cache[attr] } } for (attr in value) { val = value[attr] if (val !== cache[attr]) { cache[attr] = val this.setAttr(attr, val) } } }, setAttr: function (attr, value) { if (value || value === 0) { if (xlinkRE.test(attr)) { this.el.setAttributeNS(xlinkNS, attr, value) } else { this.el.setAttribute(attr, value) } } else { this.el.removeAttribute(attr) } } } /***/ }, /* 33 */ /***/ function(module, exports, __webpack_require__) { var transition = __webpack_require__(34) module.exports = function (value) { var el = this.el transition.apply(el, value ? 1 : -1, function () { el.style.display = value ? '' : 'none' }, this.vm) } /***/ }, /* 34 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) /** * Append with transition. * * @oaram {Element} el * @param {Element} target * @param {Vue} vm * @param {Function} [cb] */ exports.append = function (el, target, vm, cb) { apply(el, 1, function () { target.appendChild(el) }, vm, cb) } /** * InsertBefore with transition. * * @oaram {Element} el * @param {Element} target * @param {Vue} vm * @param {Function} [cb] */ exports.before = function (el, target, vm, cb) { apply(el, 1, function () { _.before(el, target) }, vm, cb) } /** * Remove with transition. * * @oaram {Element} el * @param {Vue} vm * @param {Function} [cb] */ exports.remove = function (el, vm, cb) { apply(el, -1, function () { _.remove(el) }, vm, cb) } /** * Remove by appending to another parent with transition. * This is only used in block operations. * * @oaram {Element} el * @param {Element} target * @param {Vue} vm * @param {Function} [cb] */ exports.removeThenAppend = function (el, target, vm, cb) { apply(el, -1, function () { target.appendChild(el) }, vm, cb) } /** * Append the childNodes of a fragment to target. * * @param {DocumentFragment} block * @param {Node} target * @param {Vue} vm */ exports.blockAppend = function (block, target, vm) { var nodes = _.toArray(block.childNodes) for (var i = 0, l = nodes.length; i < l; i++) { exports.before(nodes[i], target, vm) } } /** * Remove a block of nodes between two edge nodes. * * @param {Node} start * @param {Node} end * @param {Vue} vm */ exports.blockRemove = function (start, end, vm) { var node = start.nextSibling var next while (node !== end) { next = node.nextSibling exports.remove(node, vm) node = next } } /** * Apply transitions with an operation callback. * * @oaram {Element} el * @param {Number} direction * 1: enter * -1: leave * @param {Function} op - the actual DOM operation * @param {Vue} vm * @param {Function} [cb] */ var apply = exports.apply = function (el, direction, op, vm, cb) { var transition = el.__v_trans if ( !transition || // skip if there are no js hooks and CSS transition is // not supported (!transition.hooks && !_.transitionEndEvent) || // skip transitions for initial compile !vm._isCompiled || // if the vm is being manipulated by a parent directive // during the parent's compilation phase, skip the // animation. (vm.$parent && !vm.$parent._isCompiled) ) { op() if (cb) cb() return } var action = direction > 0 ? 'enter' : 'leave' transition[action](op, cb) } /***/ }, /* 35 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var addClass = _.addClass var removeClass = _.removeClass module.exports = { update: function (value) { if (this.arg) { // single toggle var method = value ? addClass : removeClass method(this.el, this.arg) } else { this.cleanup() if (value && typeof value === 'string') { // raw class text addClass(this.el, value) this.lastVal = value } else if (_.isPlainObject(value)) { // object toggle for (var key in value) { if (value[key]) { addClass(this.el, key) } else { removeClass(this.el, key) } } this.prevKeys = Object.keys(value) } } }, cleanup: function (value) { if (this.lastVal) { removeClass(this.el, this.lastVal) } if (this.prevKeys) { var i = this.prevKeys.length while (i--) { if (!value || !value[this.prevKeys[i]]) { removeClass(this.el, this.prevKeys[i]) } } } } } /***/ }, /* 36 */ /***/ function(module, exports, __webpack_require__) { module.exports = { isLiteral: true, bind: function () { this.vm.$$[this.expression] = this.el }, unbind: function () { delete this.vm.$$[this.expression] } } /***/ }, /* 37 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) module.exports = { isLiteral: true, bind: function () { var vm = this.el.__vue__ if (!vm) { _.warn( 'v-ref should only be used on a component root element.' ) return } // If we get here, it means this is a `v-ref` on a // child, because parent scope `v-ref` is stripped in // `v-component` already. So we just record our own ref // here - it will overwrite parent ref in `v-component`, // if any. vm._refID = this.expression } } /***/ }, /* 38 */ /***/ function(module, exports, __webpack_require__) { var config = __webpack_require__(6) module.exports = { bind: function () { var el = this.el this.vm.$once('hook:compiled', function () { el.removeAttribute(config.prefix + 'cloak') }) } } /***/ }, /* 39 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var Transition = __webpack_require__(40) module.exports = { priority: 1000, isLiteral: true, bind: function () { if (!this._isDynamicLiteral) { this.update(this.expression) } }, update: function (id, oldId) { var el = this.el var vm = this.el.__vue__ || this.vm var hooks = _.resolveAsset(vm.$options, 'transitions', id) id = id || 'v' el.__v_trans = new Transition(el, id, hooks, vm) if (oldId) { _.removeClass(el, oldId + '-transition') } _.addClass(el, id + '-transition') } } /***/ }, /* 40 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var queue = __webpack_require__(41) var addClass = _.addClass var removeClass = _.removeClass var transitionEndEvent = _.transitionEndEvent var animationEndEvent = _.animationEndEvent var transDurationProp = _.transitionProp + 'Duration' var animDurationProp = _.animationProp + 'Duration' var TYPE_TRANSITION = 1 var TYPE_ANIMATION = 2 /** * A Transition object that encapsulates the state and logic * of the transition. * * @param {Element} el * @param {String} id * @param {Object} hooks * @param {Vue} vm */ function Transition (el, id, hooks, vm) { this.el = el this.enterClass = id + '-enter' this.leaveClass = id + '-leave' this.hooks = hooks this.vm = vm // async state this.pendingCssEvent = this.pendingCssCb = this.cancel = this.pendingJsCb = this.op = this.cb = null this.typeCache = {} // bind var self = this ;['enterNextTick', 'enterDone', 'leaveNextTick', 'leaveDone'] .forEach(function (m) { self[m] = _.bind(self[m], self) }) } var p = Transition.prototype /** * Start an entering transition. * * 1. enter transition triggered * 2. call beforeEnter hook * 3. add enter class * 4. insert/show element * 5. call enter hook (with possible explicit js callback) * 6. reflow * 7. based on transition type: * - transition: * remove class now, wait for transitionend, * then done if there's no explicit js callback. * - animation: * wait for animationend, remove class, * then done if there's no explicit js callback. * - no css transition: * done now if there's no explicit js callback. * 8. wait for either done or js callback, then call * afterEnter hook. * * @param {Function} op - insert/show the element * @param {Function} [cb] */ p.enter = function (op, cb) { this.cancelPending() this.callHook('beforeEnter') this.cb = cb addClass(this.el, this.enterClass) op() this.callHookWithCb('enter') this.cancel = this.hooks && this.hooks.enterCancelled queue.push(this.enterNextTick) } /** * The "nextTick" phase of an entering transition, which is * to be pushed into a queue and executed after a reflow so * that removing the class can trigger a CSS transition. */ p.enterNextTick = function () { var type = this.getCssTransitionType(this.enterClass) var enterDone = this.enterDone if (type === TYPE_TRANSITION) { // trigger transition by removing enter class now removeClass(this.el, this.enterClass) this.setupCssCb(transitionEndEvent, enterDone) } else if (type === TYPE_ANIMATION) { this.setupCssCb(animationEndEvent, enterDone) } else if (!this.pendingJsCb) { enterDone() } } /** * The "cleanup" phase of an entering transition. */ p.enterDone = function () { this.cancel = this.pendingJsCb = null removeClass(this.el, this.enterClass) this.callHook('afterEnter') if (this.cb) this.cb() } /** * Start a leaving transition. * * 1. leave transition triggered. * 2. call beforeLeave hook * 3. add leave class (trigger css transition) * 4. call leave hook (with possible explicit js callback) * 5. reflow if no explicit js callback is provided * 6. based on transition type: * - transition or animation: * wait for end event, remove class, then done if * there's no explicit js callback. * - no css transition: * done if there's no explicit js callback. * 7. wait for either done or js callback, then call * afterLeave hook. * * @param {Function} op - remove/hide the element * @param {Function} [cb] */ p.leave = function (op, cb) { this.cancelPending() this.callHook('beforeLeave') this.op = op this.cb = cb addClass(this.el, this.leaveClass) this.callHookWithCb('leave') this.cancel = this.hooks && this.hooks.enterCancelled // only need to do leaveNextTick if there's no explicit // js callback if (!this.pendingJsCb) { queue.push(this.leaveNextTick) } } /** * The "nextTick" phase of a leaving transition. */ p.leaveNextTick = function () { var type = this.getCssTransitionType(this.leaveClass) if (type) { var event = type === TYPE_TRANSITION ? transitionEndEvent : animationEndEvent this.setupCssCb(event, this.leaveDone) } else { this.leaveDone() } } /** * The "cleanup" phase of a leaving transition. */ p.leaveDone = function () { this.cancel = this.pendingJsCb = null this.op() removeClass(this.el, this.leaveClass) this.callHook('afterLeave') if (this.cb) this.cb() } /** * Cancel any pending callbacks from a previously running * but not finished transition. */ p.cancelPending = function () { this.op = this.cb = null var hasPending = false if (this.pendingCssCb) { hasPending = true _.off(this.el, this.pendingCssEvent, this.pendingCssCb) this.pendingCssEvent = this.pendingCssCb = null } if (this.pendingJsCb) { hasPending = true this.pendingJsCb.cancel() this.pendingJsCb = null } if (hasPending) { removeClass(this.el, this.enterClass) removeClass(this.el, this.leaveClass) } if (this.cancel) { this.cancel.call(this.vm, this.el) this.cancel = null } } /** * Call a user-provided synchronous hook function. * * @param {String} type */ p.callHook = function (type) { if (this.hooks && this.hooks[type]) { this.hooks[type].call(this.vm, this.el) } } /** * Call a user-provided, potentially-async hook function. * We check for the length of arguments to see if the hook * expects a `done` callback. If true, the transition's end * will be determined by when the user calls that callback; * otherwise, the end is determined by the CSS transition or * animation. * * @param {String} type */ p.callHookWithCb = function (type) { var hook = this.hooks && this.hooks[type] if (hook) { if (hook.length > 1) { this.pendingJsCb = _.cancellable(this[type + 'Done']) } hook.call(this.vm, this.el, this.pendingJsCb) } } /** * Get an element's transition type based on the * calculated styles. * * @param {String} className * @return {Number} */ p.getCssTransitionType = function (className) { /* istanbul ignore if */ if ( !transitionEndEvent || // skip CSS transitions if page is not visible - // this solves the issue of transitionend events not // firing until the page is visible again. // pageVisibility API is supported in IE10+, same as // CSS transitions. document.hidden || // explicit js-only transition (this.hooks && this.hooks.css === false) ) { return } var type = this.typeCache[className] if (type) return type var inlineStyles = this.el.style var computedStyles = window.getComputedStyle(this.el) var transDuration = inlineStyles[transDurationProp] || computedStyles[transDurationProp] if (transDuration && transDuration !== '0s') { type = TYPE_TRANSITION } else { var animDuration = inlineStyles[animDurationProp] || computedStyles[animDurationProp] if (animDuration && animDuration !== '0s') { type = TYPE_ANIMATION } } if (type) { this.typeCache[className] = type } return type } /** * Setup a CSS transitionend/animationend callback. * * @param {String} event * @param {Function} cb */ p.setupCssCb = function (event, cb) { this.pendingCssEvent = event var self = this var el = this.el var onEnd = this.pendingCssCb = function (e) { if (e.target === el) { _.off(el, event, onEnd) self.pendingCssEvent = self.pendingCssCb = null if (!self.pendingJsCb && cb) { cb() } } } _.on(el, event, onEnd) } module.exports = Transition /***/ }, /* 41 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var queue = [] var queued = false /** * Push a job into the queue. * * @param {Function} job */ exports.push = function (job) { queue.push(job) if (!queued) { queued = true _.nextTick(flush) } } /** * Flush the queue, and do one forced reflow before * triggering transitions. */ function flush () { // Force layout var f = document.documentElement.offsetHeight for (var i = 0; i < queue.length; i++) { queue[i]() } queue = [] queued = false // dummy return, so js linters don't complain about // unused variable f return f } /***/ }, /* 42 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) module.exports = { acceptStatement: true, priority: 700, bind: function () { // deal with iframes if ( this.el.tagName === 'IFRAME' && this.arg !== 'load' ) { var self = this this.iframeBind = function () { _.on(self.el.contentWindow, self.arg, self.handler) } _.on(this.el, 'load', this.iframeBind) } }, update: function (handler) { if (typeof handler !== 'function') { _.warn( 'Directive "v-on:' + this.expression + '" ' + 'expects a function value.' ) return } this.reset() var vm = this.vm this.handler = function (e) { e.targetVM = vm vm.$event = e var res = handler(e) vm.$event = null return res } if (this.iframeBind) { this.iframeBind() } else { _.on(this.el, this.arg, this.handler) } }, reset: function () { var el = this.iframeBind ? this.el.contentWindow : this.el if (this.handler) { _.off(el, this.arg, this.handler) } }, unbind: function () { this.reset() _.off(this.el, 'load', this.iframeBind) } } /***/ }, /* 43 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var handlers = { text: __webpack_require__(44), radio: __webpack_require__(45), select: __webpack_require__(46), checkbox: __webpack_require__(47) } module.exports = { priority: 800, twoWay: true, handlers: handlers, /** * Possible elements: * <select> * <textarea> * <input type="*"> * - text * - checkbox * - radio * - number * - TODO: more types may be supplied as a plugin */ bind: function () { // friendly warning... this.checkFilters() if (this.hasRead && !this.hasWrite) { _.warn( 'It seems you are using a read-only filter with ' + 'v-model. You might want to use a two-way filter ' + 'to ensure correct behavior.' ) } var el = this.el var tag = el.tagName var handler if (tag === 'INPUT') { handler = handlers[el.type] || handlers.text } else if (tag === 'SELECT') { handler = handlers.select } else if (tag === 'TEXTAREA') { handler = handlers.text } else { _.warn('v-model does not support element type: ' + tag) return } handler.bind.call(this) this.update = handler.update this.unbind = handler.unbind }, /** * Check read/write filter stats. */ checkFilters: function () { var filters = this.filters if (!filters) return var i = filters.length while (i--) { var filter = _.resolveAsset(this.vm.$options, 'filters', filters[i].name) if (typeof filter === 'function' || filter.read) { this.hasRead = true } if (filter.write) { this.hasWrite = true } } } } /***/ }, /* 44 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) module.exports = { bind: function () { var self = this var el = this.el // check params // - lazy: update model on "change" instead of "input" var lazy = this._checkParam('lazy') != null // - number: cast value into number when updating model. var number = this._checkParam('number') != null // - debounce: debounce the input listener var debounce = parseInt(this._checkParam('debounce'), 10) // handle composition events. // http://blog.evanyou.me/2014/01/03/composition-event/ // skip this for Android because it handles composition // events quite differently. Android doesn't trigger // composition events for language input methods e.g. // Chinese, but instead triggers them for spelling // suggestions... (see Discussion/#162) var composing = false if (!_.isAndroid) { this.onComposeStart = function () { composing = true } this.onComposeEnd = function () { composing = false // in IE11 the "compositionend" event fires AFTER // the "input" event, so the input handler is blocked // at the end... have to call it here. self.listener() } _.on(el, 'compositionstart', this.onComposeStart) _.on(el, 'compositionend', this.onComposeEnd) } function syncToModel () { var val = number ? _.toNumber(el.value) : el.value self.set(val) } // if the directive has filters, we need to // record cursor position and restore it after updating // the input with the filtered value. // also force update for type="range" inputs to enable // "lock in range" (see #506) if (this.hasRead || el.type === 'range') { this.listener = function () { if (composing) return var charsOffset // some HTML5 input types throw error here try { // record how many chars from the end of input // the cursor was at charsOffset = el.value.length - el.selectionStart } catch (e) {} // Fix IE10/11 infinite update cycle // https://github.com/yyx990803/vue/issues/592 /* istanbul ignore if */ if (charsOffset < 0) { return } syncToModel() _.nextTick(function () { // force a value update, because in // certain cases the write filters output the // same result for different input values, and // the Observer set events won't be triggered. var newVal = self._watcher.value self.update(newVal) if (charsOffset != null) { var cursorPos = _.toString(newVal).length - charsOffset el.setSelectionRange(cursorPos, cursorPos) } }) } } else { this.listener = function () { if (composing) return syncToModel() } } if (debounce) { this.listener = _.debounce(this.listener, debounce) } // Now attach the main listener this.event = lazy ? 'change' : 'input' // Support jQuery events, since jQuery.trigger() doesn't // trigger native events in some cases and some plugins // rely on $.trigger() // // We want to make sure if a listener is attached using // jQuery, it is also removed with jQuery, that's why // we do the check for each directive instance and // store that check result on itself. This also allows // easier test coverage control by unsetting the global // jQuery variable in tests. this.hasjQuery = typeof jQuery === 'function' if (this.hasjQuery) { jQuery(el).on(this.event, this.listener) } else { _.on(el, this.event, this.listener) } // IE9 doesn't fire input event on backspace/del/cut if (!lazy && _.isIE9) { this.onCut = function () { _.nextTick(self.listener) } this.onDel = function (e) { if (e.keyCode === 46 || e.keyCode === 8) { self.listener() } } _.on(el, 'cut', this.onCut) _.on(el, 'keyup', this.onDel) } // set initial value if present if ( el.hasAttribute('value') || (el.tagName === 'TEXTAREA' && el.value.trim()) ) { this._initValue = number ? _.toNumber(el.value) : el.value } }, update: function (value) { this.el.value = _.toString(value) }, unbind: function () { var el = this.el if (this.hasjQuery) { jQuery(el).off(this.event, this.listener) } else { _.off(el, this.event, this.listener) } if (this.onComposeStart) { _.off(el, 'compositionstart', this.onComposeStart) _.off(el, 'compositionend', this.onComposeEnd) } if (this.onCut) { _.off(el, 'cut', this.onCut) _.off(el, 'keyup', this.onDel) } } } /***/ }, /* 45 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) module.exports = { bind: function () { var self = this var el = this.el this.listener = function () { self.set(el.value) } _.on(el, 'change', this.listener) if (el.checked) { this._initValue = el.value } }, update: function (value) { /* eslint-disable eqeqeq */ this.el.checked = value == this.el.value /* eslint-enable eqeqeq */ }, unbind: function () { _.off(this.el, 'change', this.listener) } } /***/ }, /* 46 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var Watcher = __webpack_require__(17) var dirParser = __webpack_require__(15) module.exports = { bind: function () { var self = this var el = this.el // update DOM using latest value. this.forceUpdate = function () { if (self._watcher) { self.update(self._watcher.get()) } } // check options param var optionsParam = this._checkParam('options') if (optionsParam) { initOptions.call(this, optionsParam) } this.number = this._checkParam('number') != null this.multiple = el.hasAttribute('multiple') this.listener = function () { var value = self.multiple ? getMultiValue(el) : el.value value = self.number ? _.isArray(value) ? value.map(_.toNumber) : _.toNumber(value) : value self.set(value) } _.on(el, 'change', this.listener) checkInitialValue.call(this) // All major browsers except Firefox resets // selectedIndex with value -1 to 0 when the element // is appended to a new parent, therefore we have to // force a DOM update whenever that happens... this.vm.$on('hook:attached', this.forceUpdate) }, update: function (value) { var el = this.el el.selectedIndex = -1 var multi = this.multiple && _.isArray(value) var options = el.options var i = options.length var option while (i--) { option = options[i] /* eslint-disable eqeqeq */ option.selected = multi ? indexOf(value, option.value) > -1 : value == option.value /* eslint-enable eqeqeq */ } }, unbind: function () { _.off(this.el, 'change', this.listener) this.vm.$off('hook:attached', this.forceUpdate) if (this.optionWatcher) { this.optionWatcher.teardown() } } } /** * Initialize the option list from the param. * * @param {String} expression */ function initOptions (expression) { var self = this var descriptor = dirParser.parse(expression)[0] function optionUpdateWatcher (value) { if (_.isArray(value)) { self.el.innerHTML = '' buildOptions(self.el, value) self.forceUpdate() } else { _.warn('Invalid options value for v-model: ' + value) } } this.optionWatcher = new Watcher( this.vm, descriptor.expression, optionUpdateWatcher, { deep: true, filters: descriptor.filters } ) // update with initial value optionUpdateWatcher(this.optionWatcher.value) } /** * Build up option elements. IE9 doesn't create options * when setting innerHTML on <select> elements, so we have * to use DOM API here. * * @param {Element} parent - a <select> or an <optgroup> * @param {Array} options */ function buildOptions (parent, options) { var op, el for (var i = 0, l = options.length; i < l; i++) { op = options[i] if (!op.options) { el = document.createElement('option') if (typeof op === 'string') { el.text = el.value = op } else { if (op.value != null) { el.value = op.value } el.text = op.text || op.value || '' if (op.disabled) { el.disabled = true } } } else { el = document.createElement('optgroup') el.label = op.label buildOptions(el, op.options) } parent.appendChild(el) } } /** * Check the initial value for selected options. */ function checkInitialValue () { var initValue var options = this.el.options for (var i = 0, l = options.length; i < l; i++) { if (options[i].hasAttribute('selected')) { if (this.multiple) { (initValue || (initValue = [])) .push(options[i].value) } else { initValue = options[i].value } } } if (typeof initValue !== 'undefined') { this._initValue = this.number ? _.toNumber(initValue) : initValue } } /** * Helper to extract a value array for select[multiple] * * @param {SelectElement} el * @return {Array} */ function getMultiValue (el) { return Array.prototype.filter .call(el.options, filterSelected) .map(getOptionValue) } function filterSelected (op) { return op.selected } function getOptionValue (op) { return op.value || op.text } /** * Native Array.indexOf uses strict equal, but in this * case we need to match string/numbers with soft equal. * * @param {Array} arr * @param {*} val */ function indexOf (arr, val) { var i = arr.length while (i--) { /* eslint-disable eqeqeq */ if (arr[i] == val) return i /* eslint-enable eqeqeq */ } return -1 } /***/ }, /* 47 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) module.exports = { bind: function () { var self = this var el = this.el this.listener = function () { self.set(el.checked) } _.on(el, 'change', this.listener) if (el.checked) { this._initValue = el.checked } }, update: function (value) { this.el.checked = !!value }, unbind: function () { _.off(this.el, 'change', this.listener) } } /***/ }, /* 48 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var isObject = _.isObject var isPlainObject = _.isPlainObject var textParser = __webpack_require__(13) var expParser = __webpack_require__(22) var templateParser = __webpack_require__(25) var compiler = __webpack_require__(10) var uid = 0 // async component resolution states var UNRESOLVED = 0 var PENDING = 1 var RESOLVED = 2 var ABORTED = 3 module.exports = { /** * Setup. */ bind: function () { // uid as a cache identifier this.id = '__v_repeat_' + (++uid) // setup anchor nodes this.start = _.createAnchor('v-repeat-start') this.end = _.createAnchor('v-repeat-end') _.replace(this.el, this.end) _.before(this.start, this.end) // check if this is a block repeat this.template = _.isTemplate(this.el) ? templateParser.parse(this.el, true) : this.el // check other directives that need to be handled // at v-repeat level this.checkIf() this.checkRef() this.checkComponent() // check for trackby param this.idKey = this._checkParam('track-by') || this._checkParam('trackby') // 0.11.0 compat // check for transition stagger var stagger = +this._checkParam('stagger') this.enterStagger = +this._checkParam('enter-stagger') || stagger this.leaveStagger = +this._checkParam('leave-stagger') || stagger this.cache = Object.create(null) }, /** * Warn against v-if usage. */ checkIf: function () { if (_.attr(this.el, 'if') !== null) { _.warn( 'Don\'t use v-if with v-repeat. ' + 'Use v-show or the "filterBy" filter instead.' ) } }, /** * Check if v-ref/ v-el is also present. */ checkRef: function () { var refID = _.attr(this.el, 'ref') this.refID = refID ? this.vm.$interpolate(refID) : null var elId = _.attr(this.el, 'el') this.elId = elId ? this.vm.$interpolate(elId) : null }, /** * Check the component constructor to use for repeated * instances. If static we resolve it now, otherwise it * needs to be resolved at build time with actual data. */ checkComponent: function () { this.componentState = UNRESOLVED var options = this.vm.$options var id = _.checkComponent(this.el, options) if (!id) { // default constructor this.Ctor = _.Vue // inline repeats should inherit this.inherit = true // important: transclude with no options, just // to ensure block start and block end this.template = compiler.transclude(this.template) var copy = _.extend({}, options) copy._asComponent = false this._linkFn = compiler.compile(this.template, copy) } else { this.Ctor = null this.asComponent = true // check inline-template if (this._checkParam('inline-template') !== null) { // extract inline template as a DocumentFragment this.inlineTemplate = _.extractContent(this.el, true) } var tokens = textParser.parse(id) if (tokens) { // dynamic component to be resolved later var ctorExp = textParser.tokensToExp(tokens) this.ctorGetter = expParser.parse(ctorExp).get } else { // static this.componentId = id this.pendingData = null } } }, resolveComponent: function () { this.componentState = PENDING this.vm._resolveComponent(this.componentId, _.bind(function (Ctor) { if (this.componentState === ABORTED) { return } this.Ctor = Ctor this.componentState = RESOLVED this.realUpdate(this.pendingData) this.pendingData = null }, this)) }, /** * Resolve a dynamic component to use for an instance. * The tricky part here is that there could be dynamic * components depending on instance data. * * @param {Object} data * @param {Object} meta * @return {Function} */ resolveDynamicComponent: function (data, meta) { // create a temporary context object and copy data // and meta properties onto it. // use _.define to avoid accidentally overwriting scope // properties. var context = Object.create(this.vm) var key for (key in data) { _.define(context, key, data[key]) } for (key in meta) { _.define(context, key, meta[key]) } var id = this.ctorGetter.call(context, context) var Ctor = _.resolveAsset(this.vm.$options, 'components', id) _.assertAsset(Ctor, 'component', id) if (!Ctor.options) { _.warn( 'Async resolution is not supported for v-repeat ' + '+ dynamic component. (component: ' + id + ')' ) return _.Vue } return Ctor }, /** * Update. * This is called whenever the Array mutates. If we have * a component, we might need to wait for it to resolve * asynchronously. * * @param {Array|Number|String} data */ update: function (data) { if (this.componentId) { var state = this.componentState if (state === UNRESOLVED) { this.pendingData = data // once resolved, it will call realUpdate this.resolveComponent() } else if (state === PENDING) { this.pendingData = data } else if (state === RESOLVED) { this.realUpdate(data) } } else { this.realUpdate(data) } }, /** * The real update that actually modifies the DOM. * * @param {Array|Number|String} data */ realUpdate: function (data) { this.vms = this.diff(data, this.vms) // update v-ref if (this.refID) { this.vm.$[this.refID] = this.converted ? toRefObject(this.vms) : this.vms } if (this.elId) { this.vm.$$[this.elId] = this.vms.map(function (vm) { return vm.$el }) } }, /** * Diff, based on new data and old data, determine the * minimum amount of DOM manipulations needed to make the * DOM reflect the new data Array. * * The algorithm diffs the new data Array by storing a * hidden reference to an owner vm instance on previously * seen data. This allows us to achieve O(n) which is * better than a levenshtein distance based algorithm, * which is O(m * n). * * @param {Array} data * @param {Array} oldVms * @return {Array} */ diff: function (data, oldVms) { var idKey = this.idKey var converted = this.converted var start = this.start var end = this.end var inDoc = _.inDoc(start) var alias = this.arg var init = !oldVms var vms = new Array(data.length) var obj, raw, vm, i, l, primitive // First pass, go through the new Array and fill up // the new vms array. If a piece of data has a cached // instance for it, we reuse it. Otherwise build a new // instance. for (i = 0, l = data.length; i < l; i++) { obj = data[i] raw = converted ? obj.$value : obj primitive = !isObject(raw) vm = !init && this.getVm(raw, i, converted ? obj.$key : null) if (vm) { // reusable instance vm._reused = true vm.$index = i // update $index // update data for track-by or object repeat, // since in these two cases the data is replaced // rather than mutated. if (idKey || converted || primitive) { if (alias) { vm[alias] = raw } else if (_.isPlainObject(raw)) { vm.$data = raw } else { vm.$value = raw } } } else { // new instance vm = this.build(obj, i, true) vm._reused = false } vms[i] = vm // insert if this is first run if (init) { vm.$before(end) } } // if this is the first run, we're done. if (init) { return vms } // Second pass, go through the old vm instances and // destroy those who are not reused (and remove them // from cache) var removalIndex = 0 var totalRemoved = oldVms.length - vms.length for (i = 0, l = oldVms.length; i < l; i++) { vm = oldVms[i] if (!vm._reused) { this.uncacheVm(vm) vm.$destroy(false, true) // defer cleanup until removal this.remove(vm, removalIndex++, totalRemoved, inDoc) } } // final pass, move/insert new instances into the // right place. var targetPrev, prevEl, currentPrev var insertionIndex = 0 for (i = 0, l = vms.length; i < l; i++) { vm = vms[i] // this is the vm that we should be after targetPrev = vms[i - 1] prevEl = targetPrev ? targetPrev._staggerCb ? targetPrev._staggerAnchor : targetPrev._blockEnd || targetPrev.$el : start if (vm._reused && !vm._staggerCb) { currentPrev = findPrevVm(vm, start, this.id) if (currentPrev !== targetPrev) { this.move(vm, prevEl) } } else { // new instance, or still in stagger. // insert with updated stagger index. this.insert(vm, insertionIndex++, prevEl, inDoc) } vm._reused = false } return vms }, /** * Build a new instance and cache it. * * @param {Object} data * @param {Number} index * @param {Boolean} needCache */ build: function (data, index, needCache) { var meta = { $index: index } if (this.converted) { meta.$key = data.$key } var raw = this.converted ? data.$value : data var alias = this.arg if (alias) { data = {} data[alias] = raw } else if (!isPlainObject(raw)) { // non-object values data = {} meta.$value = raw } else { // default data = raw } // resolve constructor var Ctor = this.Ctor || this.resolveDynamicComponent(data, meta) var parent = this._host || this.vm var vm = parent.$addChild({ el: templateParser.clone(this.template), data: data, inherit: this.inherit, template: this.inlineTemplate, // repeater meta, e.g. $index, $key _meta: meta, // mark this as an inline-repeat instance _repeat: this.inherit, // is this a component? _asComponent: this.asComponent, // linker cachable if no inline-template _linkerCachable: !this.inlineTemplate && Ctor !== _.Vue, // pre-compiled linker for simple repeats _linkFn: this._linkFn, // identifier, shows that this vm belongs to this collection _repeatId: this.id, // transclusion content owner _context: this.vm }, Ctor) // cache instance if (needCache) { this.cacheVm(raw, vm, index, this.converted ? meta.$key : null) } // sync back changes for two-way bindings of primitive values var type = typeof raw var dir = this if ( this.rawType === 'object' && (type === 'string' || type === 'number') ) { vm.$watch(alias || '$value', function (val) { if (dir.filters) { _.warn( 'You seem to be mutating the $value reference of ' + 'a v-repeat instance (likely through v-model) ' + 'and filtering the v-repeat at the same time. ' + 'This will not work properly with an Array of ' + 'primitive values. Please use an Array of ' + 'Objects instead.' ) } dir._withLock(function () { if (dir.converted) { dir.rawValue[vm.$key] = val } else { dir.rawValue.$set(vm.$index, val) } }) }) } return vm }, /** * Unbind, teardown everything */ unbind: function () { this.componentState = ABORTED if (this.refID) { this.vm.$[this.refID] = null } if (this.vms) { var i = this.vms.length var vm while (i--) { vm = this.vms[i] this.uncacheVm(vm) vm.$destroy() } } }, /** * Cache a vm instance based on its data. * * If the data is an object, we save the vm's reference on * the data object as a hidden property. Otherwise we * cache them in an object and for each primitive value * there is an array in case there are duplicates. * * @param {Object} data * @param {Vue} vm * @param {Number} index * @param {String} [key] */ cacheVm: function (data, vm, index, key) { var idKey = this.idKey var cache = this.cache var primitive = !isObject(data) var id if (key || idKey || primitive) { id = idKey ? idKey === '$index' ? index : data[idKey] : (key || index) if (!cache[id]) { cache[id] = vm } else if (!primitive && idKey !== '$index') { _.warn('Duplicate track-by key in v-repeat: ' + id) } } else { id = this.id if (data.hasOwnProperty(id)) { if (data[id] === null) { data[id] = vm } else { _.warn( 'Duplicate objects are not supported in v-repeat ' + 'when using components or transitions.' ) } } else { _.define(data, id, vm) } } vm._raw = data }, /** * Try to get a cached instance from a piece of data. * * @param {Object} data * @param {Number} index * @param {String} [key] * @return {Vue|undefined} */ getVm: function (data, index, key) { var idKey = this.idKey var primitive = !isObject(data) if (key || idKey || primitive) { var id = idKey ? idKey === '$index' ? index : data[idKey] : (key || index) return this.cache[id] } else { return data[this.id] } }, /** * Delete a cached vm instance. * * @param {Vue} vm */ uncacheVm: function (vm) { var data = vm._raw var idKey = this.idKey var index = vm.$index // fix #948: avoid accidentally fall through to // a parent repeater which happens to have $key. var key = vm.hasOwnProperty('$key') && vm.$key var primitive = !isObject(data) if (idKey || key || primitive) { var id = idKey ? idKey === '$index' ? index : data[idKey] : (key || index) this.cache[id] = null } else { data[this.id] = null vm._raw = null } }, /** * Pre-process the value before piping it through the * filters, and convert non-Array objects to arrays. * * This function will be bound to this directive instance * and passed into the watcher. * * @param {*} value * @return {Array} * @private */ _preProcess: function (value) { // regardless of type, store the un-filtered raw value. this.rawValue = value var type = this.rawType = typeof value if (!isPlainObject(value)) { this.converted = false if (type === 'number') { value = range(value) } else if (type === 'string') { value = _.toArray(value) } return value || [] } else { // convert plain object to array. var keys = Object.keys(value) var i = keys.length var res = new Array(i) var key while (i--) { key = keys[i] res[i] = { $key: key, $value: value[key] } } this.converted = true return res } }, /** * Insert an instance. * * @param {Vue} vm * @param {Number} index * @param {Node} prevEl * @param {Boolean} inDoc */ insert: function (vm, index, prevEl, inDoc) { if (vm._staggerCb) { vm._staggerCb.cancel() vm._staggerCb = null } var staggerAmount = this.getStagger(vm, index, null, 'enter') if (inDoc && staggerAmount) { // create an anchor and insert it synchronously, // so that we can resolve the correct order without // worrying about some elements not inserted yet var anchor = vm._staggerAnchor if (!anchor) { anchor = vm._staggerAnchor = _.createAnchor('stagger-anchor') anchor.__vue__ = vm } _.after(anchor, prevEl) var op = vm._staggerCb = _.cancellable(function () { vm._staggerCb = null vm.$before(anchor) _.remove(anchor) }) setTimeout(op, staggerAmount) } else { vm.$after(prevEl) } }, /** * Move an already inserted instance. * * @param {Vue} vm * @param {Node} prevEl */ move: function (vm, prevEl) { vm.$after(prevEl, null, false) }, /** * Remove an instance. * * @param {Vue} vm * @param {Number} index * @param {Boolean} inDoc */ remove: function (vm, index, total, inDoc) { if (vm._staggerCb) { vm._staggerCb.cancel() vm._staggerCb = null // it's not possible for the same vm to be removed // twice, so if we have a pending stagger callback, // it means this vm is queued for enter but removed // before its transition started. Since it is already // destroyed, we can just leave it in detached state. return } var staggerAmount = this.getStagger(vm, index, total, 'leave') if (inDoc && staggerAmount) { var op = vm._staggerCb = _.cancellable(function () { vm._staggerCb = null remove() }) setTimeout(op, staggerAmount) } else { remove() } function remove () { vm.$remove(function () { vm._cleanup() }) } }, /** * Get the stagger amount for an insertion/removal. * * @param {Vue} vm * @param {Number} index * @param {String} type * @param {Number} total */ getStagger: function (vm, index, total, type) { type = type + 'Stagger' var transition = vm.$el.__v_trans var hooks = transition && transition.hooks var hook = hooks && (hooks[type] || hooks.stagger) return hook ? hook.call(vm, index, total) : index * this[type] } } /** * Helper to find the previous element that is an instance * root node. This is necessary because a destroyed vm's * element could still be lingering in the DOM before its * leaving transition finishes, but its __vue__ reference * should have been removed so we can skip them. * * If this is a block repeat, we want to make sure we only * return vm that is bound to this v-repeat. (see #929) * * @param {Vue} vm * @param {Comment|Text} anchor * @return {Vue} */ function findPrevVm (vm, anchor, id) { var el = vm.$el.previousSibling while ( (!el.__vue__ || el.__vue__.$options._repeatId !== id) && el !== anchor ) { el = el.previousSibling } return el.__vue__ } /** * Create a range array from given number. * * @param {Number} n * @return {Array} */ function range (n) { var i = -1 var ret = new Array(n) while (++i < n) { ret[i] = i } return ret } /** * Convert a vms array to an object ref for v-ref on an * Object value. * * @param {Array} vms * @return {Object} */ function toRefObject (vms) { var ref = {} for (var i = 0, l = vms.length; i < l; i++) { ref[vms[i].$key] = vms[i] } return ref } /***/ }, /* 49 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var compiler = __webpack_require__(10) var templateParser = __webpack_require__(25) var transition = __webpack_require__(34) module.exports = { bind: function () { var el = this.el if (!el.__vue__) { this.start = _.createAnchor('v-if-start') this.end = _.createAnchor('v-if-end') _.replace(el, this.end) _.before(this.start, this.end) if (_.isTemplate(el)) { this.template = templateParser.parse(el, true) } else { this.template = document.createDocumentFragment() this.template.appendChild(templateParser.clone(el)) } // compile the nested partial this.linker = compiler.compile( this.template, this.vm.$options, true ) } else { this.invalid = true _.warn( 'v-if="' + this.expression + '" cannot be ' + 'used on an instance root element.' ) } }, update: function (value) { if (this.invalid) return if (value) { // avoid duplicate compiles, since update() can be // called with different truthy values if (!this.unlink) { this.link( templateParser.clone(this.template), this.linker ) } } else { this.teardown() } }, link: function (frag, linker) { var vm = this.vm this.unlink = linker(vm, frag) transition.blockAppend(frag, this.end, vm) // call attached for all the child components created // during the compilation if (_.inDoc(vm.$el)) { var children = this.getContainedComponents() if (children) children.forEach(callAttach) } }, teardown: function () { if (!this.unlink) return // collect children beforehand var children if (_.inDoc(this.vm.$el)) { children = this.getContainedComponents() } transition.blockRemove(this.start, this.end, this.vm) if (children) children.forEach(callDetach) this.unlink() this.unlink = null }, getContainedComponents: function () { var vm = this.vm var start = this.start.nextSibling var end = this.end function contains (c) { var cur = start var next while (next !== end) { next = cur.nextSibling if ( cur === c.$el || cur.contains && cur.contains(c.$el) ) { return true } cur = next } return false } return vm.$children.length && vm.$children.filter(contains) }, unbind: function () { if (this.unlink) this.unlink() } } function callAttach (child) { if (!child._isAttached) { child._callHook('attached') } } function callDetach (child) { if (child._isAttached) { child._callHook('detached') } } /***/ }, /* 50 */ /***/ function(module, exports, __webpack_require__) { exports.content = __webpack_require__(51) exports.partial = __webpack_require__(52) /***/ }, /* 51 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) // This is the elementDirective that handles <content> // transclusions. It relies on the raw content of an // instance being stored as `$options._content` during // the transclude phase. module.exports = { bind: function () { var vm = this.vm var host = vm // we need find the content context, which is the // closest non-inline-repeater instance. while (host.$options._repeat) { host = host.$parent } var raw = host.$options._content var content if (!raw) { this.fallback() return } var context = host._context var selector = this.el.getAttribute('select') if (!selector) { // Default content var self = this var compileDefaultContent = function () { self.compile( extractFragment(raw.childNodes, raw, true), context, vm ) } if (!host._isCompiled) { // defer until the end of instance compilation, // because the default outlet must wait until all // other possible outlets with selectors have picked // out their contents. host.$once('hook:compiled', compileDefaultContent) } else { compileDefaultContent() } } else { // select content selector = vm.$interpolate(selector) var nodes = raw.querySelectorAll(selector) if (nodes.length) { content = extractFragment(nodes, raw) if (content.hasChildNodes()) { this.compile(content, context, vm) } else { this.fallback() } } else { this.fallback() } } }, fallback: function () { this.compile(_.extractContent(this.el, true), this.vm) }, compile: function (content, context, host) { if (content && context) { this.unlink = context.$compile(content, host) } if (content) { _.replace(this.el, content) } else { _.remove(this.el) } }, unbind: function () { if (this.unlink) { this.unlink() } } } /** * Extract qualified content nodes from a node list. * * @param {NodeList} nodes * @param {Element} parent * @param {Boolean} main * @return {DocumentFragment} */ function extractFragment (nodes, parent, main) { var frag = document.createDocumentFragment() for (var i = 0, l = nodes.length; i < l; i++) { var node = nodes[i] // if this is the main outlet, we want to skip all // previously selected nodes; // otherwise, we want to mark the node as selected. // clone the node so the original raw content remains // intact. this ensures proper re-compilation in cases // where the outlet is inside a conditional block if (main && !node.__v_selected) { frag.appendChild(node.cloneNode(true)) } else if (!main && node.parentNode === parent) { node.__v_selected = true frag.appendChild(node.cloneNode(true)) } } return frag } /***/ }, /* 52 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var templateParser = __webpack_require__(25) var textParser = __webpack_require__(13) var compiler = __webpack_require__(10) var Cache = __webpack_require__(14) var cache = new Cache(1000) // v-partial reuses logic from v-if var vIf = __webpack_require__(49) module.exports = { link: vIf.link, teardown: vIf.teardown, getContainedComponents: vIf.getContainedComponents, bind: function () { var el = this.el this.start = _.createAnchor('v-partial-start') this.end = _.createAnchor('v-partial-end') _.replace(el, this.end) _.before(this.start, this.end) var id = el.getAttribute('name') var tokens = textParser.parse(id) if (tokens) { // dynamic partial this.setupDynamic(tokens) } else { // static partial this.insert(id) } }, setupDynamic: function (tokens) { var self = this var exp = textParser.tokensToExp(tokens) this.unwatch = this.vm.$watch(exp, function (value) { self.teardown() self.insert(value) }, { immediate: true, user: false }) }, insert: function (id) { var partial = _.resolveAsset(this.vm.$options, 'partials', id) _.assertAsset(partial, 'partial', id) if (partial) { var frag = templateParser.parse(partial, true) // cache partials based on constructor id. var cacheId = (this.vm.constructor.cid || '') + partial var linker = this.compile(frag, cacheId) // this is provided by v-if this.link(frag, linker) } }, compile: function (frag, cacheId) { var hit = cache.get(cacheId) if (hit) return hit var linker = compiler.compile(frag, this.vm.$options, true) cache.put(cacheId, linker) return linker }, unbind: function () { if (this.unlink) this.unlink() if (this.unwatch) this.unwatch() } } /***/ }, /* 53 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) /** * Stringify value. * * @param {Number} indent */ exports.json = { read: function (value, indent) { return typeof value === 'string' ? value : JSON.stringify(value, null, Number(indent) || 2) }, write: function (value) { try { return JSON.parse(value) } catch (e) { return value } } } /** * 'abc' => 'Abc' */ exports.capitalize = function (value) { if (!value && value !== 0) return '' value = value.toString() return value.charAt(0).toUpperCase() + value.slice(1) } /** * 'abc' => 'ABC' */ exports.uppercase = function (value) { return (value || value === 0) ? value.toString().toUpperCase() : '' } /** * 'AbC' => 'abc' */ exports.lowercase = function (value) { return (value || value === 0) ? value.toString().toLowerCase() : '' } /** * 12345 => $12,345.00 * * @param {String} sign */ var digitsRE = /(\d{3})(?=\d)/g exports.currency = function (value, currency) { value = parseFloat(value) if (!isFinite(value) || (!value && value !== 0)) return '' currency = currency || '$' var stringified = Math.abs(value).toFixed(2) var _int = stringified.slice(0, -3) var i = _int.length % 3 var head = i > 0 ? (_int.slice(0, i) + (_int.length > 3 ? ',' : '')) : '' var _float = stringified.slice(-3) var sign = value < 0 ? '-' : '' return currency + sign + head + _int.slice(i).replace(digitsRE, '$1,') + _float } /** * 'item' => 'items' * * @params * an array of strings corresponding to * the single, double, triple ... forms of the word to * be pluralized. When the number to be pluralized * exceeds the length of the args, it will use the last * entry in the array. * * e.g. ['single', 'double', 'triple', 'multiple'] */ exports.pluralize = function (value) { var args = _.toArray(arguments, 1) return args.length > 1 ? (args[value % 10 - 1] || args[args.length - 1]) : (args[0] + (value === 1 ? '' : 's')) } /** * A special filter that takes a handler function, * wraps it so it only gets triggered on specific * keypresses. v-on only. * * @param {String} key */ var keyCodes = { esc: 27, tab: 9, enter: 13, 'delete': 46, up: 38, left: 37, right: 39, down: 40 } exports.key = function (handler, key) { if (!handler) return var code = keyCodes[key] if (!code) { code = parseInt(key, 10) } return function (e) { if (e.keyCode === code) { return handler.call(this, e) } } } // expose keycode hash exports.key.keyCodes = keyCodes /** * Install special array filters */ _.extend(exports, __webpack_require__(54)) /***/ }, /* 54 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var Path = __webpack_require__(23) /** * Filter filter for v-repeat * * @param {String} searchKey * @param {String} [delimiter] * @param {String} dataKey */ exports.filterBy = function (arr, search, delimiter, dataKey) { // allow optional `in` delimiter // because why not if (delimiter && delimiter !== 'in') { dataKey = delimiter } if (search == null) { return arr } // cast to lowercase string search = ('' + search).toLowerCase() return arr.filter(function (item) { return dataKey ? contains(Path.get(item, dataKey), search) : contains(item, search) }) } /** * Filter filter for v-repeat * * @param {String} sortKey * @param {String} reverse */ exports.orderBy = function (arr, sortKey, reverse) { if (!sortKey) { return arr } var order = 1 if (arguments.length > 2) { if (reverse === '-1') { order = -1 } else { order = reverse ? -1 : 1 } } // sort on a copy to avoid mutating original array return arr.slice().sort(function (a, b) { if (sortKey !== '$key' && sortKey !== '$value') { if (a && '$value' in a) a = a.$value if (b && '$value' in b) b = b.$value } a = _.isObject(a) ? Path.get(a, sortKey) : a b = _.isObject(b) ? Path.get(b, sortKey) : b return a === b ? 0 : a > b ? order : -order }) } /** * String contain helper * * @param {*} val * @param {String} search */ function contains (val, search) { if (_.isPlainObject(val)) { for (var key in val) { if (contains(val[key], search)) { return true } } } else if (_.isArray(val)) { var i = val.length while (i--) { if (contains(val[i], search)) { return true } } } else if (val != null) { return val.toString().toLowerCase().indexOf(search) > -1 } } /***/ }, /* 55 */ /***/ function(module, exports, __webpack_require__) { var mergeOptions = __webpack_require__(1).mergeOptions /** * The main init sequence. This is called for every * instance, including ones that are created from extended * constructors. * * @param {Object} options - this options object should be * the result of merging class * options and the options passed * in to the constructor. */ exports._init = function (options) { options = options || {} this.$el = null this.$parent = options._parent this.$root = options._root || this this.$children = [] this.$ = {} // child vm references this.$$ = {} // element references this._watchers = [] // all watchers as an array this._directives = [] // all directives this._childCtors = {} // inherit:true constructors // a flag to avoid this being observed this._isVue = true // events bookkeeping this._events = {} // registered callbacks this._eventsCount = {} // for $broadcast optimization this._eventCancelled = false // for event cancellation // block instance properties this._isBlock = false this._blockStart = // @type {CommentNode} this._blockEnd = null // @type {CommentNode} // lifecycle state this._isCompiled = this._isDestroyed = this._isReady = this._isAttached = this._isBeingDestroyed = false this._unlinkFn = null // context: the scope in which the component was used, // and the scope in which props and contents of this // instance should be compiled in. this._context = options._context || options._parent // push self into parent / transclusion host if (this.$parent) { this.$parent.$children.push(this) } // props used in v-repeat diffing this._reused = false this._staggerOp = null // merge options. options = this.$options = mergeOptions( this.constructor.options, options, this ) // initialize data as empty object. // it will be filled up in _initScope(). this._data = {} // initialize data observation and scope inheritance. this._initScope() // setup event system and option events. this._initEvents() // call created hook this._callHook('created') // if `el` option is passed, start compilation. if (options.el) { this.$mount(options.el) } } /***/ }, /* 56 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var inDoc = _.inDoc /** * Setup the instance's option events & watchers. * If the value is a string, we pull it from the * instance's methods by name. */ exports._initEvents = function () { var options = this.$options registerCallbacks(this, '$on', options.events) registerCallbacks(this, '$watch', options.watch) } /** * Register callbacks for option events and watchers. * * @param {Vue} vm * @param {String} action * @param {Object} hash */ function registerCallbacks (vm, action, hash) { if (!hash) return var handlers, key, i, j for (key in hash) { handlers = hash[key] if (_.isArray(handlers)) { for (i = 0, j = handlers.length; i < j; i++) { register(vm, action, key, handlers[i]) } } else { register(vm, action, key, handlers) } } } /** * Helper to register an event/watch callback. * * @param {Vue} vm * @param {String} action * @param {String} key * @param {Function|String|Object} handler * @param {Object} [options] */ function register (vm, action, key, handler, options) { var type = typeof handler if (type === 'function') { vm[action](key, handler, options) } else if (type === 'string') { var methods = vm.$options.methods var method = methods && methods[handler] if (method) { vm[action](key, method, options) } else { _.warn( 'Unknown method: "' + handler + '" when ' + 'registering callback for ' + action + ': "' + key + '".' ) } } else if (handler && type === 'object') { register(vm, action, key, handler.handler, handler) } } /** * Setup recursive attached/detached calls */ exports._initDOMHooks = function () { this.$on('hook:attached', onAttached) this.$on('hook:detached', onDetached) } /** * Callback to recursively call attached hook on children */ function onAttached () { if (!this._isAttached) { this._isAttached = true this.$children.forEach(callAttach) } } /** * Iterator to call attached hook * * @param {Vue} child */ function callAttach (child) { if (!child._isAttached && inDoc(child.$el)) { child._callHook('attached') } } /** * Callback to recursively call detached hook on children */ function onDetached () { if (this._isAttached) { this._isAttached = false this.$children.forEach(callDetach) } } /** * Iterator to call detached hook * * @param {Vue} child */ function callDetach (child) { if (child._isAttached && !inDoc(child.$el)) { child._callHook('detached') } } /** * Trigger all handlers for a hook * * @param {String} hook */ exports._callHook = function (hook) { var handlers = this.$options[hook] if (handlers) { for (var i = 0, j = handlers.length; i < j; i++) { handlers[i].call(this) } } this.$emit('hook:' + hook) } /***/ }, /* 57 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var compiler = __webpack_require__(10) var Observer = __webpack_require__(18) var Dep = __webpack_require__(19) /** * Setup the scope of an instance, which contains: * - observed data * - computed properties * - user methods * - meta properties */ exports._initScope = function () { this._initProps() this._initMeta() this._initMethods() this._initData() this._initComputed() } /** * Initialize props. */ exports._initProps = function () { var options = this.$options var el = options.el var props = options.props if (props && !el) { _.warn( 'Props will not be compiled if no `el` option is ' + 'provided at instantiation.' ) } // make sure to convert string selectors into element now el = options.el = _.query(el) this._propsUnlinkFn = el && props ? compiler.compileAndLinkProps( this, el, props ) : null } /** * Initialize the data. */ exports._initData = function () { var propsData = this._data var optionsDataFn = this.$options.data var optionsData = optionsDataFn && optionsDataFn() if (optionsData) { this._data = optionsData for (var prop in propsData) { if (this._props[prop].raw !== null) { optionsData.$set(prop, propsData[prop]) } } } var data = this._data // proxy data on instance var keys = Object.keys(data) var i, key i = keys.length while (i--) { key = keys[i] if (!_.isReserved(key)) { this._proxy(key) } } // observe data Observer.create(data, this) } /** * Swap the isntance's $data. Called in $data's setter. * * @param {Object} newData */ exports._setData = function (newData) { newData = newData || {} var oldData = this._data this._data = newData var keys, key, i // copy props. // this should only happen during a v-repeat of component // that also happens to have compiled props. var props = this.$options.props if (props) { i = props.length while (i--) { key = props[i].name if (key !== '$data' && !newData.hasOwnProperty(key)) { newData.$set(key, oldData[key]) } } } // unproxy keys not present in new data keys = Object.keys(oldData) i = keys.length while (i--) { key = keys[i] if (!_.isReserved(key) && !(key in newData)) { this._unproxy(key) } } // proxy keys not already proxied, // and trigger change for changed values keys = Object.keys(newData) i = keys.length while (i--) { key = keys[i] if (!this.hasOwnProperty(key) && !_.isReserved(key)) { // new property this._proxy(key) } } oldData.__ob__.removeVm(this) Observer.create(newData, this) this._digest() } /** * Proxy a property, so that * vm.prop === vm._data.prop * * @param {String} key */ exports._proxy = function (key) { // need to store ref to self here // because these getter/setters might // be called by child instances! var self = this Object.defineProperty(self, key, { configurable: true, enumerable: true, get: function proxyGetter () { return self._data[key] }, set: function proxySetter (val) { self._data[key] = val } }) } /** * Unproxy a property. * * @param {String} key */ exports._unproxy = function (key) { delete this[key] } /** * Force update on every watcher in scope. */ exports._digest = function () { var i = this._watchers.length while (i--) { this._watchers[i].update(true) // shallow updates } var children = this.$children i = children.length while (i--) { var child = children[i] if (child.$options.inherit) { child._digest() } } } /** * Setup computed properties. They are essentially * special getter/setters */ function noop () {} exports._initComputed = function () { var computed = this.$options.computed if (computed) { for (var key in computed) { var userDef = computed[key] var def = { enumerable: true, configurable: true } if (typeof userDef === 'function') { def.get = _.bind(userDef, this) def.set = noop } else { def.get = userDef.get ? _.bind(userDef.get, this) : noop def.set = userDef.set ? _.bind(userDef.set, this) : noop } Object.defineProperty(this, key, def) } } } /** * Setup instance methods. Methods must be bound to the * instance since they might be called by children * inheriting them. */ exports._initMethods = function () { var methods = this.$options.methods if (methods) { for (var key in methods) { this[key] = _.bind(methods[key], this) } } } /** * Initialize meta information like $index, $key & $value. */ exports._initMeta = function () { var metas = this.$options._meta if (metas) { for (var key in metas) { this._defineMeta(key, metas[key]) } } } /** * Define a meta property, e.g $index, $key, $value * which only exists on the vm instance but not in $data. * * @param {String} key * @param {*} value */ exports._defineMeta = function (key, value) { var dep = new Dep() Object.defineProperty(this, key, { enumerable: true, configurable: true, get: function metaGetter () { dep.depend() return value }, set: function metaSetter (val) { if (val !== value) { value = val dep.notify() } } }) } /***/ }, /* 58 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var Directive = __webpack_require__(59) var compiler = __webpack_require__(10) /** * Transclude, compile and link element. * * If a pre-compiled linker is available, that means the * passed in element will be pre-transcluded and compiled * as well - all we need to do is to call the linker. * * Otherwise we need to call transclude/compile/link here. * * @param {Element} el * @return {Element} */ exports._compile = function (el) { var options = this.$options var host = this._host if (options._linkFn) { // pre-transcluded with linker, just use it this._initElement(el) this._unlinkFn = options._linkFn(this, el, host) } else { // transclude and init element // transclude can potentially replace original // so we need to keep reference; this step also injects // the template and caches the original attributes // on the container node and replacer node. var original = el el = compiler.transclude(el, options) this._initElement(el) // root is always compiled per-instance, because // container attrs and props can be different every time. var rootUnlinkFn = compiler.compileAndLinkRoot(this, el, options) // compile and link the rest var linker var ctor = this.constructor // component compilation can be cached // as long as it's not using inline-template if (options._linkerCachable) { linker = ctor.linker if (!linker) { linker = ctor.linker = compiler.compile(el, options) } } var contentUnlinkFn = linker ? linker(this, el) : compiler.compile(el, options)(this, el, host) this._unlinkFn = function () { rootUnlinkFn() // passing destroying: true to avoid searching and // splicing the directives contentUnlinkFn(true) } // finally replace original if (options.replace) { _.replace(original, el) } } return el } /** * Initialize instance element. Called in the public * $mount() method. * * @param {Element} el */ exports._initElement = function (el) { if (el instanceof DocumentFragment) { this._isBlock = true this.$el = this._blockStart = el.firstChild this._blockEnd = el.lastChild // set persisted text anchors to empty if (this._blockStart.nodeType === 3) { this._blockStart.data = this._blockEnd.data = '' } this._blockFragment = el } else { this.$el = el } this.$el.__vue__ = this this._callHook('beforeCompile') } /** * Create and bind a directive to an element. * * @param {String} name - directive name * @param {Node} node - target node * @param {Object} desc - parsed directive descriptor * @param {Object} def - directive definition object * @param {Vue|undefined} host - transclusion host component */ exports._bindDir = function (name, node, desc, def, host) { this._directives.push( new Directive(name, node, this, desc, def, host) ) } /** * Teardown an instance, unobserves the data, unbind all the * directives, turn off all the event listeners, etc. * * @param {Boolean} remove - whether to remove the DOM node. * @param {Boolean} deferCleanup - if true, defer cleanup to * be called later */ exports._destroy = function (remove, deferCleanup) { if (this._isBeingDestroyed) { return } this._callHook('beforeDestroy') this._isBeingDestroyed = true var i // remove self from parent. only necessary // if parent is not being destroyed as well. var parent = this.$parent if (parent && !parent._isBeingDestroyed) { parent.$children.$remove(this) } // destroy all children. i = this.$children.length while (i--) { this.$children[i].$destroy() } // teardown props if (this._propsUnlinkFn) { this._propsUnlinkFn() } // teardown all directives. this also tearsdown all // directive-owned watchers. if (this._unlinkFn) { this._unlinkFn() } i = this._watchers.length while (i--) { this._watchers[i].teardown() } // remove reference to self on $el if (this.$el) { this.$el.__vue__ = null } // remove DOM element var self = this if (remove && this.$el) { this.$remove(function () { self._cleanup() }) } else if (!deferCleanup) { this._cleanup() } } /** * Clean up to ensure garbage collection. * This is called after the leave transition if there * is any. */ exports._cleanup = function () { // remove reference from data ob // frozen object may not have observer. if (this._data.__ob__) { this._data.__ob__.removeVm(this) } // Clean up references to private properties and other // instances. preserve reference to _data so that proxy // accessors still work. The only potential side effect // here is that mutating the instance after it's destroyed // may affect the state of other components that are still // observing the same object, but that seems to be a // reasonable responsibility for the user rather than // always throwing an error on them. this.$el = this.$parent = this.$root = this.$children = this._watchers = this._directives = null // call the last hook... this._isDestroyed = true this._callHook('destroyed') // turn off all instance listeners. this.$off() } /***/ }, /* 59 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var config = __webpack_require__(6) var Watcher = __webpack_require__(17) var textParser = __webpack_require__(13) var expParser = __webpack_require__(22) /** * A directive links a DOM element with a piece of data, * which is the result of evaluating an expression. * It registers a watcher with the expression and calls * the DOM update function when a change is triggered. * * @param {String} name * @param {Node} el * @param {Vue} vm * @param {Object} descriptor * - {String} expression * - {String} [arg] * - {Array<Object>} [filters] * @param {Object} def - directive definition object * @param {Vue|undefined} host - transclusion host target * @constructor */ function Directive (name, el, vm, descriptor, def, host) { // public this.name = name this.el = el this.vm = vm // copy descriptor props this.raw = descriptor.raw this.expression = descriptor.expression this.arg = descriptor.arg this.filters = descriptor.filters // private this._descriptor = descriptor this._host = host this._locked = false this._bound = false // init this._bind(def) } var p = Directive.prototype /** * Initialize the directive, mixin definition properties, * setup the watcher, call definition bind() and update() * if present. * * @param {Object} def */ p._bind = function (def) { if (this.name !== 'cloak' && this.el && this.el.removeAttribute) { this.el.removeAttribute(config.prefix + this.name) } if (typeof def === 'function') { this.update = def } else { _.extend(this, def) } this._watcherExp = this.expression this._checkDynamicLiteral() if (this.bind) { this.bind() } if (this._watcherExp && (this.update || this.twoWay) && (!this.isLiteral || this._isDynamicLiteral) && !this._checkStatement()) { // wrapped updater for context var dir = this var update = this._update = this.update ? function (val, oldVal) { if (!dir._locked) { dir.update(val, oldVal) } } : function () {} // noop if no update is provided // pre-process hook called before the value is piped // through the filters. used in v-repeat. var preProcess = this._preProcess ? _.bind(this._preProcess, this) : null var watcher = this._watcher = new Watcher( this.vm, this._watcherExp, update, // callback { filters: this.filters, twoWay: this.twoWay, deep: this.deep, preProcess: preProcess } ) if (this._initValue != null) { watcher.set(this._initValue) } else if (this.update) { this.update(watcher.value) } } this._bound = true } /** * check if this is a dynamic literal binding. * * e.g. v-component="{{currentView}}" */ p._checkDynamicLiteral = function () { var expression = this.expression if (expression && this.isLiteral) { var tokens = textParser.parse(expression) if (tokens) { var exp = textParser.tokensToExp(tokens) this.expression = this.vm.$get(exp) this._watcherExp = exp this._isDynamicLiteral = true } } } /** * Check if the directive is a function caller * and if the expression is a callable one. If both true, * we wrap up the expression and use it as the event * handler. * * e.g. v-on="click: a++" * * @return {Boolean} */ p._checkStatement = function () { var expression = this.expression if ( expression && this.acceptStatement && !expParser.isSimplePath(expression) ) { var fn = expParser.parse(expression).get var vm = this.vm var handler = function () { fn.call(vm, vm) } if (this.filters) { handler = vm._applyFilters(handler, null, this.filters) } this.update(handler) return true } } /** * Check for an attribute directive param, e.g. lazy * * @param {String} name * @return {String} */ p._checkParam = function (name) { var param = this.el.getAttribute(name) if (param !== null) { this.el.removeAttribute(name) } return param } /** * Teardown the watcher and call unbind. */ p._teardown = function () { if (this._bound) { this._bound = false if (this.unbind) { this.unbind() } if (this._watcher) { this._watcher.teardown() } this.vm = this.el = this._watcher = null } } /** * Set the corresponding value with the setter. * This should only be used in two-way directives * e.g. v-model. * * @param {*} value * @public */ p.set = function (value) { if (this.twoWay) { this._withLock(function () { this._watcher.set(value) }) } } /** * Execute a function while preventing that function from * triggering updates on this directive instance. * * @param {Function} fn */ p._withLock = function (fn) { var self = this self._locked = true fn.call(self) _.nextTick(function () { self._locked = false }) } module.exports = Directive /***/ }, /* 60 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) /** * Apply a list of filter (descriptors) to a value. * Using plain for loops here because this will be called in * the getter of any watcher with filters so it is very * performance sensitive. * * @param {*} value * @param {*} [oldValue] * @param {Array} filters * @param {Boolean} write * @return {*} */ exports._applyFilters = function (value, oldValue, filters, write) { var filter, fn, args, arg, offset, i, l, j, k for (i = 0, l = filters.length; i < l; i++) { filter = filters[i] fn = _.resolveAsset(this.$options, 'filters', filter.name) _.assertAsset(fn, 'filter', filter.name) if (!fn) continue fn = write ? fn.write : (fn.read || fn) if (typeof fn !== 'function') continue args = write ? [value, oldValue] : [value] offset = write ? 2 : 1 if (filter.args) { for (j = 0, k = filter.args.length; j < k; j++) { arg = filter.args[j] args[j + offset] = arg.dynamic ? this.$get(arg.value) : arg.value } } value = fn.apply(this, args) } return value } /** * Resolve a component, depending on whether the component * is defined normally or using an async factory function. * Resolves synchronously if already resolved, otherwise * resolves asynchronously and caches the resolved * constructor on the factory. * * @param {String} id * @param {Function} cb */ exports._resolveComponent = function (id, cb) { var factory = _.resolveAsset(this.$options, 'components', id) _.assertAsset(factory, 'component', id) // async component factory if (!factory.options) { if (factory.resolved) { // cached cb(factory.resolved) } else if (factory.requested) { // pool callbacks factory.pendingCallbacks.push(cb) } else { factory.requested = true var cbs = factory.pendingCallbacks = [cb] factory(function resolve (res) { if (_.isPlainObject(res)) { res = _.Vue.extend(res) } // cache resolved factory.resolved = res // invoke callbacks for (var i = 0, l = cbs.length; i < l; i++) { cbs[i](res) } }, function reject (reason) { _.warn( 'Failed to resolve async component: ' + id + '. ' + (reason ? '\nReason: ' + reason : '') ) }) } } else { // normal component cb(factory) } } /***/ }, /* 61 */ /***/ function(module, exports, __webpack_require__) { var Watcher = __webpack_require__(17) var Path = __webpack_require__(23) var textParser = __webpack_require__(13) var dirParser = __webpack_require__(15) var expParser = __webpack_require__(22) var filterRE = /[^|]\|[^|]/ /** * Get the value from an expression on this vm. * * @param {String} exp * @return {*} */ exports.$get = function (exp) { var res = expParser.parse(exp) if (res) { try { return res.get.call(this, this) } catch (e) {} } } /** * Set the value from an expression on this vm. * The expression must be a valid left-hand * expression in an assignment. * * @param {String} exp * @param {*} val */ exports.$set = function (exp, val) { var res = expParser.parse(exp, true) if (res && res.set) { res.set.call(this, this, val) } } /** * Add a property on the VM * * @param {String} key * @param {*} val */ exports.$add = function (key, val) { this._data.$add(key, val) } /** * Delete a property on the VM * * @param {String} key */ exports.$delete = function (key) { this._data.$delete(key) } /** * Watch an expression, trigger callback when its * value changes. * * @param {String} exp * @param {Function} cb * @param {Object} [options] * - {Boolean} deep * - {Boolean} immediate * - {Boolean} user * @return {Function} - unwatchFn */ exports.$watch = function (exp, cb, options) { var vm = this var wrappedCb = function (val, oldVal) { cb.call(vm, val, oldVal) } var watcher = new Watcher(vm, exp, wrappedCb, { deep: options && options.deep, user: !options || options.user !== false }) if (options && options.immediate) { wrappedCb(watcher.value) } return function unwatchFn () { watcher.teardown() } } /** * Evaluate a text directive, including filters. * * @param {String} text * @return {String} */ exports.$eval = function (text) { // check for filters. if (filterRE.test(text)) { var dir = dirParser.parse(text)[0] // the filter regex check might give false positive // for pipes inside strings, so it's possible that // we don't get any filters here var val = this.$get(dir.expression) return dir.filters ? this._applyFilters(val, null, dir.filters) : val } else { // no filter return this.$get(text) } } /** * Interpolate a piece of template text. * * @param {String} text * @return {String} */ exports.$interpolate = function (text) { var tokens = textParser.parse(text) var vm = this if (tokens) { return tokens.length === 1 ? vm.$eval(tokens[0].value) : tokens.map(function (token) { return token.tag ? vm.$eval(token.value) : token.value }).join('') } else { return text } } /** * Log instance data as a plain JS object * so that it is easier to inspect in console. * This method assumes console is available. * * @param {String} [path] */ exports.$log = function (path) { var data = path ? Path.get(this._data, path) : this._data if (data) { data = JSON.parse(JSON.stringify(data)) } console.log(data) } /***/ }, /* 62 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var transition = __webpack_require__(34) /** * Convenience on-instance nextTick. The callback is * auto-bound to the instance, and this avoids component * modules having to rely on the global Vue. * * @param {Function} fn */ exports.$nextTick = function (fn) { _.nextTick(fn, this) } /** * Append instance to target * * @param {Node} target * @param {Function} [cb] * @param {Boolean} [withTransition] - defaults to true */ exports.$appendTo = function (target, cb, withTransition) { return insert( this, target, cb, withTransition, append, transition.append ) } /** * Prepend instance to target * * @param {Node} target * @param {Function} [cb] * @param {Boolean} [withTransition] - defaults to true */ exports.$prependTo = function (target, cb, withTransition) { target = query(target) if (target.hasChildNodes()) { this.$before(target.firstChild, cb, withTransition) } else { this.$appendTo(target, cb, withTransition) } return this } /** * Insert instance before target * * @param {Node} target * @param {Function} [cb] * @param {Boolean} [withTransition] - defaults to true */ exports.$before = function (target, cb, withTransition) { return insert( this, target, cb, withTransition, before, transition.before ) } /** * Insert instance after target * * @param {Node} target * @param {Function} [cb] * @param {Boolean} [withTransition] - defaults to true */ exports.$after = function (target, cb, withTransition) { target = query(target) if (target.nextSibling) { this.$before(target.nextSibling, cb, withTransition) } else { this.$appendTo(target.parentNode, cb, withTransition) } return this } /** * Remove instance from DOM * * @param {Function} [cb] * @param {Boolean} [withTransition] - defaults to true */ exports.$remove = function (cb, withTransition) { if (!this.$el.parentNode) { return cb && cb() } var inDoc = this._isAttached && _.inDoc(this.$el) // if we are not in document, no need to check // for transitions if (!inDoc) withTransition = false var op var self = this var realCb = function () { if (inDoc) self._callHook('detached') if (cb) cb() } if ( this._isBlock && !this._blockFragment.hasChildNodes() ) { op = withTransition === false ? append : transition.removeThenAppend blockOp(this, this._blockFragment, op, realCb) } else { op = withTransition === false ? remove : transition.remove op(this.$el, this, realCb) } return this } /** * Shared DOM insertion function. * * @param {Vue} vm * @param {Element} target * @param {Function} [cb] * @param {Boolean} [withTransition] * @param {Function} op1 - op for non-transition insert * @param {Function} op2 - op for transition insert * @return vm */ function insert (vm, target, cb, withTransition, op1, op2) { target = query(target) var targetIsDetached = !_.inDoc(target) var op = withTransition === false || targetIsDetached ? op1 : op2 var shouldCallHook = !targetIsDetached && !vm._isAttached && !_.inDoc(vm.$el) if (vm._isBlock) { blockOp(vm, target, op, cb) } else { op(vm.$el, target, vm, cb) } if (shouldCallHook) { vm._callHook('attached') } return vm } /** * Execute a transition operation on a block instance, * iterating through all its block nodes. * * @param {Vue} vm * @param {Node} target * @param {Function} op * @param {Function} cb */ function blockOp (vm, target, op, cb) { var current = vm._blockStart var end = vm._blockEnd var next while (next !== end) { next = current.nextSibling op(current, target, vm) current = next } op(end, target, vm, cb) } /** * Check for selectors * * @param {String|Element} el */ function query (el) { return typeof el === 'string' ? document.querySelector(el) : el } /** * Append operation that takes a callback. * * @param {Node} el * @param {Node} target * @param {Vue} vm - unused * @param {Function} [cb] */ function append (el, target, vm, cb) { target.appendChild(el) if (cb) cb() } /** * InsertBefore operation that takes a callback. * * @param {Node} el * @param {Node} target * @param {Vue} vm - unused * @param {Function} [cb] */ function before (el, target, vm, cb) { _.before(el, target) if (cb) cb() } /** * Remove operation that takes a callback. * * @param {Node} el * @param {Vue} vm - unused * @param {Function} [cb] */ function remove (el, vm, cb) { _.remove(el) if (cb) cb() } /***/ }, /* 63 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) /** * Listen on the given `event` with `fn`. * * @param {String} event * @param {Function} fn */ exports.$on = function (event, fn) { (this._events[event] || (this._events[event] = [])) .push(fn) modifyListenerCount(this, event, 1) return this } /** * Adds an `event` listener that will be invoked a single * time then automatically removed. * * @param {String} event * @param {Function} fn */ exports.$once = function (event, fn) { var self = this function on () { self.$off(event, on) fn.apply(this, arguments) } on.fn = fn this.$on(event, on) return this } /** * Remove the given callback for `event` or all * registered callbacks. * * @param {String} event * @param {Function} fn */ exports.$off = function (event, fn) { var cbs // all if (!arguments.length) { if (this.$parent) { for (event in this._events) { cbs = this._events[event] if (cbs) { modifyListenerCount(this, event, -cbs.length) } } } this._events = {} return this } // specific event cbs = this._events[event] if (!cbs) { return this } if (arguments.length === 1) { modifyListenerCount(this, event, -cbs.length) this._events[event] = null return this } // specific handler var cb var i = cbs.length while (i--) { cb = cbs[i] if (cb === fn || cb.fn === fn) { modifyListenerCount(this, event, -1) cbs.splice(i, 1) break } } return this } /** * Trigger an event on self. * * @param {String} event */ exports.$emit = function (event) { this._eventCancelled = false var cbs = this._events[event] if (cbs) { // avoid leaking arguments: // http://jsperf.com/closure-with-arguments var i = arguments.length - 1 var args = new Array(i) while (i--) { args[i] = arguments[i + 1] } i = 0 cbs = cbs.length > 1 ? _.toArray(cbs) : cbs for (var l = cbs.length; i < l; i++) { if (cbs[i].apply(this, args) === false) { this._eventCancelled = true } } } return this } /** * Recursively broadcast an event to all children instances. * * @param {String} event * @param {...*} additional arguments */ exports.$broadcast = function (event) { // if no child has registered for this event, // then there's no need to broadcast. if (!this._eventsCount[event]) return var children = this.$children for (var i = 0, l = children.length; i < l; i++) { var child = children[i] child.$emit.apply(child, arguments) if (!child._eventCancelled) { child.$broadcast.apply(child, arguments) } } return this } /** * Recursively propagate an event up the parent chain. * * @param {String} event * @param {...*} additional arguments */ exports.$dispatch = function () { var parent = this.$parent while (parent) { parent.$emit.apply(parent, arguments) parent = parent._eventCancelled ? null : parent.$parent } return this } /** * Modify the listener counts on all parents. * This bookkeeping allows $broadcast to return early when * no child has listened to a certain event. * * @param {Vue} vm * @param {String} event * @param {Number} count */ var hookRE = /^hook:/ function modifyListenerCount (vm, event, count) { var parent = vm.$parent // hooks do not get broadcasted so no need // to do bookkeeping for them if (!parent || !count || hookRE.test(event)) return while (parent) { parent._eventsCount[event] = (parent._eventsCount[event] || 0) + count parent = parent.$parent } } /***/ }, /* 64 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) /** * Create a child instance that prototypally inehrits * data on parent. To achieve that we create an intermediate * constructor with its prototype pointing to parent. * * @param {Object} opts * @param {Function} [BaseCtor] * @return {Vue} * @public */ exports.$addChild = function (opts, BaseCtor) { BaseCtor = BaseCtor || _.Vue opts = opts || {} var parent = this var ChildVue var inherit = opts.inherit !== undefined ? opts.inherit : BaseCtor.options.inherit if (inherit) { var ctors = parent._childCtors ChildVue = ctors[BaseCtor.cid] if (!ChildVue) { var optionName = BaseCtor.options.name var className = optionName ? _.classify(optionName) : 'VueComponent' ChildVue = new Function( 'return function ' + className + ' (options) {' + 'this.constructor = ' + className + ';' + 'this._init(options) }' )() ChildVue.options = BaseCtor.options ChildVue.linker = BaseCtor.linker // important: transcluded inline repeaters should // inherit from outer scope rather than host ChildVue.prototype = opts._context || this ctors[BaseCtor.cid] = ChildVue } } else { ChildVue = BaseCtor } opts._parent = parent opts._root = parent.$root var child = new ChildVue(opts) return child } /***/ }, /* 65 */ /***/ function(module, exports, __webpack_require__) { var _ = __webpack_require__(1) var compiler = __webpack_require__(10) /** * Set instance target element and kick off the compilation * process. The passed in `el` can be a selector string, an * existing Element, or a DocumentFragment (for block * instances). * * @param {Element|DocumentFragment|string} el * @public */ exports.$mount = function (el) { if (this._isCompiled) { _.warn('$mount() should be called only once.') return } el = _.query(el) if (!el) { el = document.createElement('div') } this._compile(el) this._isCompiled = true this._callHook('compiled') this._initDOMHooks() if (_.inDoc(this.$el)) { this._callHook('attached') ready.call(this) } else { this.$once('hook:attached', ready) } return this } /** * Mark an instance as ready. */ function ready () { this._isAttached = true this._isReady = true this._callHook('ready') } /** * Teardown the instance, simply delegate to the internal * _destroy. */ exports.$destroy = function (remove, deferCleanup) { this._destroy(remove, deferCleanup) } /** * Partially compile a piece of DOM and return a * decompile function. * * @param {Element|DocumentFragment} el * @param {Vue} [host] * @return {Function} */ exports.$compile = function (el, host) { return compiler.compile(el, this.$options, true, host)(this, el) } /***/ } /******/ ]) }); ;
src/Console.js
sgnh/react-console-wrapper
import React from 'react'; const { array, string, bool, shape } = React.PropTypes; const Console = (props) => { if (props.assert.assertion) { console.assert(props.assert.assertion, props.assert.message); } if (props.clear) { console.clear(); } if (props.count) { console.count(props.count); } if (props.error) { console.error(props.error); } if (props.group) { console.group(); } if (props.groupColapsed) { console.groupCollapsed(); } if (props.groupEnd) { console.groupEnd(); } if (props.info) { console.info(props.info); } if (props.log) { console.log(props.log); } if (props.table.data.length) { console.table(props.table.data, props.table.columns); } if (props.time) { console.time(props.time); } if (props.timeEnd) { console.timeEnd(props.timeEnd); } if (props.trace) { console.trace(); } if (props.warn) { console.warn(props.warn); } return null; }; Console.propTypes = { assert: shape({ assertion: bool, message: string, }), clear: bool, count: string, error: string, group: bool, groupColapsed: bool, groupEnd: bool, info: string, log: string, table: shape({ data: array, columns: array, }), time: string, timeEnd: string, trace: bool, warn: string, }; Console.defaultProps = { assert: { assertion: false, message: '', }, clear: false, count: '', error: '', group: false, groupColapsed: false, groupEnd: false, info: '', log: '', table: { data: [], columns: [], }, time: '', timeEnd: '', trace: false, warn: '', }; export default Console;
ajax/libs/flocks.js/0.16.18/flocks.js
fredericksilva/cdnjs
/** @jsx React.DOM */ /* jshint node: true, browser: true, newcap: false */ /* eslint max-statements: 0, no-else-return: 0, brace-style: 0 */ /* eslint-env node,browser */ /** * The Flocks library module. * * @module Flocks * @main Flocks * @class Flocks */ // if it's in a <script> it's defined already // otherwise assume commonjs /* eslint-disable no-use-before-define, vars-on-top */ if (typeof React === "undefined") { var React = require("react"); } /* eslint-enable no-use-before-define, vars-on-top */ // wrap the remainder (function() { "use strict"; var Mixin, exports, initialized = false, updateBlocks = 0, tagtype, /* eslint-disable no-unused-vars */ dirty = false, handler = function(Ignored) { return true; }, /* eslint-ensable no-unused-vars */ finalizer = function() { return true; }, prevFCtx = {}, nextFCtx = {}, flocks2Ctxs = { "flocks2context" : React.PropTypes.object }; // ... lol function arrayMember(Item, Array) { return (!!(~( Array.indexOf(Item, 0) ))); } function isArray(maybeArray) { return (Object.prototype.toString.call(maybeArray) === "[object Array]"); } function isUndefined(maybeUndefined) { return (typeof maybeUndefined === "undefined"); } function isNonArrayObject(maybeArray) { if (typeof maybeArray !== "object") { return false; } if (Object.prototype.toString.call(maybeArray) === "[object Array]") { return false; } return true; } function flocksLog(Level, Message) { if (typeof Level === "string") { if (arrayMember(Level, ["warn","debug","error","log","info","exception","assert"])) { console[Level]("Flocks2 [" + Level + "] " + Message.toString()); } else { console.log("Flocks2 [Unknown level] " + Message.toString()); } } else if (isUndefined(nextFCtx.flocks2Config)) { console.log("Flocks2 pre-config [" + Level.toString() + "] " + Message.toString()); } else if (nextFCtx.flocks2Config.log_level >= Level) { console.log("Flocks2 [" + Level.toString() + "] " + Message.toString()); } } function attemptUpdate() { flocksLog(3, " - Flocks2 attempting update"); dirty = true; if (!(initialized)) { flocksLog(1, " x Flocks2 skipped update: root is not initialized"); return null; } if (updateBlocks) { flocksLog(1, " x Flocks2 skipped update: lock count updateBlocks is non-zero"); return null; } /* todo see issue #9 https://github.com/StoneCypher/flocks.js/issues/9 if (deepCompare(nextFCtx, prevFCtx)) { flocksLog(2, " x Flocks2 skipped update: no update to state"); return true; } */ if (!(handler(nextFCtx))) { flocksLog(0, " ! Flocks2 rolling back update: handler rejected propset"); nextFCtx = prevFCtx; dirty = false; return null; } prevFCtx = nextFCtx; flocksLog(3, " - Flocks2 update passed"); React.render( React.createFactory(tagtype)( { "flocks2context" : nextFCtx } ), document.body ); dirty = false; flocksLog(3, " - Flocks2 update complete; finalizing"); finalizer(); return true; } function enforceString(On, Label) { if (typeof On !== "string") { throw Label || "Argument must be a string"; } } function enforceArray(On, Label) { if (!isArray(On)) { throw Label || "Argument must be an array"; } } function enforceNonArrayObject(On, Label) { if (!isNonArrayObject(On)) { throw Label || "Argument must be a non-array object"; } } function setByKey(Key, MaybeValue) { enforceString(Key, "Flocks2 set/2 must take a string for its key"); nextFCtx[Key] = MaybeValue; flocksLog(1, " - Flocks2 setByKey \"" + Key + "\""); attemptUpdate(); } function setTargetByPath(Path, Target, NewVal) { var NextPath, OldVal; // it gets hoisted anyway, so it triggers eslint warnings when inlined // might as well be explicit about it if (!(isArray(Path))) { throw "Path must be an array!"; } if (Path.length === 0) { OldVal = Target; Target = NewVal; return OldVal; } if (Path.length === 1) { OldVal = Target[Path[0]]; Target[Path[0]] = NewVal; return OldVal; } if (["string","number"].indexOf(typeof Path[0]) !== -1) { NextPath = Path.splice(1, Number.MAX_VALUE); return setTargetByPath(NextPath, Target[Path[0]], NewVal); } } function setByPath(Path, NewVal) { enforceArray(Path, "Flocks2 setByPathh/2 must take an array for its key"); flocksLog(1, " - Flocks2 setByPath \"" + Path.join("|") + "\""); setTargetByPath(Path, nextFCtx, NewVal); attemptUpdate(); } // todo // function setByObject(Key, MaybeValue) { // flocksLog(0, " - Flocks2 setByObject stub"); // attemptUpdate(); // } function set(Key, MaybeValue) { flocksLog(3, " - Flocks2 multi-set"); if (typeof Key === "string") { setByKey(Key, MaybeValue); } else if (isArray(Key)) { setByPath(Key, MaybeValue); } // else if (isNonArrayObject(Key)) { setByObject(Key); } // todo else { throw "Flocks2 set/1,2 key must be a string or an array"; } } function getByPath(Path, Target) { var NextPath; if (!(isArray(Path))) { throw "path must be an array!"; } if (Path.length === 0) { return Target; } if (Path.length === 1) { return Target[Path[0]]; } if (["string","number"].indexOf(typeof Path[0]) !== -1) { NextPath = Path.splice(1, Number.MAX_VALUE); return getByPath(NextPath, Target[Path[0]]); } } function update(SparseObject) { // todo console.log("ERROR: stub called!"); enforceNonArrayObject(SparseObject, "Flocks2 update/1 must take a plain object"); } function lock() { ++updateBlocks; } function unlock() { if (updateBlocks <= 0) { throw "unlock()ed with no lock!"; } --updateBlocks; attemptUpdate(); } function clone(obj) { var copy = obj.constructor(), attr; if ((obj === null) || (typeof obj !== "object")) { return obj; } for (attr in obj) { if (obj.hasOwnProperty(attr)) { copy[attr] = obj[attr]; } } return copy; } function create(iFlocksConfig, iFlocksData) { var FlocksConfig = iFlocksConfig || {}, FlocksData = iFlocksData || {}, target = FlocksConfig.target || document.body, stub = function() { console.log("ERROR: stub called!"); attemptUpdate(); }, // todo updater = { "get" : stub, // todo "override" : stub, // todo "clear" : stub, // todo "get_path" : getByPath, "set" : set, "set_path" : setByPath, "update" : update, "lock" : lock, "unlock" : unlock }; FlocksConfig["log_level"] = FlocksConfig["log_level"] || -1; tagtype = FlocksConfig.control; FlocksData.flocks2Config = FlocksConfig; nextFCtx = FlocksData; flocksLog(1, "Flocks2 root creation begins"); if (!(tagtype)) { throw "Flocks2 fatal error: must provide a control in create/2 FlocksConfig"; } if (FlocksConfig.handler) { handler = FlocksConfig.handler; flocksLog(3, " - Flocks2 handler assigned"); } if (FlocksConfig.finalizer) { finalizer = FlocksConfig.finalizer; flocksLog(3, " - Flocks2 finalizer assigned"); } if (FlocksConfig.preventAutoContext) { flocksLog(2, " - Flocks2 skipping auto-context"); } else { flocksLog(2, " - Flocks2 engaging auto-context"); this.fctx = clone(nextFCtx); } flocksLog(3, "Flocks2 creation finished; initializing"); initialized = true; attemptUpdate(); flocksLog(3, "Flocks2 expose updater"); this.fupd = updater; this.fset = updater.set; this.fgetpath = updater.get_path; this.flock = updater.lock; this.funlock = updater.unlock; this.fupdate = updater.update; flocksLog(3, "Flocks2 initialization finished"); return updater; } Mixin = { "contextTypes" : flocks2Ctxs, "childContextTypes" : flocks2Ctxs, "componentWillMount" : function() { flocksLog(1, " - Flocks2 component will mount: " + this.constructor.displayName); flocksLog(3, isUndefined(this.props.flocks2context)? " - No F2 Context Prop" : " - F2 Context Prop found"); flocksLog(3, isUndefined(this.context.flocks2context)? " - No F2 Context" : " - F2 Context found"); if (this.props.flocks2context) { this.context.flocks2context = this.props.flocks2context; } this.fupdate = function(Obj) { return update(Obj); }; this.fgetpath = function(P,T) { return getByPath(P,T); }; this.fset = function(K,V) { return set(K,V); }; this.fsetpath = function(P,V) { return set(P,V); }; this.flock = function() { return lock(); }; this.funlock = function() { return unlock(); }; this.fctx = this.context.flocks2context; }, "getChildContext" : function() { return this.context; } }; function atLeastFlocks(OriginalList) { var NewList; if (isUndefined(OriginalList)) { return [ Mixin ]; } if (isArray(OriginalList)) { if (arrayMember(Mixin, OriginalList)) { return OriginalList; } else { NewList = clone(OriginalList); NewList.push(Mixin); return NewList; } } throw "Original mixin list must be an array or undefined!"; } function createClass(spec) { spec.mixins = atLeastFlocks(spec.mixins); return React.createClass(spec); } exports = { "version" : "0.16.17", "plumbing" : Mixin, "createClass" : createClass, "mount" : create, "clone" : clone, "isArray" : isArray, "isUndefined" : isUndefined, "isNonArrayObject" : isNonArrayObject, "enforceString" : enforceString, "enforceArray" : enforceArray, "enforceNonArrayObject" : enforceNonArrayObject, "atLeastFlocks" : atLeastFlocks }; if (typeof module !== "undefined") { module.exports = exports; } else { window.flocks = exports; } }());
stubo/static/node_modules/react-tools/src/browser/server/ReactServerRenderingTransaction.js
Stub-O-Matic-BA/stubo-app
/** * Copyright 2014-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. * * @providesModule ReactServerRenderingTransaction * @typechecks */ 'use strict'; var PooledClass = require('PooledClass'); var CallbackQueue = require('CallbackQueue'); var ReactPutListenerQueue = require('ReactPutListenerQueue'); var Transaction = require('Transaction'); var assign = require('Object.assign'); var emptyFunction = require('emptyFunction'); /** * Provides a `CallbackQueue` queue for collecting `onDOMReady` callbacks * during the performing of the transaction. */ var ON_DOM_READY_QUEUEING = { /** * Initializes the internal `onDOMReady` queue. */ initialize: function() { this.reactMountReady.reset(); }, close: emptyFunction }; var PUT_LISTENER_QUEUEING = { initialize: function() { this.putListenerQueue.reset(); }, close: emptyFunction }; /** * Executed within the scope of the `Transaction` instance. Consider these as * being member methods, but with an implied ordering while being isolated from * each other. */ var TRANSACTION_WRAPPERS = [ PUT_LISTENER_QUEUEING, ON_DOM_READY_QUEUEING ]; /** * @class ReactServerRenderingTransaction * @param {boolean} renderToStaticMarkup */ function ReactServerRenderingTransaction(renderToStaticMarkup) { this.reinitializeTransaction(); this.renderToStaticMarkup = renderToStaticMarkup; this.reactMountReady = CallbackQueue.getPooled(null); this.putListenerQueue = ReactPutListenerQueue.getPooled(); } var Mixin = { /** * @see Transaction * @abstract * @final * @return {array} Empty list of operation wrap proceedures. */ getTransactionWrappers: function() { return TRANSACTION_WRAPPERS; }, /** * @return {object} The queue to collect `onDOMReady` callbacks with. */ getReactMountReady: function() { return this.reactMountReady; }, getPutListenerQueue: function() { return this.putListenerQueue; }, /** * `PooledClass` looks for this, and will invoke this before allowing this * instance to be resused. */ destructor: function() { CallbackQueue.release(this.reactMountReady); this.reactMountReady = null; ReactPutListenerQueue.release(this.putListenerQueue); this.putListenerQueue = null; } }; assign( ReactServerRenderingTransaction.prototype, Transaction.Mixin, Mixin ); PooledClass.addPoolingTo(ReactServerRenderingTransaction); module.exports = ReactServerRenderingTransaction;
src/components/Page/Panel/index.js
ascrutae/sky-walking-ui
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import React, { Component } from 'react'; export default class Panel extends Component { componentDidMount() { const { globalVariables, variables, onChange } = this.props; if (!this.isRender(this.props)) { return; } onChange({ ...globalVariables, ...variables }); } shouldComponentUpdate(nextProps) { const { globalVariables, variables, onChange } = nextProps; if (!this.isRender(nextProps)) { return false; } if (globalVariables !== this.props.globalVariables || variables !== this.props.variables) { onChange({ ...globalVariables, ...variables }); return false; } return true; } isRender = props => [props.variables, props.globalVariables] .reduce((acc, curr) => (acc && (curr === undefined || (curr !== undefined && Object.keys(curr).length > 0))), true); render() { const { children } = this.props; return children && (<div> {children} </div>); } }
newclient/scripts/components/admin/disclosure-filter-by-type/index.js
kuali/research-coi
/* The Conflict of Interest (COI) module of Kuali Research Copyright © 2005-2016 Kuali, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/> */ import styles from './style'; import classNames from 'classnames'; import React from 'react'; import {GreyButton} from '../../grey-button'; import {AdminActions} from '../../../actions/admin-actions'; import DisclosureFilter from '../disclosure-filter'; import DoneWithFilterButton from '../done-with-filter-button'; export class DisclosureFilterByType extends DisclosureFilter { constructor() { super(); this.label = 'TYPE'; this.toggleFilter = this.toggleFilter.bind(this); this.isChecked = this.isChecked.bind(this); } clear(e) { AdminActions.clearTypeFilter(); e.stopPropagation(); } toggleFilter(evt) { const index = Number(evt.target.id.replace('typeFilt', '')); AdminActions.toggleTypeFilter(this.props.possibleTypes[index]); } isChecked(value) { return this.props.activeFilters.find(filter => { return filter === value; }) !== undefined; } // render() is implemented in DisclosureFilter, which will call renderFilter renderFilter() { const options = this.props.possibleTypes.map((type, index) => { const id = `typeFilt${index}`; return ( <div className={styles.checkbox} key={type}> <input id={id} type="checkbox" checked={this.isChecked(type)} onChange={this.toggleFilter} /> <label htmlFor={id}>{type}</label> </div> ); }); return ( <div className={styles.container}> <DoneWithFilterButton onClick={this.close} /> {options} <GreyButton className={`${styles.override} ${styles.clearButton}`} onClick={this.clear}> <i className={classNames('fa', 'fa-times', styles.x)} /> CLEAR FILTER </GreyButton> </div> ); } }
src/components/views/elements/LanguageDropdown.js
aperezdc/matrix-react-sdk
/* Copyright 2017 Marcel Radzio (MTRNord) Copyright 2017 Vector Creations Ltd. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import React from 'react'; import PropTypes from 'prop-types'; import sdk from '../../../index'; import * as languageHandler from '../../../languageHandler'; import SettingsStore from "../../../settings/SettingsStore"; function languageMatchesSearchQuery(query, language) { if (language.label.toUpperCase().indexOf(query.toUpperCase()) == 0) return true; if (language.value.toUpperCase() == query.toUpperCase()) return true; return false; } export default class LanguageDropdown extends React.Component { constructor(props) { super(props); this._onSearchChange = this._onSearchChange.bind(this); this.state = { searchQuery: '', langs: null, }; } componentWillMount() { languageHandler.getAllLanguagesFromJson().then((langs) => { langs.sort(function(a, b) { if (a.label < b.label) return -1; if (a.label > b.label) return 1; return 0; }); this.setState({langs}); }).catch(() => { this.setState({langs: ['en']}); }).done(); if (!this.props.value) { // If no value is given, we start with the first // country selected, but our parent component // doesn't know this, therefore we do this. const language = SettingsStore.getValue("language", null, /*excludeDefault:*/true); if (language) { this.props.onOptionChange(language); } else { const language = languageHandler.normalizeLanguageKey(languageHandler.getLanguageFromBrowser()); this.props.onOptionChange(language); } } } _onSearchChange(search) { this.setState({ searchQuery: search, }); } render() { if (this.state.langs === null) { const Spinner = sdk.getComponent('elements.Spinner'); return <Spinner />; } const Dropdown = sdk.getComponent('elements.Dropdown'); let displayedLanguages; if (this.state.searchQuery) { displayedLanguages = this.state.langs.filter((lang) => { return languageMatchesSearchQuery(this.state.searchQuery, lang); }); } else { displayedLanguages = this.state.langs; } const options = displayedLanguages.map((language) => { return <div key={language.value}> { language.label } </div>; }); // default value here too, otherwise we need to handle null / undefined // values between mounting and the initial value propgating let language = SettingsStore.getValue("language", null, /*excludeDefault:*/true); let value = null; if (language) { value = this.props.value || language; } else { language = navigator.language || navigator.userLanguage; value = this.props.value || language; } return <Dropdown className={this.props.className} onOptionChange={this.props.onOptionChange} onSearchChange={this._onSearchChange} searchEnabled={true} value={value} > { options } </Dropdown>; } } LanguageDropdown.propTypes = { className: PropTypes.string, onOptionChange: PropTypes.func.isRequired, value: PropTypes.string, };
src/index.js
Aikk/gallery-by-react
import 'core-js/fn/object/assign'; import React from 'react'; import ReactDOM from 'react-dom'; import App from './components/Main'; // Render the main component into the dom ReactDOM.render(<App />, document.getElementById('app'));
test/helpers/shallowRenderHelper.js
Wobugaosuni/galleryByReact
/** * Function to get the shallow output for a given component * As we are using phantom.js, we also need to include the fn.proto.bind shim! * * @see http://simonsmith.io/unit-testing-react-components-without-a-dom/ * @author somonsmith */ import React from 'react'; import TestUtils from 'react-addons-test-utils'; /** * Get the shallow rendered component * * @param {Object} component The component to return the output for * @param {Object} props [optional] The components properties * @param {Mixed} ...children [optional] List of children * @return {Object} Shallow rendered output */ export default function createComponent(component, props = {}, ...children) { const shallowRenderer = TestUtils.createRenderer(); shallowRenderer.render(React.createElement(component, props, children.length > 1 ? children : children[0])); return shallowRenderer.getRenderOutput(); }
react-flux-mui/js/material-ui/src/svg-icons/device/battery-unknown.js
pbogdan/react-flux-mui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceBatteryUnknown = (props) => ( <SvgIcon {...props}> <path d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33v15.33C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V5.33C17 4.6 16.4 4 15.67 4zm-2.72 13.95h-1.9v-1.9h1.9v1.9zm1.35-5.26s-.38.42-.67.71c-.48.48-.83 1.15-.83 1.6h-1.6c0-.83.46-1.52.93-2l.93-.94c.27-.27.44-.65.44-1.06 0-.83-.67-1.5-1.5-1.5s-1.5.67-1.5 1.5H9c0-1.66 1.34-3 3-3s3 1.34 3 3c0 .66-.27 1.26-.7 1.69z"/> </SvgIcon> ); DeviceBatteryUnknown = pure(DeviceBatteryUnknown); DeviceBatteryUnknown.displayName = 'DeviceBatteryUnknown'; DeviceBatteryUnknown.muiName = 'SvgIcon'; export default DeviceBatteryUnknown;
src/components/TopNav.js
Hylozoic/hylo-redux
import React from 'react' import A, { IndexA } from './A' import Icon from './Icon' import Dropdown from './Dropdown' import { filter } from 'lodash/fp' import { throttle, times } from 'lodash' import { leftNavWidth, leftNavEasing, menuButtonWidth } from './LeftNav' import NavMenuButton from './NavMenuButton' import { editorUrl } from '../containers/StandalonePostEditor' const { array, object, func, string, bool, number } = React.PropTypes import { viewportTop } from '../util/scrolling' import { makeUrl } from '../util/navigation' import { VelocityComponent } from 'velocity-react' import cx from 'classnames' import CommunityMenu, { allCommunities } from './CommunityMenu' import UserMenu from './UserMenu' import { isCommunityUrl } from '../routes' const getPostType = path => { if (path.endsWith('events')) return 'event' if (path.endsWith('projects')) return 'project' } const getLabel = path => { if (path.endsWith('events')) return 'Events' if (path.endsWith('projects')) return 'Projects' if (path.endsWith('people')) return 'Members' if (path.endsWith('about')) return 'About' if (path.endsWith('invite')) return 'Invite' if (path === '/app' || path.match(/^\/c\/[^/]+$/)) return 'Conversations' return 'Menu' } export default class TopNav extends React.Component { static propTypes = { refresh: func, path: string, openLeftNav: func, opened: bool, community: object, network: object, leftNavIsOpen: bool, links: array, currentUser: object, tagNotificationCount: number } static contextTypes = { isMobile: bool } constructor (props) { super(props) this.state = {isScrolling: false} } handleScrollEvents = throttle(event => { event.preventDefault() if (this.state.isScrolling) { if (viewportTop() === 0) { this.setState({isScrolling: false}) } } else { if (viewportTop() > 0) { this.setState({isScrolling: true}) } } }, 50) componentDidMount () { if (!this.context.isMobile) { this.setState({isScrolling: viewportTop() > 0}) window.addEventListener('scroll', this.handleScrollEvents) } if (!this.props.currentUser) { this.setState({returnPath: window.location.pathname}) } } componentWillUnmount () { if (!this.context.isMobile) { window.removeEventListener('scroll', this.handleScrollEvents) } } render () { const { currentUser, openLeftNav, leftNavIsOpen, path, network, links, tagNotificationCount } = this.props const { isMobile } = this.context const { returnPath } = this.state const label = getLabel(path) const community = this.props.community || allCommunities() const { slug } = community const moveWithMenu = isMobile ? {marginLeft: leftNavIsOpen ? leftNavWidth : 0} : {marginLeft: 0} const widenMenuButton = {width: leftNavIsOpen ? leftNavWidth : menuButtonWidth} return <VelocityComponent animation={moveWithMenu} easing={leftNavEasing}> <nav id='topNav' className={cx('clearfix', {scrolling: this.state.isScrolling})}> {currentUser && (isMobile ? <NavMenuButton onClick={openLeftNav} label={label} notificationCount={tagNotificationCount} /> : <VelocityComponent animation={widenMenuButton} easing={leftNavEasing}> <NavMenuButton onClick={openLeftNav} notificationCount={tagNotificationCount} /> </VelocityComponent>)} {currentUser ? <UserMenu slug={slug} /> : <ul className='right'> {!isCommunityUrl(path) && <li><A to={makeUrl('/signup', {next: returnPath})}>Sign up</A></li>} <li><A to={makeUrl('/login', {next: returnPath})}>Log in</A></li> </ul>} <CommunityMenu {...{community, network}} /> {currentUser && !network && <TopMainMenu {...{links, leftNavIsOpen}} />} {currentUser && <A to={editorUrl(slug, getPostType(path))} className='compose'> <Icon name='Compose' /> </A>} </nav> </VelocityComponent> } } class TopMainMenu extends React.Component { static propTypes = {links: array, leftNavIsOpen: bool} constructor (props) { super(props) this.state = {hiddenCount: 0} } adjustMenu = (depth = 0) => { const rightSide = document.querySelector('#topNav > .right') const mainMenu = document.querySelector('#topNav > .main-menu') const mainMenuEnd = mainMenu.offsetLeft + mainMenu.offsetWidth const space = rightSide.offsetLeft - mainMenuEnd const { hiddenCount } = this.state if (space < 30) { this.setState({hiddenCount: hiddenCount + 1}) if (depth < 6) this.adjustMenu(depth + 1) } else if (space > 100 && hiddenCount > 0) { this.setState({hiddenCount: Math.max(0, hiddenCount - 1)}) if (depth < 7) this.adjustMenu(depth + 1) } } componentDidUpdate (prevProps) { const { leftNavIsOpen, links } = this.props if (links !== prevProps.links) { setTimeout(this.adjustMenu) } if (leftNavIsOpen !== prevProps.leftNavIsOpen) { times(4, n => setTimeout(this.adjustMenu, 150 + 150 * n)) } } componentDidMount () { this.throttledAdjustMenu = throttle(this.adjustMenu, 100) window.addEventListener('resize', this.throttledAdjustMenu) this.adjustMenu() } componentWillUnmount () { window.removeEventListener('resize', this.throttledAdjustMenu) } render () { const { links } = this.props const { hiddenCount } = this.state const LinkItem = ({ link, className }) => { const { url, label, index } = link const AComponent = index ? IndexA : A return <AComponent to={url} className={className}>{label}</AComponent> } const topLinks = filter(l => l.label !== 'Network', links) return <div className='main-menu'> {topLinks.slice(1, topLinks.length - hiddenCount).map((link, i) => <LinkItem link={link} key={link.label} />)} {hiddenCount > 0 && <Dropdown triangle className='overflow-menu' toggleChildren={<Icon name='More' />}> {topLinks.slice(-hiddenCount).map((link, i) => <li key={link.label} className={`li-${i}`}> <LinkItem link={link} /> </li>)} </Dropdown>} </div> } }
ajax/libs/clappr/0.0.63/clappr.js
iskitz/cdnjs
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":7,"./components/iframe_player":19,"./components/player":23,"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){ // 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 = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#x27;', '`': '&#x60;' }; 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)); },{}],7:[function(require,module,exports){ module.exports={ "name": "clappr", "version": "0.0.63", "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" }, "browserify-shim": "./shim.js", "browserify": { "transform": [ "browserify-shim" ] }, "homepage": "https://github.com/globocom/clappr", "devDependencies": { "browserify": "^6.3.2", "browserify-shim": "^3.8.0", "chai": "latest", "compass-mixins": "latest", "dotenv": "^0.4.0", "es6ify": "~1.4.0", "exorcist": "^0.1.6", "express": "^4.6.1", "express-alias": "latest", "glob": "^4.0.2", "gulp": "^3.8.1", "gulp-compressor": "^0.1.0", "gulp-jshint": "latest", "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": "latest", "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": "latest", "sinon": "^1.10.2", "traceur": "0.0.72", "vinyl-source-stream": "^1.0.0", "vinyl-transform": "0.0.1", "watchify": "^2.0.0", "yargs": "latest" }, "dependencies": { "underscore": "1.7.0", "jquery": "~2.1.0", "mousetrap": "0.0.1", "scrollmonitor": "^1.0.8" } } },{}],8:[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; }; }); module.exports = Events; },{"../plugins/log":40,"underscore":6}],9:[function(require,module,exports){ "use strict"; var _ = require('underscore'); module.exports = { 'iframe_player': _.template('<html><head><meta http-equiv="content-type" content="text/html; charset=utf-8"/><script type="text/javascript" charset="utf-8" src="http://cdn.clappr.io/j/vendor/jquery.min.js"></script><script type="text/javascript" charset="utf-8" src="http://cdn.clappr.io/j/vendor/underscore-min.js"></script><script type="text/javascript" charset="utf-8" src="http://flavio.globoi.com/clappr.js"></script><script type="text/javascript" charset="utf-8"></script><style>body {margin:0}</style></head><body><div id="player-wrapper" style="border: 0px;border-radius: 0px;width: 100%;height: 100%"></div></body></html>'), '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}', '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":6}],10:[function(require,module,exports){ "use strict"; var $ = require('jquery'); 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)); }}; module.exports = Styler; },{"./jst":9,"jquery":"jquery","underscore":6}],11:[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":6}],12:[function(require,module,exports){ "use strict"; var UIObject = require('ui_object'); var Styler = require('../../base/styler'); var _ = require('underscore'); 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, 'playback:progress', this.progress); this.listenTo(this.playback, 'playback:timeupdate', this.timeUpdated); this.listenTo(this.playback, 'playback:ready', this.ready); this.listenTo(this.playback, 'playback:buffering', this.buffering); this.listenTo(this.playback, 'playback:bufferfull', this.bufferfull); this.listenTo(this.playback, 'playback:settingsupdate', this.settingsUpdate); this.listenTo(this.playback, 'playback:loadedmetadata', this.loadedMetadata); this.listenTo(this.playback, 'playback:highdefinitionupdate', this.highDefinitionUpdate); this.listenTo(this.playback, 'playback:bitrate', this.updateBitrate); this.listenTo(this.playback, 'playback:playbackstate', this.playbackStateChanged); this.listenTo(this.playback, 'playback:dvr', this.playbackDvrStateChanged); this.listenTo(this.playback, 'playback:mediacontrol:disable', this.disableMediaControl); this.listenTo(this.playback, 'playback:mediacontrol:enable', this.enableMediaControl); this.listenTo(this.playback, 'playback:ended', this.ended); this.listenTo(this.playback, 'playback:play', this.playing); this.listenTo(this.playback, 'playback:error', this.error); }, with: function(klass) { _.extend(this, klass); return this; }, playbackStateChanged: function() { this.trigger('container:playbackstate'); }, playbackDvrStateChanged: function(dvrInUse) { this.settings = this.playback.settings; this.dvrInUse = dvrInUse; this.trigger('container:dvr', dvrInUse); }, updateBitrate: function(newBitrate) { this.trigger('container:bitrate', newBitrate); }, statsReport: function(metrics) { this.trigger('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('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('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('container:error', { error: errorObj, container: this }, this.name); }, loadedMetadata: function(duration) { this.trigger('container:loadedmetadata', duration); }, timeUpdated: function(position, duration) { this.trigger('container:timeupdate', position, duration, this.name); }, progress: function(startPosition, endPosition, duration) { this.trigger('container:progress', startPosition, endPosition, duration, this.name); }, playing: function() { this.trigger('container:play', this.name); }, play: function() { this.playback.play(); }, stop: function() { this.trigger('container:stop', this.name); this.playback.stop(); }, pause: function() { this.trigger('container:pause', this.name); this.playback.pause(); }, ended: function() { this.trigger('container:ended', this, this.name); }, clicked: function() { this.trigger('container:click', this, this.name); }, setCurrentTime: function(time) { this.trigger('container:seek', time, this.name); this.playback.seek(time); }, setVolume: function(value) { this.trigger('container:volume', value, this.name); this.playback.volume(value); }, fullscreen: function() { this.trigger('container:fullscreen', this.name); }, buffering: function() { this.trigger('container:state:buffering', this.name); }, bufferfull: function() { this.trigger('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('container:settingsupdate'); }, highDefinitionUpdate: function() { this.trigger('container:highdefinitionupdate'); }, isHighDefinitionInUse: function() { return this.playback.isHighDefinitionInUse(); }, disableMediaControl: function() { this.mediaControlDisabled = true; this.trigger('container:mediacontrol:disable'); }, enableMediaControl: function() { this.mediaControlDisabled = false; this.trigger('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":10,"ui_object":"ui_object","underscore":6}],13:[function(require,module,exports){ "use strict"; var _ = require('underscore'); var BaseObject = require('base_object'); var Container = require('container'); var $ = require('jquery'); 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, '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","jquery":"jquery","underscore":6}],14:[function(require,module,exports){ "use strict"; module.exports = require('./container_factory'); },{"./container_factory":13}],15:[function(require,module,exports){ "use strict"; var _ = require('underscore'); var $ = require('jquery'); 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 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.addEventListener('fullscreenchange', (function() { return $__0.exit(); })); document.addEventListener('MSFullscreenChange', (function() { return $__0.exit(); })); document.addEventListener('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('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('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(); }, 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, 'container:destroyed', this.removeContainer); this.el.appendChild(container.render().el); this.containers.push(container); }, prependContainer: function(container) { this.listenTo(container, 'container:destroyed', this.removeContainer); this.$el.append(container.render().el); this.containers.unshift(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, 'mediacontrol:fullscreen', this.toggleFullscreen); this.listenTo(this.mediaControl, 'mediacontrol:show', this.onMediaControlShow.bind(this, true)); this.listenTo(this.mediaControl, '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":10,"../../base/utils":11,"../container_factory":14,"jquery":"jquery","media_control":"media_control","mediator":"mediator","player_info":"player_info","ui_object":"ui_object","underscore":6}],16:[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":6}],17:[function(require,module,exports){ "use strict"; module.exports = require('./core_factory'); },{"./core_factory":16}],18:[function(require,module,exports){ "use strict"; var BaseObject = require('base_object'); var $ = require('jquery'); 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":23,"base_object":"base_object","jquery":"jquery"}],19:[function(require,module,exports){ "use strict"; module.exports = require('./iframe_player'); },{"./iframe_player":18}],20:[function(require,module,exports){ "use strict"; module.exports = require('./loader'); },{"./loader":21}],21:[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 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('../../plugins/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, 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":30,"../../plugins/background_button":33,"../../plugins/click_to_pause":35,"../../plugins/dvr_controls":37,"../../plugins/google_analytics":39,"../../plugins/poster":42,"../../plugins/spinner_three_bounce":44,"../../plugins/stats":46,"../../plugins/watermark":48,"base_object":"base_object","flash":"flash","hls":"hls","html5_audio":"html5_audio","html5_video":"html5_video","player_info":"player_info","underscore":6}],22:[function(require,module,exports){ "use strict"; var _ = require('underscore'); var $ = require('jquery'); 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 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('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, 'container:play', this.changeTogglePlay); this.listenTo(this.container, 'container:timeupdate', this.updateSeekBar); this.listenTo(this.container, 'container:progress', this.updateProgressBar); this.listenTo(this.container, 'container:settingsupdate', this.settingsUpdate); this.listenTo(this.container, 'container:dvr', this.settingsUpdate); this.listenTo(this.container, 'container:highdefinitionupdate', this.highDefinitionUpdate); this.listenTo(this.container, 'container:mediacontrol:disable', this.disable); this.listenTo(this.container, 'container:mediacontrol:enable', this.enable); this.listenTo(this.container, '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('mediacontrol:playing'); } else { this.$playPauseToggle.removeClass('playing').addClass('paused'); this.$playStopToggle.removeClass('playing').addClass('stopped'); this.trigger('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('mediacontrol:mousemove:seekbar', event); }, mouseleaveOnSeekBar: function(event) { this.trigger('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('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('container:dvr', this.container.isDvrInUse()); this.container.setVolume(this.currentVolume); if (this.container.mediaControlDisabled) { this.disable(); } this.trigger("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.isVisible() || this.container.getPlaybackType() === null) return; var timeout = 2000; if (!event || (event.clientX !== this.lastMouseX && event.clientY !== this.lastMouseY) || navigator.userAgent.match(/firefox/i)) { if (this.hideId) { clearTimeout(this.hideId); } this.$el.show(); this.trigger('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; if (this.hideId) { clearTimeout(this.hideId); } if (!this.isVisible()) return; if (this.keepVisible || this.draggingSeekBar || this.draggingVolumeBar) { this.hideId = setTimeout((function() { return $__0.hide(); }), timeout); } else { this.trigger('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, "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(); })); }, 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('mediacontrol:rendered'); return this; } }, {}, UIObject); module.exports = MediaControl; },{"../../base/jst":9,"../../base/styler":10,"../../base/utils":11,"../seek_time":24,"jquery":"jquery","mediator":"mediator","mousetrap":4,"player_info":"player_info","ui_object":"ui_object","underscore":6}],23:[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 }; }; 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":17,"./loader":20,"base_object":"base_object","player_info":"player_info","scrollmonitor":5,"underscore":6}],24:[function(require,module,exports){ "use strict"; module.exports = require('./seek_time'); },{"./seek_time":25}],25:[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 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, 'mediacontrol:mousemove:seekbar', this.showTime); this.listenTo(this.mediaControl, '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":9,"../../base/styler":10,"../../base/utils":11,"ui_object":"ui_object"}],26:[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('jquery'); var Browser = require('browser'); var Mousetrap = require('mousetrap'); var seekStringToSeconds = require('../../base/utils').seekStringToSeconds; 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.swfPath = options.swfPath || "http://cdn.clappr.io/latest/assets/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('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('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('playback:buffering', this.name); this.currentState = "PLAYING_BUFFERING"; } else if (this.currentState === "PLAYING_BUFFERING" && this.el.getState() === "PLAYING") { this.trigger('playback:bufferfull', this.name); this.currentState = "PLAYING"; } else if (this.el.getState() === "IDLE") { this.currentState = "IDLE"; } else if (this.el.getState() === "ENDED") { this.trigger('playback:ended', this.name); this.trigger('playback:timeupdate', 0, this.el.getDuration(), this.name); this.currentState = "ENDED"; } }, progress: function() { if (this.currentState !== "IDLE" && this.currentState !== "ENDED") { this.trigger('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, '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('playback:play', this.name); }, volume: function(value) { var $__0 = this; if (this.isReady) { this.el.playerVolume(value); } else { this.listenToOnce(this, 'playback:bufferfull', (function() { return $__0.volume(value); })); } }, pause: function() { this.currentState = "PAUSED"; this.el.playerPause(); }, stop: function() { this.el.playerStop(); this.trigger('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('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":9,"../../base/styler":10,"../../base/utils":11,"browser":"browser","jquery":"jquery","mediator":"mediator","mousetrap":4,"playback":"playback","underscore":6}],27:[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 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.swfPath = options.swfPath || "http://cdn.clappr.io/latest/assets/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('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('playback:highdefinitionupdate'); this.trigger('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('playback:settingsupdate', this.name); } if (livePlayback && (!this.dvrEnabled || !this.dvrInUse)) { position = duration; } this.trigger('playback:timeupdate', position, duration, this.name); }, play: function() { if (this.currentState === 'PAUSED') { this.el.globoPlayerResume(); } else if (this.currentState !== "PLAYING") { this.firstPlay(); } this.trigger('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('playback:buffering', this.name); this.updateCurrentState(state); } else if (state === "PLAYING") { if (_.contains(["PLAYING_BUFFERING", "PAUSED", "IDLE"], this.currentState)) { this.trigger('playback:bufferfull', this.name); this.updateCurrentState(state); } } else if (state === "PAUSED") { this.updateCurrentState(state); } else if (state === "IDLE") { this.trigger('playback:ended', this.name); this.trigger('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('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('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, '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('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('playback:timeupdate', time, duration, this.name); }, updateDvr: function(dvrInUse) { var previousDvrInUse = !!this.dvrInUse; this.dvrInUse = dvrInUse; if (this.dvrInUse !== previousDvrInUse) { this.updateSettings(); this.trigger('playback:dvr', this.dvrInUse); this.trigger('playback:stats:add', {'dvr': this.dvrInUse}); } }, flashPlaybackError: function() { this.trigger('playback:stop'); }, timeUpdate: function(time, duration) { this.trigger('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":9,"../../base/styler":10,"browser":"browser","mediator":"mediator","playback":"playback","underscore":6}],28:[function(require,module,exports){ "use strict"; var Playback = require('playback'); 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, 'container:play', this.play); this.listenTo(this.container, 'container:pause', this.pause); this.listenTo(this.container, 'container:seek', this.seek); this.listenTo(this.container, 'container:volume', this.volume); this.listenTo(this.container, 'container:stop', this.stop); }, getPlaybackType: function() { return "aod"; }, play: function() { this.el.play(); this.trigger('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('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('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; },{"playback":"playback"}],29:[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 _ = 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.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.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('playback:loadedmetadata', e.target.duration); this.trigger('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('playback:play'); if (this.isHLS) { this.trigger('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('playback:ended', this.name); this.trigger('playback:timeupdate', 0, this.el.duration, this.name); }, stalled: function() { if (this.getPlaybackType() === 'vod' && this.el.readyState < this.el.HAVE_FUTURE_DATA) { this.trigger('playback:buffering', this.name); } }, waiting: function() { if (this.el.readyState < this.el.HAVE_FUTURE_DATA) { this.trigger('playback:buffering', this.name); } }, bufferFull: function() { if (this.getPlaybackType() === 'vod' && this.options.poster && this.firstBuffer) { this.firstBuffer = false; this.el.poster = this.options.poster; } else { this.el.poster = ''; } this.trigger('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('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('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('playback:ready', this.name); process.nextTick((function() { return $__0.options.autoPlay && $__0.play(); })); return this; } }, {}, Playback); HTML5Video.canPlay = function(resource) { if (Browser.isChrome || Browser.isFirefox || Browser.isIE) { return (!!resource.match(/(.*).(mp4|webm)/)); } else if (Browser.isSafari || Browser.isMobile || Browser.isWin8App || Browser.isLegacyIE) { return (!!resource.match(/(.*).mp4/)); } }; module.exports = HTML5Video; }).call(this,require('_process')) },{"../../base/jst":9,"../../base/styler":10,"../../base/utils":11,"_process":2,"browser":"browser","mousetrap":4,"playback":"playback","underscore":6}],30:[function(require,module,exports){ "use strict"; module.exports = require('./no_op'); },{"./no_op":31}],31:[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":9,"../../base/styler":10,"playback":"playback"}],32:[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 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, 'container:state:buffering', this.hide); this.listenTo(this.core.mediaControl.container, 'container:state:bufferfull', this.show); this.listenTo(this.core.mediaControl, 'mediacontrol:rendered', this.settingsUpdate); this.listenTo(this.core.mediaControl, 'mediacontrol:show', this.updateSize); this.listenTo(this.core.mediaControl, 'mediacontrol:playing', this.playing); this.listenTo(this.core.mediaControl, 'mediacontrol:notplaying', this.notplaying); Mediator.on('player:resize', this.updateSize, this); }, stopListening: function() { $traceurRuntime.superCall(this, $BackgroundButton.prototype, "stopListening", []); Mediator.off('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, 'container:settingsupdate', this.settingsUpdate); this.listenTo(this.core.mediaControl.container, 'container:dvr', this.settingsUpdate); this.listenTo(this.core.mediaControl, '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":9,"../../base/styler":10,"_process":2,"browser":"browser","mediator":"mediator","player_info":"player_info","ui_core_plugin":"ui_core_plugin"}],33:[function(require,module,exports){ "use strict"; module.exports = require('./background_button'); },{"./background_button":32}],34:[function(require,module,exports){ "use strict"; var ContainerPlugin = require('container_plugin'); 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, 'container:click', this.click); this.listenTo(this.container, '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"}],35:[function(require,module,exports){ "use strict"; module.exports = require('./click_to_pause'); },{"./click_to_pause":34}],36:[function(require,module,exports){ "use strict"; var UICorePlugin = require('ui_core_plugin'); var JST = require('../../base/jst'); var Styler = require('../../base/styler'); 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, 'mediacontrol:rendered', this.settingsUpdate); this.listenTo(this.core.mediaControl.container, 'container:dvr', 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":9,"../../base/styler":10,"ui_core_plugin":"ui_core_plugin"}],37:[function(require,module,exports){ "use strict"; module.exports = require('./dvr_controls'); },{"./dvr_controls":36}],38:[function(require,module,exports){ "use strict"; var ContainerPlugin = require('container_plugin'); 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, 'container:play', this.onPlay); this.listenTo(this.container, 'container:pause', this.onPause); this.listenTo(this.container, 'container:stop', this.onStop); this.listenTo(this.container, 'container:ended', this.onEnded); this.listenTo(this.container, 'container:state:buffering', this.onBuffering); this.listenTo(this.container, 'container:state:bufferfull', this.onBufferFull); this.listenTo(this.container, 'container:error', this.onError); this.listenTo(this.container, 'container:playbackstate', this.onPlaybackChanged); this.listenTo(this.container, 'container:volume', (function(event) { return $__0.onVolumeChanged(event); })); this.listenTo(this.container, 'container:seek', (function(event) { return $__0.onSeek(event); })); this.listenTo(this.container, 'container:fullscreen', this.onFullscreen); this.listenTo(this.container, 'container:highdefinitionupdate', this.onHD); this.listenTo(this.container.playback, '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"}],39:[function(require,module,exports){ "use strict"; module.exports = require('./google_analytics'); },{"./google_analytics":38}],40:[function(require,module,exports){ "use strict"; module.exports = require('./log'); },{"./log":41}],41:[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":6}],42:[function(require,module,exports){ "use strict"; module.exports = require('./poster'); },{"./poster":43}],43:[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 Mediator = require('mediator'); var PlayerInfo = require('player_info'); var $ = require('jquery'); 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, 'container:state:buffering', this.onBuffering); this.listenTo(this.container, 'container:state:bufferfull', this.onBufferfull); this.listenTo(this.container, 'container:stop', this.onStop); this.listenTo(this.container, 'container:ended', this.onStop); Mediator.on('player:resize', this.updateSize, this); }, stopListening: function() { $traceurRuntime.superCall(this, $PosterPlugin.prototype, "stopListening", []); Mediator.off('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":9,"../../base/styler":10,"_process":2,"jquery":"jquery","mediator":"mediator","player_info":"player_info","ui_container_plugin":"ui_container_plugin","underscore":6}],44:[function(require,module,exports){ "use strict"; module.exports = require('./spinner_three_bounce'); },{"./spinner_three_bounce":45}],45:[function(require,module,exports){ "use strict"; var UIContainerPlugin = require('ui_container_plugin'); var Styler = require('../../base/styler'); var JST = require('../../base/jst'); var SpinnerThreeBouncePlugin = function SpinnerThreeBouncePlugin(options) { $traceurRuntime.superCall(this, $SpinnerThreeBouncePlugin.prototype, "constructor", [options]); this.template = JST.spinner_three_bounce; this.listenTo(this.container, 'container:state:buffering', this.onBuffering); this.listenTo(this.container, 'container:state:bufferfull', this.onBufferFull); this.listenTo(this.container, '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":9,"../../base/styler":10,"ui_container_plugin":"ui_container_plugin"}],46:[function(require,module,exports){ "use strict"; module.exports = require('./stats'); },{"./stats":47}],47:[function(require,module,exports){ "use strict"; var ContainerPlugin = require('container_plugin'); var $ = require("jquery"); 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, 'playback:play', this.onPlay); this.listenTo(this.container, 'container:stop', this.onStop); this.listenTo(this.container, 'container:destroyed', this.onStop); this.listenTo(this.container, 'container:state:buffering', this.onBuffering); this.listenTo(this.container, 'container:state:bufferfull', this.onBufferFull); this.listenTo(this.container, 'container:stats:add', this.onStatsAdd); this.listenTo(this.container, 'container:bitrate', this.onStatsAdd); this.listenTo(this.container.playback, '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","jquery":"jquery"}],48:[function(require,module,exports){ "use strict"; module.exports = require('./watermark'); },{"./watermark":49}],49:[function(require,module,exports){ "use strict"; var UIContainerPlugin = require('ui_container_plugin'); var Styler = require('../../base/styler'); var JST = require('../../base/jst'); 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, 'container:play', this.onPlay); this.listenTo(this.container, '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":9,"../../base/styler":10,"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; },{"./events":8,"./utils":11,"underscore":6}],"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.isMobile = !!(/Android|webOS|iPhone|iPad|iPod|BlackBerry|Windows Phone|IEMobile|Opera Mini/i.test(navigator.userAgent)); Browser.isWin8App = !!(/MSAppHost/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":12}],"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":15}],"flash":[function(require,module,exports){ "use strict"; module.exports = require('./flash'); },{"./flash":26}],"hls":[function(require,module,exports){ "use strict"; module.exports = require('./hls'); },{"./hls":27}],"html5_audio":[function(require,module,exports){ "use strict"; module.exports = require('./html5_audio'); },{"./html5_audio":28}],"html5_video":[function(require,module,exports){ "use strict"; module.exports = require('./html5_video'); },{"./html5_video":29}],"jquery":[function(require,module,exports){ /*! * jQuery JavaScript Library v2.1.1 * 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: 2014-05-01T17:11Z */ (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 arr = []; var slice = arr.slice; var concat = arr.concat; var push = arr.push; var indexOf = arr.indexOf; var class2type = {}; var toString = class2type.toString; var hasOwn = class2type.hasOwnProperty; var support = {}; var // Use the correct document accordingly with window argument (sandbox) document = window.document, version = "2.1.1", // 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 // 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: arr.sort, splice: arr.splice }; 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; // 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, isWindow: function( obj ) { 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 return !jQuery.isArray( obj ) && obj - parseFloat( obj ) >= 0; }, isPlainObject: function( obj ) { // Not plain objects: // - Any object or value whose internal [[Class]] property is not "[object Object]" // - DOM nodes // - window if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } if ( obj.constructor && !hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) { return false; } // If the function hasn't returned already, we're confident that // |obj| is a plain object, created by {} or constructed with new Object return true; }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, type: function( obj ) { if ( obj == null ) { return obj + ""; } // Support: Android < 4.0, iOS < 6 (functionish RegExp) return typeof obj === "object" || typeof obj === "function" ? class2type[ toString.call(obj) ] || "object" : typeof obj; }, // Evaluates a script in a global context globalEval: function( code ) { var script, indirect = eval; code = jQuery.trim( code ); if ( code ) { // If the code includes a valid, prologue position // strict mode pragma, execute code by injecting a // script tag into the document. if ( code.indexOf("use strict") === 1 ) { script = document.createElement("script"); script.text = code; document.head.appendChild( script ).parentNode.removeChild( script ); } else { // Otherwise, avoid the DOM node creation, insertion // and removal by using an indirect global eval indirect( code ); } } }, // 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 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 ) { return arr == null ? -1 : indexOf.call( arr, elem, i ); }, merge: function( first, second ) { var len = +second.length, j = 0, i = first.length; for ( ; j < len; j++ ) { 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 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 = 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: Date.now, // 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 ) { var length = 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 v1.10.19 * http://sizzlejs.com/ * * Copyright 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2014-04-18 */ (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" + -(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 strundefined = typeof undefined, 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 if we can't use a native one indexOf = arr.indexOf || function( elem ) { var i = 0, len = this.length; for ( ; i < len; i++ ) { if ( this[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 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 ); }; // 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 || []; if ( !selector || typeof selector !== "string" ) { return results; } if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { return []; } if ( documentIsHTML && !seed ) { // Shortcuts if ( (match = rquickExpr.exec( selector )) ) { // Speed-up: Sizzle("#ID") if ( (m = match[1]) ) { if ( nodeType === 9 ) { elem = context.getElementById( m ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document (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 && context.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // QSA path if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { nid = old = expando; newContext = context; newSelector = nodeType === 9 && selector; // 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 !== strundefined && 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, doc = node ? node.ownerDocument || node : preferredDoc, parent = doc.defaultView; // 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; // Support tests documentIsHTML = !isXML( doc ); // Support: IE>8 // If iframe document is assigned to "document" variable and if iframe has been reloaded, // IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936 // IE6-8 do not support the defaultView property so parent will be undefined if ( parent && parent !== parent.top ) { // IE11 does not have attachEvent, so all must suffer if ( parent.addEventListener ) { parent.addEventListener( "unload", function() { setDocument(); }, false ); } else if ( parent.attachEvent ) { parent.attachEvent( "onunload", function() { setDocument(); }); } } /* 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; }); // Check if getElementsByClassName can be trusted support.getElementsByClassName = rnative.test( doc.getElementsByClassName ) && assert(function( div ) { div.innerHTML = "<div class='a'></div><div class='a i'></div>"; // Support: Safari<4 // Catch class over-caching div.firstChild.className = "i"; // Support: Opera<10 // Catch gEBCN failure to find non-leading classes return div.getElementsByClassName("i").length === 2; }); // Support: IE<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 !== strundefined && 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 !== strundefined && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; } // Tag Expr.find["TAG"] = support.getElementsByTagName ? function( tag, context ) { if ( typeof context.getElementsByTagName !== strundefined ) { return context.getElementsByTagName( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, 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 ( typeof context.getElementsByClassName !== strundefined && 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 div.innerHTML = "<select msallowclip=''><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("[msallowclip^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); } // Support: IE8 // Boolean attributes and "value" are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } // 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"); } }); 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.call( sortInput, a ) - indexOf.call( 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.call( sortInput, a ) - indexOf.call( 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 !== strundefined && 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 + " " ).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.call( 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 ); return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { 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.call( 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.call( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); } ]; 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 // 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 ( indexOf.call( qualifier, elem ) >= 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, len = this.length, ret = [], self = this; 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, // 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[0] === "<" && selector[ 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 ) { // 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 = [], truncate = until !== undefined; while ( (elem = elem[ dir ]) && elem.nodeType !== 9 ) { if ( elem.nodeType === 1 ) { if ( truncate && jQuery( elem ).is( until ) ) { break; } matched.push( elem ); } } return matched; }, sibling: function( n, elem ) { var matched = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { matched.push( n ); } } return matched; } }); jQuery.fn.extend({ has: function( target ) { var targets = jQuery( target, this ), l = targets.length; return this.filter(function() { var i = 0; for ( ; i < l; 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 indexOf.call( jQuery( elem ), this[ 0 ] ); } // Locate the position of the desired element return indexOf.call( this, // If it receives a jQuery object, the first element is used elem.jquery ? elem[ 0 ] : elem ); }, 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 ) { while ( (cur = cur[dir]) && 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 elem.contentDocument || jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var matched = jQuery.map( this, fn, until ); if ( name.slice( -5 ) !== "Until" ) { selector = until; } if ( selector && typeof selector === "string" ) { matched = jQuery.filter( selector, matched ); } if ( this.length > 1 ) { // Remove duplicates if ( !guaranteedUnique[ name ] ) { jQuery.unique( matched ); } // Reverse order for parents* and prev-derivatives if ( rparentsprev.test( name ) ) { matched.reverse(); } } return this.pushStack( matched ); }; }); 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 // 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" ) { 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; } // 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" ); } } }); /** * The ready event handler and self cleanup method */ function completed() { document.removeEventListener( "DOMContentLoaded", completed, false ); window.removeEventListener( "load", completed, false ); 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 ); } else { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed, false ); } } return readyList.promise( obj ); }; // Kick off the DOM ready check even if the user does not jQuery.ready.promise(); // 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, len = 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 < len; i++ ) { fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); } } } return chainable ? elems : // Gets bulk ? fn.call( elems ) : len ? fn( elems[0], key ) : emptyGet; }; /** * Determines whether an object can have data */ jQuery.acceptData = function( owner ) { // Accepts only: // - Node // - Node.ELEMENT_NODE // - Node.DOCUMENT_NODE // - Object // - Any /* jshint -W018 */ return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType ); }; function Data() { // Support: Android < 4, // Old WebKit does not have Object.preventExtensions/freeze method, // return new empty object instead with no [[set]] accessor Object.defineProperty( this.cache = {}, 0, { get: function() { return {}; } }); this.expando = jQuery.expando + Math.random(); } Data.uid = 1; Data.accepts = jQuery.acceptData; Data.prototype = { key: function( owner ) { // We can accept data for non-element nodes in modern browsers, // but we should not, see #8335. // Always return the key for a frozen object. if ( !Data.accepts( owner ) ) { return 0; } var descriptor = {}, // Check if the owner object already has a cache key unlock = owner[ this.expando ]; // If not, create one if ( !unlock ) { unlock = Data.uid++; // Secure it in a non-enumerable, non-writable property try { descriptor[ this.expando ] = { value: unlock }; Object.defineProperties( owner, descriptor ); // Support: Android < 4 // Fallback to a less secure definition } catch ( e ) { descriptor[ this.expando ] = unlock; jQuery.extend( owner, descriptor ); } } // Ensure the cache object if ( !this.cache[ unlock ] ) { this.cache[ unlock ] = {}; } return unlock; }, set: function( owner, data, value ) { var prop, // There may be an unlock assigned to this node, // if there is no entry for this "owner", create one inline // and set the unlock as though an owner entry had always existed unlock = this.key( owner ), cache = this.cache[ unlock ]; // Handle: [ owner, key, value ] args if ( typeof data === "string" ) { cache[ data ] = value; // Handle: [ owner, { properties } ] args } else { // Fresh assignments by object are shallow copied if ( jQuery.isEmptyObject( cache ) ) { jQuery.extend( this.cache[ unlock ], data ); // Otherwise, copy the properties one-by-one to the cache object } else { for ( prop in data ) { cache[ prop ] = data[ prop ]; } } } return cache; }, get: function( owner, key ) { // Either a valid cache is found, or will be created. // New caches will be created and the unlock returned, // allowing direct access to the newly created // empty data object. A valid owner object must be provided. var cache = this.cache[ this.key( owner ) ]; return key === undefined ? cache : cache[ key ]; }, access: function( owner, key, value ) { var stored; // In cases where either: // // 1. No key was specified // 2. A string key was specified, but no value provided // // Take the "read" path and allow the get method to determine // which value to return, respectively either: // // 1. The entire cache object // 2. The data stored at the key // if ( key === undefined || ((key && typeof key === "string") && value === undefined) ) { stored = this.get( owner, key ); return stored !== undefined ? stored : this.get( owner, jQuery.camelCase(key) ); } // [*]When the key is not a string, or both a key and value // are specified, set or extend (existing objects) with either: // // 1. An object of properties // 2. A key and value // this.set( owner, key, value ); // Since the "set" path can have two possible entry points // return the expected data based on which path was taken[*] return value !== undefined ? value : key; }, remove: function( owner, key ) { var i, name, camel, unlock = this.key( owner ), cache = this.cache[ unlock ]; if ( key === undefined ) { this.cache[ unlock ] = {}; } else { // Support array or space separated string of keys if ( jQuery.isArray( key ) ) { // If "name" is an array of keys... // When data is initially created, via ("key", "val") signature, // keys will be converted to camelCase. // Since there is no way to tell _how_ a key was added, remove // both plain key and camelCase key. #12786 // This will only penalize the array argument path. name = key.concat( key.map( jQuery.camelCase ) ); } else { camel = jQuery.camelCase( key ); // Try the string as a key before any manipulation if ( key in cache ) { name = [ key, camel ]; } else { // If a key with the spaces exists, use it. // Otherwise, create an array by matching non-whitespace name = camel; name = name in cache ? [ name ] : ( name.match( rnotwhite ) || [] ); } } i = name.length; while ( i-- ) { delete cache[ name[ i ] ]; } } }, hasData: function( owner ) { return !jQuery.isEmptyObject( this.cache[ owner[ this.expando ] ] || {} ); }, discard: function( owner ) { if ( owner[ this.expando ] ) { delete this.cache[ owner[ this.expando ] ]; } } }; var data_priv = new Data(); var data_user = new Data(); /* Implementation Summary 1. Enforce API surface and semantic compatibility with 1.9.x branch 2. Improve the module's maintainability by reducing the storage paths to a single mechanism. 3. Use the same single mechanism to support "private" and "user" data. 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) 5. Avoid exposing implementation details on user objects (eg. expando properties) 6. Provide a clear path for implementation upgrade to WeakMap in 2014 */ var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, rmultiDash = /([A-Z])/g; function dataAttr( elem, key, data ) { var name; // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { name = "data-" + key.replace( rmultiDash, "-$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 data_user.set( elem, key, data ); } else { data = undefined; } } return data; } jQuery.extend({ hasData: function( elem ) { return data_user.hasData( elem ) || data_priv.hasData( elem ); }, data: function( elem, name, data ) { return data_user.access( elem, name, data ); }, removeData: function( elem, name ) { data_user.remove( elem, name ); }, // TODO: Now that all calls to _data and _removeData have been replaced // with direct calls to data_priv methods, these can be deprecated. _data: function( elem, name, data ) { return data_priv.access( elem, name, data ); }, _removeData: function( elem, name ) { data_priv.remove( elem, name ); } }); jQuery.fn.extend({ data: function( key, value ) { var i, name, data, elem = this[ 0 ], attrs = elem && elem.attributes; // Gets all values if ( key === undefined ) { if ( this.length ) { data = data_user.get( elem ); if ( elem.nodeType === 1 && !data_priv.get( elem, "hasDataAttrs" ) ) { 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 ] ); } } } data_priv.set( elem, "hasDataAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { data_user.set( this, key ); }); } return access( this, function( value ) { var data, camelKey = jQuery.camelCase( key ); // The calling jQuery object (element matches) is not empty // (and therefore has an element appears at this[ 0 ]) and the // `value` parameter was not undefined. An empty jQuery object // will result in `undefined` for elem = this[ 0 ] which will // throw an exception if an attempt to read a data cache is made. if ( elem && value === undefined ) { // Attempt to get data from the cache // with the key as-is data = data_user.get( elem, key ); if ( data !== undefined ) { return data; } // Attempt to get data from the cache // with the key camelized data = data_user.get( elem, camelKey ); if ( data !== undefined ) { return data; } // Attempt to "discover" the data in // HTML5 custom data-* attrs data = dataAttr( elem, camelKey, undefined ); if ( data !== undefined ) { return data; } // We tried really hard, but the data doesn't exist. return; } // Set the data... this.each(function() { // First, attempt to store a copy or reference of any // data that might've been store with a camelCased key. var data = data_user.get( this, camelKey ); // For HTML5 data-* attribute interop, we have to // store property names with dashes in a camelCase form. // This might not apply to all properties...* data_user.set( this, camelKey, value ); // *... In the case of properties that might _actually_ // have dashes, we need to also store a copy of that // unchanged property. if ( key.indexOf("-") !== -1 && data !== undefined ) { data_user.set( this, key, value ); } }); }, null, value, arguments.length > 1, null, true ); }, removeData: function( key ) { return this.each(function() { data_user.remove( this, key ); }); } }); jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = data_priv.get( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray( data ) ) { queue = data_priv.access( 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 data_priv.get( elem, key ) || data_priv.access( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { data_priv.remove( elem, [ type + "queue", 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 = data_priv.get( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } }); var pnum = (/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source; 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 ); }; var rcheckableType = (/^(?:checkbox|radio)$/i); (function() { var fragment = document.createDocumentFragment(), div = fragment.appendChild( document.createElement( "div" ) ), input = document.createElement( "input" ); // #11217 - WebKit loses check when the name is after the checked attribute // Support: Windows Web Apps (WWA) // `name` and `type` need .setAttribute for WWA input.setAttribute( "type", "radio" ); input.setAttribute( "checked", "checked" ); input.setAttribute( "name", "t" ); div.appendChild( input ); // 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; // Make sure textarea (and checkbox) defaultValue is properly cloned // Support: IE9-IE11+ div.innerHTML = "<textarea>x</textarea>"; support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; })(); var strundefined = typeof undefined; support.focusinBubbles = "onfocusin" in window; var 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 handleObjIn, eventHandle, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = data_priv.get( 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 && jQuery.event.triggered !== e.type ? jQuery.event.dispatch.apply( elem, arguments ) : undefined; }; } // 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 if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } } } 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; } }, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var j, origCount, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = data_priv.hasData( elem ) && data_priv.get( 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; data_priv.remove( elem, "events" ); } }, trigger: function( event, data, elem, onlyHandlers ) { var i, cur, tmp, bubbleType, ontype, handle, special, 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 = ( data_priv.get( cur, "events" ) || {} )[ event.type ] && data_priv.get( 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. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && jQuery.isFunction( 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; elem[ type ](); 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, j, ret, matched, handleObj, handlerQueue = [], args = slice.call( arguments ), handlers = ( data_priv.get( 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 i, matches, sel, handleObj, 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") ) { for ( ; cur !== this; cur = cur.parentNode || this ) { // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( 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; }, // 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 offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var eventDoc, doc, body, button = original.button; // 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 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, 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: Cordova 2.5 (WebKit) (#13255) // All events should have a target; Cordova deviceready doesn't if ( !event.target ) { event.target = document; } // Support: Safari 6.0+, Chrome < 28 // Target should not be a text node (#504, #13143) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } return fixHook.filter ? fixHook.filter( event, originalEvent ) : 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 ) { this.focus(); return false; } }, 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 ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) { 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 = function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } }; 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: 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 && e.preventDefault ) { e.preventDefault(); } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( e && e.stopPropagation ) { e.stopPropagation(); } }, 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 // Support: Chrome 15+ 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; } }; }); // Create "bubbling" focus and blur events // Support: Firefox, Chrome, Safari 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 = data_priv.access( doc, fix ); if ( !attaches ) { doc.addEventListener( orig, handler, true ); } data_priv.access( doc, fix, ( attaches || 0 ) + 1 ); }, teardown: function() { var doc = this.ownerDocument || this, attaches = data_priv.access( doc, fix ) - 1; if ( !attaches ) { doc.removeEventListener( orig, handler, true ); data_priv.remove( doc, fix ); } else { data_priv.access( doc, fix, attaches ); } } }; }); } 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" ) { // ( 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 ); } } }); var rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, 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 = { // Support: IE 9 option: [ 1, "<select multiple='multiple'>", "</select>" ], thead: [ 1, "<table>", "</table>" ], col: [ 2, "<table><colgroup>", "</colgroup></table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], _default: [ 0, "", "" ] }; // Support: IE 9 wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; // Support: 1.x compatibility // Manipulating tables requires a tbody function manipulationTarget( elem, content ) { return jQuery.nodeName( elem, "table" ) && jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ? elem.getElementsByTagName("tbody")[0] || elem.appendChild( elem.ownerDocument.createElement("tbody") ) : elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { elem.type = (elem.getAttribute("type") !== null) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[ 1 ]; } else { elem.removeAttribute("type"); } return elem; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var i = 0, l = elems.length; for ( ; i < l; i++ ) { data_priv.set( elems[ i ], "globalEval", !refElements || data_priv.get( refElements[ i ], "globalEval" ) ); } } function cloneCopyEvent( src, dest ) { var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events; if ( dest.nodeType !== 1 ) { return; } // 1. Copy private data: events, handlers, etc. if ( data_priv.hasData( src ) ) { pdataOld = data_priv.access( src ); pdataCur = data_priv.set( dest, pdataOld ); events = pdataOld.events; if ( events ) { delete pdataCur.handle; pdataCur.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } } // 2. Copy user data if ( data_user.hasData( src ) ) { udataOld = data_user.access( src ); udataCur = jQuery.extend( {}, udataOld ); data_user.set( dest, udataCur ); } } function getAll( context, tag ) { var ret = context.getElementsByTagName ? context.getElementsByTagName( tag || "*" ) : context.querySelectorAll ? context.querySelectorAll( tag || "*" ) : []; return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], ret ) : ret; } // Support: IE >= 9 function fixInput( src, dest ) { var nodeName = dest.nodeName.toLowerCase(); // Fails to persist the checked state of a cloned checkbox or radio button. if ( nodeName === "input" && rcheckableType.test( src.type ) ) { dest.checked = src.checked; // Fails to return the selected option to the default selected state when cloning options } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var i, l, srcElements, destElements, clone = elem.cloneNode( true ), inPage = jQuery.contains( elem.ownerDocument, elem ); // Support: IE >= 9 // Fix Cloning issues if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && !jQuery.isXMLDoc( elem ) ) { // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); for ( i = 0, l = srcElements.length; i < l; i++ ) { fixInput( srcElements[ i ], destElements[ i ] ); } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0, l = srcElements.length; i < l; i++ ) { cloneCopyEvent( srcElements[ i ], destElements[ i ] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } // Return the cloned set return clone; }, buildFragment: function( elems, context, scripts, selection ) { var elem, tmp, tag, wrap, contains, j, fragment = context.createDocumentFragment(), nodes = [], i = 0, l = elems.length; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { // Support: QtWebKit // jQuery.merge because push.apply(_, arraylike) throws 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 || fragment.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; } // Support: QtWebKit // jQuery.merge because push.apply(_, arraylike) throws jQuery.merge( nodes, tmp.childNodes ); // Remember the top-level container tmp = fragment.firstChild; // Fixes #12346 // Support: Webkit, IE tmp.textContent = ""; } } } // Remove wrapper from fragment fragment.textContent = ""; 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( fragment.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 ); } } } } return fragment; }, cleanData: function( elems ) { var data, elem, type, key, special = jQuery.event.special, i = 0; for ( ; (elem = elems[ i ]) !== undefined; i++ ) { if ( jQuery.acceptData( elem ) ) { key = elem[ data_priv.expando ]; if ( key && (data = data_priv.cache[ key ]) ) { 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 ); } } } if ( data_priv.cache[ key ] ) { // Discard any remaining `private` data delete data_priv.cache[ key ]; } } } // Discard any remaining `user` data delete data_user.cache[ elem[ data_user.expando ] ]; } } }); jQuery.fn.extend({ text: function( value ) { return access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().each(function() { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { this.textContent = value; } }); }, null, value, arguments.length ); }, append: function() { return this.domManip( arguments, function( elem ) { 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++ ) { if ( elem.nodeType === 1 ) { // Prevent memory leaks jQuery.cleanData( getAll( elem, false ) ); // Remove any remaining nodes elem.textContent = ""; } } 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 && elem.nodeType === 1 ) { return elem.innerHTML; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for ( ; i < l; i++ ) { elem = this[ i ] || {}; // Remove element nodes and prevent memory leaks 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 fragment, first, scripts, hasScripts, node, doc, 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 ) { // Support: QtWebKit // jQuery.merge because push.apply(_, arraylike) throws 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 || "" ) && !data_priv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Optional AJAX dependency, but won't run scripts if not present if ( jQuery._evalUrl ) { jQuery._evalUrl( node.src ); } } else { jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) ); } } } } } } return this; } }); jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, ret = [], insert = jQuery( selector ), last = insert.length - 1, i = 0; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone( true ); jQuery( insert[ i ] )[ original ]( elems ); // Support: QtWebKit // .get() because push.apply(_, arraylike) throws 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 ].contentDocument; // Support: IE doc.write(); doc.close(); display = actualDisplay( nodeName, doc ); iframe.detach(); } // Store the correct default display elemdisplay[ nodeName ] = display; } return display; } var rmargin = (/^margin/); var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" ); var getStyles = function( elem ) { return elem.ownerDocument.defaultView.getComputedStyle( elem, null ); }; function curCSS( elem, name, computed ) { var width, minWidth, maxWidth, ret, style = elem.style; computed = computed || getStyles( elem ); // Support: IE9 // getPropertyValue is only needed for .css('filter') in IE9, see #12537 if ( computed ) { ret = computed.getPropertyValue( name ) || computed[ name ]; } if ( computed ) { if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { ret = jQuery.style( elem, name ); } // Support: iOS < 6 // A tribute to the "awesome hack by Dean Edwards" // iOS < 6 (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; } } return ret !== undefined ? // Support: IE // IE returns zIndex value as an integer. ret + "" : ret; } function addGetHookIf( conditionFn, hookFn ) { // Define the hook, we'll check on the first run if it's really needed. return { get: function() { if ( conditionFn() ) { // 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() { var pixelPositionVal, boxSizingReliableVal, docElem = document.documentElement, container = document.createElement( "div" ), div = document.createElement( "div" ); if ( !div.style ) { return; } div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; container.style.cssText = "border:0;width:0;height:0;top:0;left:-9999px;margin-top:1px;" + "position:absolute"; container.appendChild( div ); // Executing both pixelPosition & boxSizingReliable tests require only one layout // so they're executed at the same time to save the second computation. function computePixelPositionAndBoxSizingReliable() { 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"; div.innerHTML = ""; docElem.appendChild( container ); var divStyle = window.getComputedStyle( div, null ); pixelPositionVal = divStyle.top !== "1%"; boxSizingReliableVal = divStyle.width === "4px"; docElem.removeChild( container ); } // Support: node.js jsdom // Don't assume that getComputedStyle is a property of the global object if ( window.getComputedStyle ) { jQuery.extend( support, { pixelPosition: function() { // This test is executed only once but we still do memoizing // since we can use the boxSizingReliable pre-computing. // No need to check if the test was already performed, though. computePixelPositionAndBoxSizingReliable(); return pixelPositionVal; }, boxSizingReliable: function() { if ( boxSizingReliableVal == null ) { computePixelPositionAndBoxSizingReliable(); } return boxSizingReliableVal; }, reliableMarginRight: function() { // Support: Android 2.3 // Check if 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 // This support function is only executed once so no memoizing is needed. var ret, marginDiv = div.appendChild( document.createElement( "div" ) ); // Reset CSS: box-sizing; display; margin; border; padding marginDiv.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"; marginDiv.style.marginRight = marginDiv.style.width = "0"; div.style.width = "1px"; docElem.appendChild( container ); ret = !parseFloat( window.getComputedStyle( marginDiv, null ).marginRight ); docElem.removeChild( container ); return ret; } }); } })(); // 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 // 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[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 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 = 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"; } 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 ] = data_priv.get( 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 ] = data_priv.access( elem, "olddisplay", defaultDisplay(elem.nodeName) ); } } else { hidden = isHidden( elem ); if ( display !== "none" || !hidden ) { data_priv.set( 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; } 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": "cssFloat" }, // 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 specifying 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 ) { style[ name ] = value; } } 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 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, 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, jQuery.css( elem, "boxSizing", false, styles ) === "border-box", styles ) : 0 ); } }; }); // Support: Android 2.3 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: IE9 // 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, i = 0, attrs = { height: type }; // 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 = data_priv.get( 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 IE9-10 do 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" ? data_priv.get( elem, "olddisplay" ) || defaultDisplay( elem.nodeName ) : display; if ( checkDisplay === "inline" && jQuery.css( elem, "float" ) === "none" ) { style.display = "inline-block"; } } if ( opts.overflow ) { style.overflow = "hidden"; 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 = data_priv.access( 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; data_priv.remove( 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 || data_priv.get( 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 = data_priv.get( 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 = data_priv.get( 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, i = 0, timers = jQuery.timers; 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() { var input = document.createElement( "input" ), select = document.createElement( "select" ), opt = select.appendChild( document.createElement( "option" ) ); input.type = "checkbox"; // Support: iOS 5.1, Android 4.x, Android 2.3 // Check the default checkbox/radio value ("" on old WebKit; "on" elsewhere) support.checkOn = input.value !== ""; // Must access the parent to make an option select properly // Support: IE9, IE10 support.optSelected = opt.selected; // 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; // Check if an input maintains its value after becoming a radio // Support: IE9, IE10 input = document.createElement( "input" ); input.value = "t"; input.type = "radio"; support.radioValue = input.value === "t"; })(); var nodeHook, boolHook, attrHandle = jQuery.expr.attrHandle; 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 elem[ propName ] = false; } elem.removeAttribute( name ); } } }, 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; } } } } }); // Hooks for boolean attributes boolHook = { set: function( elem, value, name ) { if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else { elem.setAttribute( name, name ); } return name; } }; jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { var getter = attrHandle[ name ] || jQuery.find.attr; attrHandle[ 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; }; }); var rfocusable = /^(?:input|select|textarea|button)$/i; jQuery.fn.extend({ prop: function( name, value ) { return access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { return this.each(function() { delete this[ jQuery.propFix[ name ] || name ]; }); } }); 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 ) { return elem.hasAttribute( "tabindex" ) || rfocusable.test( elem.nodeName ) || elem.href ? elem.tabIndex : -1; } } } }); // Support: IE9+ // Selectedness for an option in an optgroup can be inaccurate if ( !support.optSelected ) { jQuery.propHooks.selected = { get: function( elem ) { var parent = elem.parentNode; if ( parent && 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; }); var rclass = /[\t\r\n\f]/g; jQuery.fn.extend({ addClass: function( value ) { var classes, elem, cur, clazz, j, finalValue, proceed = typeof value === "string" && value, i = 0, len = this.length; 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, proceed = arguments.length === 0 || typeof value === "string" && value, i = 0, len = this.length; 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 data_priv.set( 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 ? "" : data_priv.get( 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; } }); 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 ]; // IE6-9 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 ( (option.selected = jQuery.inArray( option.value, values ) >= 0) ) { optionSet = true; } } // force browsers to behave consistently when non-matching value is set if ( !optionSet ) { elem.selectedIndex = -1; } return values; } } } }); // 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; }; } }); // 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 = (/\?/); // Support: Android 2.3 // Workaround failure to string-cast null input jQuery.parseJSON = function( data ) { return JSON.parse( data + "" ); }; // Cross-browser xml parsing jQuery.parseXML = function( data ) { var xml, tmp; if ( !data || typeof data !== "string" ) { return null; } // Support: IE9 try { tmp = new DOMParser(); xml = tmp.parseFromString( data, "text/xml" ); } catch ( e ) { xml = undefined; } if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }; var // Document location ajaxLocParts, ajaxLocation, rhash = /#.*$/, rts = /([?&])_=[^&]*/, rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg, // #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[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 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 ); } 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 ct, type, finalDataType, firstDataType, 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 transport, // URL without anti-cache param cacheURL, // Response headers responseHeadersString, responseHeaders, // 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 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 (prefilters might expect it) // 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 fireGlobals = 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 }); }; }); // 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._evalUrl = function( url ) { return jQuery.ajax({ url: url, type: "GET", dataType: "script", async: false, global: false, "throws": true }); }; jQuery.fn.extend({ wrapAll: function( html ) { var wrap; 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 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.firstElementChild ) { elem = elem.firstElementChild; } 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; }; 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(); } }); jQuery.ajaxSettings.xhr = function() { try { return new XMLHttpRequest(); } catch( e ) {} }; var xhrId = 0, xhrCallbacks = {}, xhrSuccessStatus = { // file protocol always yields status code 0, assume 200 0: 200, // Support: IE9 // #1450: sometimes IE returns 1223 when it should be 204 1223: 204 }, xhrSupported = jQuery.ajaxSettings.xhr(); // Support: IE9 // Open requests must be manually aborted on unload (#5280) if ( window.ActiveXObject ) { jQuery( window ).on( "unload", function() { for ( var key in xhrCallbacks ) { xhrCallbacks[ key ](); } }); } support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); support.ajax = xhrSupported = !!xhrSupported; jQuery.ajaxTransport(function( options ) { var callback; // Cross domain only allowed if supported through XMLHttpRequest if ( support.cors || xhrSupported && !options.crossDomain ) { return { send: function( headers, complete ) { var i, xhr = options.xhr(), id = ++xhrId; 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 ) { xhr.setRequestHeader( i, headers[ i ] ); } // Callback callback = function( type ) { return function() { if ( callback ) { delete xhrCallbacks[ id ]; callback = xhr.onload = xhr.onerror = null; if ( type === "abort" ) { xhr.abort(); } else if ( type === "error" ) { complete( // file: protocol always yields status 0; see #8605, #14207 xhr.status, xhr.statusText ); } else { complete( xhrSuccessStatus[ xhr.status ] || xhr.status, xhr.statusText, // Support: IE9 // Accessing binary-data responseText throws an exception // (#11426) typeof xhr.responseText === "string" ? { text: xhr.responseText } : undefined, xhr.getAllResponseHeaders() ); } } }; }; // Listen to events xhr.onload = callback(); xhr.onerror = callback("error"); // Create the abort callback callback = xhrCallbacks[ id ] = callback("abort"); try { // Do send the request (this may raise an exception) xhr.send( options.hasContent && options.data || null ); } catch ( e ) { // #14683: Only rethrow if this hasn't been notified as an error yet if ( callback ) { throw e; } } }, abort: function() { if ( callback ) { callback(); } } }; } }); // 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 crossDomain jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function( s ) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, callback; return { send: function( _, complete ) { script = jQuery("<script>").prop({ async: true, charset: s.scriptCharset, src: s.url }).on( "load error", callback = function( evt ) { script.remove(); callback = null; if ( evt ) { complete( evt.type === "error" ? 404 : 200, evt.type ); } } ); document.head.appendChild( script[ 0 ] ); }, abort: function() { if ( callback ) { callback(); } } }; } }); 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, type, response, self = this, off = url.indexOf(" "); if ( off >= 0 ) { selector = jQuery.trim( url.slice( off ) ); 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; }; 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; } 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" ) && ( curCSSTop + curCSSLeft ).indexOf("auto") > -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, elem = this[ 0 ], box = { top: 0, left: 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.clientTop, left: box.left + win.pageXOffset - docElem.clientLeft }; }, position: function() { if ( !this[ 0 ] ) { return; } var offsetParent, offset, elem = this[ 0 ], parentOffset = { top: 0, left: 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 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 = "pageYOffset" === prop; jQuery.fn[ method ] = function( val ) { return access( this, function( elem, method, val ) { var win = getWindow( elem ); if ( val === undefined ) { return win ? win[ prop ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : window.pageXOffset, top ? val : window.pageYOffset ); } 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 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; })); },{}],"media_control":[function(require,module,exports){ "use strict"; module.exports = require('./media_control'); },{"./media_control":22}],"mediator":[function(require,module,exports){ "use strict"; var Events = require('../base/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; },{"../base/events":8}],"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; },{}],"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('jquery'); 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":11,"base_object":"base_object","jquery":"jquery","underscore":6}]},{},[3,1]);
ajax/libs/react-table/2.2.1/react-table.js
him2him2/cdnjs
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.reactTable = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ "use strict";function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function remove(e,t){return e.filter(function(a,s){var n=t(a);return!!n&&(e.splice(s,1),!0)})}function get(e,t){return isArray(t)&&(t=t.join(".")),t.replace("[",".").replace("]","").split(".").reduce(function(e,t){return e[t]},e)}function takeRight(e,t){var a=t>e.length?0:e.length-t;return e.slice(a)}function last(e){return e[e.length-1]}function range(e){for(var t=[],a=0;a<e;a++)t.push(e);return t}function orderBy(e,t,a){return e.sort(function(e,s){for(var n=0;n<t.length;n++){var r=t[n],o=r(e),i=r(s),l=a[n]===!1||"desc"===a[n];if(o>i)return l?-1:1;if(o<i)return l?1:-1}return 0})}function clone(e){return JSON.parse(JSON.stringify(e,function(e,t){return"function"==typeof t?t.toString():t}))}function isArray(e){return Array.isArray(e)}var _typeof2="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};Object.defineProperty(exports,"__esModule",{value:!0}),exports.ReactTableDefaults=void 0;var _typeof="function"==typeof Symbol&&"symbol"===_typeof2(Symbol.iterator)?function(e){return"undefined"==typeof e?"undefined":_typeof2(e)}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":"undefined"==typeof e?"undefined":_typeof2(e)},_extends=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var a=arguments[t];for(var s in a)Object.prototype.hasOwnProperty.call(a,s)&&(e[s]=a[s])}return e},_react=require("react"),_react2=_interopRequireDefault(_react),_classnames=require("classnames"),_classnames2=_interopRequireDefault(_classnames),_={get:get,takeRight:takeRight,last:last,orderBy:orderBy,range:range,clone:clone,remove:remove},defaultButton=function(e){return _react2.default.createElement("button",_extends({},e,{className:"-btn"}),e.children)},ReactTableDefaults=exports.ReactTableDefaults={className:"-striped -highlight",tableClassName:"",theadClassName:"",tbodyClassName:"",trClassName:"",trClassCallback:function(e){return null},thClassName:"",thGroupClassName:"",tdClassName:"",paginationClassName:"",style:{},tableStyle:{},theadStyle:{},tbodyStyle:{},trStyle:{},trStyleCallback:function(e){},thStyle:{},tdStyle:{},paginationStyle:{},pageSize:20,minRows:0,column:{sortable:!0,show:!0,className:"",style:{},innerClassName:"",innerStyle:{},headerClassName:"",headerStyle:{},headerInnerClassName:"",headerInnerStyle:{}},previousText:"Previous",nextText:"Next",loadingText:"Loading...",tableComponent:function(e){return _react2.default.createElement("table",e,e.children)},theadComponent:function(e){return _react2.default.createElement("thead",e,e.children)},tbodyComponent:function(e){return _react2.default.createElement("tbody",e,e.children)},trComponent:function(e){return _react2.default.createElement("tr",e,e.children)},thComponent:function(e){return _react2.default.createElement("th",e,e.children)},tdComponent:function(e){return _react2.default.createElement("td",e,e.children)},previousComponent:null,nextComponent:null,data:[]};exports.default=_react2.default.createClass({displayName:"src",getDefaultProps:function(){return ReactTableDefaults},getInitialState:function(){return{sorting:!1}},componentWillMount:function(){this.update(this.props)},componentWillReceiveProps:function(e){this.update(e)},update:function(e){var t={loading:!1,page:0,pages:-1};this.setState(t);var a=Object.assign({},this.state,t);this.isAsync="function"==typeof e.data,this.buildColumns(e,a),this.buildData(e,a)},buildColumns:function(e){var t=this;this.hasHeaderGroups=!1,e.columns.forEach(function(e){e.columns&&(t.hasHeaderGroups=!0)}),this.headerGroups=[],this.decoratedColumns=[];var a=[],s=function(e){var s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};t.headerGroups.push(Object.assign({},s,{columns:e})),a=[]},n=function(e){var a=Object.assign({},t.props.column,e);if("string"==typeof a.accessor){var s=function(){a.id=a.id||a.accessor;var e=a.accessor;return a.accessor=function(t){return _.get(t,e)},{v:a}}();if("object"===("undefined"==typeof s?"undefined":_typeof(s)))return s.v}if(a.accessor&&!a.id)throw console.warn(a),new Error("A column id is required if using a non-string accessor for column above.");return a.accessor=function(e){},a};e.columns.forEach(function(e,r){e.columns?(e.columns.forEach(function(e){t.decoratedColumns.push(n(e))}),t.hasHeaderGroups&&(a.length>0&&s(a),s(_.takeRight(t.decoratedColumns,e.columns.length),e))):(t.decoratedColumns.push(n(e)),a.push(_.last(t.decoratedColumns)))}),this.hasHeaderGroups&&a.length>0&&s(a)},getInitSorting:function(){var e=this.decoratedColumns.filter(function(e){return"undefined"!=typeof e.sort}).map(function(e){return{id:e.id,asc:"asc"===e.sort}});return e.length?e:[{id:this.decoratedColumns[0].id,asc:!0}]},buildData:function(e,t){var a=this,s=t.sorting===!1?this.getInitSorting():t.sorting,n=function(e){a.setState({sorting:s,data:e,page:t.page,loading:!1})};if(this.isAsync){this.setState({loading:!0});var r=function(e){if(!e)return Promise.reject("Uh Oh! Nothing was returned in ReactTable's data callback!");e.pages&&a.setState({pages:e.pages});var t=a.accessData(e.rows);n(t)},o=e.data({sorting:s,page:t.page||0,pageSize:e.pageSize,pages:t.pages},r);o&&o.then&&o.then(r)}else{var i=this.accessData(e.data),l=this.sortData(i,s);n(l)}},accessData:function(e){var t=this;return e.map(function(e,a){var s={__original:e,__index:a};return t.decoratedColumns.forEach(function(t){s[t.id]=t.accessor(e)}),s})},sortData:function(e,t){var a=t.length?t:this.getInitSorting();return _.orderBy(e,a.map(function(e){return function(t){return null===t[e.id]||void 0===t[e.id]?-(1/0):"string"==typeof t[e.id]?t[e.id].toLowerCase():t[e.id]}}),a.map(function(e){return e.asc?"asc":"desc"}))},setPage:function(e){return this.isAsync?this.buildData(this.props,Object.assign({},this.state,{page:e})):void this.setState({page:e})},render:function(){var e=this,t=this.state.data?this.state.data:[],a=this.isAsync?this.state.pages:Math.ceil(t.length/this.props.pageSize),s=this.props.pageSize*this.state.page,n=s+this.props.pageSize,r=this.isAsync?t.slice(0,this.props.pageSize):t.slice(s,n),o=a>1?_.range(this.props.pageSize-r.length):this.props.minRows?_.range(Math.max(this.props.minRows-r.length,0)):[],i=this.state.page>0,l=this.state.page+1<a,c=this.props.tableComponent,u=this.props.theadComponent,d=this.props.tbodyComponent,p=this.props.trComponent,f=this.props.thComponent,h=this.props.tdComponent,m=this.props.previousComponent||defaultButton,y=this.props.nextComponent||defaultButton;return _react2.default.createElement("div",{className:(0,_classnames2.default)(this.props.className,"ReactTable"),style:this.props.style},_react2.default.createElement(c,{className:(0,_classnames2.default)(this.props.tableClassName),style:this.props.tableStyle},this.hasHeaderGroups&&_react2.default.createElement(u,{className:(0,_classnames2.default)(this.props.theadGroupClassName,"-headerGroups"),style:this.props.theadStyle},_react2.default.createElement(p,{className:this.props.trClassName,style:this.props.trStyle},this.headerGroups.map(function(t,a){return _react2.default.createElement(f,{key:a,colSpan:t.columns.length,className:(0,_classnames2.default)(e.props.thClassname,t.headerClassName),style:Object.assign({},e.props.thStyle,t.headerStyle)},_react2.default.createElement("div",{className:(0,_classnames2.default)(t.headerInnerClassName,"-th-inner"),style:Object.assign({},e.props.thInnerStyle,t.headerInnerStyle)},"function"==typeof t.header?_react2.default.createElement(t.header,{data:e.props.data,column:t}):t.header))}))),_react2.default.createElement(u,{className:(0,_classnames2.default)(this.props.theadClassName),style:this.props.theadStyle},_react2.default.createElement(p,{className:this.props.trClassName,style:this.props.trStyle},this.decoratedColumns.map(function(t,a){var s=e.state.sorting.find(function(e){return e.id===t.id}),n="function"==typeof t.show?t.show():t.show;return _react2.default.createElement(f,{key:a,className:(0,_classnames2.default)(e.props.thClassname,t.headerClassName,s?s.asc?"-sort-asc":"-sort-desc":"",{"-cursor-pointer":t.sortable,"-hidden":!n}),style:Object.assign({},e.props.thStyle,t.headerStyle),onClick:function(a){t.sortable&&e.sortColumn(t,a.shiftKey)}},_react2.default.createElement("div",{className:(0,_classnames2.default)(t.headerInnerClassName,"-th-inner"),style:Object.assign({},t.headerInnerStyle,{minWidth:t.minWidth+"px"})},"function"==typeof t.header?_react2.default.createElement(t.header,{data:e.props.data,column:t}):t.header))}))),_react2.default.createElement(d,{className:(0,_classnames2.default)(this.props.tbodyClassName),style:this.props.tbodyStyle},r.map(function(t,a){var s={row:t.__original,index:t.__index,viewIndex:a};return _react2.default.createElement(p,{key:a,className:(0,_classnames2.default)(e.props.trClassName,e.props.trClassCallback(s)),style:Object.assign({},e.props.trStyle,e.props.trStyleCallback(s))},e.decoratedColumns.map(function(a,n){var r=a.render,o="function"==typeof a.show?a.show():a.show;return _react2.default.createElement(h,{key:n,className:(0,_classnames2.default)(a.className,{hidden:!o}),style:Object.assign({},e.props.tdStyle,a.style)},_react2.default.createElement("div",{className:(0,_classnames2.default)(a.innerClassName,"-td-inner"),style:Object.assign({},a.innerStyle,{minWidth:a.minWidth+"px"})},"function"==typeof r?_react2.default.createElement(r,_extends({value:t[a.id]},s)):"undefined"!=typeof r?r:t[a.id]))}))}),o.map(function(t,a){return _react2.default.createElement(p,{key:a,className:(0,_classnames2.default)(e.props.trClassName,"-padRow"),style:e.props.trStyle},e.decoratedColumns.map(function(t,a){var s="function"==typeof t.show?t.show():t.show;return _react2.default.createElement(h,{key:a,className:(0,_classnames2.default)(t.className,{hidden:!s}),style:Object.assign({},e.props.tdStyle,t.style)},_react2.default.createElement("div",{className:(0,_classnames2.default)(t.innerClassName,"-td-inner"),style:Object.assign({},t.innerStyle,{minWidth:t.minWidth+"px"})}," "))}))}))),a>1&&_react2.default.createElement("div",{className:(0,_classnames2.default)(this.props.paginationClassName,"-pagination"),style:this.props.paginationStyle},_react2.default.createElement("div",{className:"-left"},_react2.default.createElement(m,{onClick:i&&function(t){return e.previousPage(t)},disabled:!i},this.props.previousText)),_react2.default.createElement("div",{className:"-center"},"Page ",this.state.page+1," of ",a),_react2.default.createElement("div",{className:"-right"},_react2.default.createElement(y,{onClick:l&&function(t){return e.nextPage(t)},disabled:!l},this.props.nextText))),_react2.default.createElement("div",{className:(0,_classnames2.default)("-loading",{"-active":this.state.loading})},_react2.default.createElement("div",{className:"-loading-inner"},this.props.loadingText)))},sortColumn:function(e,t){var a=this.state.sorting||[],s=_.clone(this.state.sorting||[]),n=s.findIndex(function(t){return t.id===e.id});if(n>-1){var r=s[n];r.asc?(r.asc=!1,t||(s=[r])):t?s.splice(n,1):(r.asc=!0,s=[r])}else t?s.push({id:e.id,asc:!0}):s=[{id:e.id,asc:!0}];var o=0===n||!a.length&&s.length||!t?0:this.state.page;this.buildData(this.props,Object.assign({},this.state,{page:o,sorting:s}))},nextPage:function(e){e.preventDefault(),this.setPage(this.state.page+1)},previousPage:function(e){e.preventDefault(),this.setPage(this.state.page-1)}}); },{"classnames":2,"react":"react"}],2:[function(require,module,exports){ !function(){"use strict";function e(){for(var r=[],o=0;o<arguments.length;o++){var f=arguments[o];if(f){var i=typeof f;if("string"===i||"number"===i)r.push(f);else if(Array.isArray(f))r.push(e.apply(null,f));else if("object"===i)for(var t in f)n.call(f,t)&&f[t]&&r.push(t)}}return r.join(" ")}var n={}.hasOwnProperty;"undefined"!=typeof module&&module.exports?module.exports=e:"function"==typeof define&&"object"==typeof define.amd&&define.amd?define("classnames",[],function(){return e}):window.classNames=e}(); },{}]},{},[1])(1) });
examples/Portal.js
BespokeInsights/react-overlays
import React from 'react'; import Button from 'react-bootstrap/lib/Button'; import Portal from 'react-overlays/Portal'; class PortalExample extends React.Component { constructor(...args){ super(...args); this.state = { show: false }; this.show = ()=> this.setState({ show: true }); } render() { let child = ( <span>But I actually render here!</span> ); return ( <div className='portal-example'> <Button bsStyle='primary' onClick={this.show}> Render Child </Button> <div className='panel panel-default'> <div className='panel-body'> <span>It looks like I will render here.</span> <Portal container={()=> this.refs.container}> { this.state.show && child } </Portal> </div> </div> <div className='panel panel-default'> <div ref='container' className='panel-body'/> </div> </div> ); } } export default PortalExample;
mobx-src/components/Login.js
xiedidan/smart-territory-demo
import React from 'react' import {observer} from 'mobx-react' import _ from 'lodash' import * as THREE from 'three' import {Form, Input, Icon, Checkbox, Button, Row, Col} from 'antd' import constants from '../utilities/constants' const FormItem = Form.Item @observer class Login extends React.Component { constructor() { super() // member function this.hasErrors = this.hasErrors.bind(this) this.submitHandler = this.submitHandler.bind(this) this.render = this.render.bind(this) } // lifecycle componentDidMount() { // To disabled submit button at the beginning. this.props.form.validateFields() } hasErrors(fieldsError) { return Object.keys(fieldsError).some(field => fieldsError[field]) } // helper submitHandler(e) { e.preventDefault() this.props.form.validateFields((err, values) => { if (!err) { this.props.store.login(values["username"], values["password"]) } }) } render() { const { getFieldDecorator, getFieldsError, getFieldError, isFieldTouched } = this.props.form // Only show error after a field is touched. const usernameError = isFieldTouched('username') && getFieldError('username') const passwordError = isFieldTouched('password') && getFieldError('password') return <div className="login-container"> <div className="login-logo" /> <h3 className="login-title">电子航道图应用系统</h3> <Form onSubmit={this.submitHandler} className="login-form"> <FormItem validateStatus={usernameError ? 'error' : ''} help={usernameError || ''} > { getFieldDecorator('username', { rules: [{ required: true, message: '输入用户名' }] }) ( <Input prefix={<Icon type="user" style={{ fontsize: 13 }} />} placeholder="用户名" /> ) } </FormItem> <FormItem validateStatus={passwordError ? 'error' : ''} help={passwordError || ''} > { getFieldDecorator('password', { rules: [{ required: true, message: '输入密码' }] }) ( <Input type="password" prefix={<Icon type="lock" style={{ fontsize: 13}} />} placeholder="密码" /> ) } </FormItem> <FormItem> { getFieldDecorator('remember', { valuePropName: 'checked', initialValue: true }) ( <Checkbox>保持登录</Checkbox> ) } <a className="login-form-forgot" href="">忘记密码</a> <Button type="primary" htmlType="submit" className="login-form-button" disabled={this.hasErrors(getFieldsError())}>登录</Button> </FormItem> </Form> </div> } } const WrappedLoginForm = Form.create()(Login) export default WrappedLoginForm
examples/async/index.js
CuthbertJungle/redux
import 'babel-core/polyfill'; import React from 'react'; import Root from './containers/Root'; React.render( <Root />, document.getElementById('root') );
src/server.js
shalomeir/snippod-starter-demo-app-front
import Express from 'express'; import React from 'react'; import ReactDOM from 'react-dom/server'; import config from './config'; import favicon from 'serve-favicon'; import compression from 'compression'; import httpProxy from 'http-proxy'; import path from 'path'; import createStore from './store/create'; import ApiClient from './helpers/ApiClient'; import Html from './helpers/Html'; import PrettyError from 'pretty-error'; import http from 'http'; import SocketIo from 'socket.io'; import createHistory from 'history/lib/createMemoryHistory'; //import { reduxReactRouter, match } from 'redux-router/server'; import { match } from 'react-router'; import { ReduxAsyncConnect, loadOnServer } from 'redux-async-connect'; import { Provider } from 'react-redux'; import { IntlProvider } from 'react-intl'; import * as i18n from './i18n'; import qs from 'query-string'; import getRoutes from './routes'; //import getStatusFromRoutes from './helpers/getStatusFromRoutes'; import './utils/supportIntl'; import Root from './Root'; const pretty = new PrettyError(); const app = new Express(); const server = new http.Server(app); const proxy = httpProxy.createProxyServer({ target: 'http://' + config.apiHost + ':' + config.apiPort, ws: true }); app.use(compression()); app.use(favicon(path.join(__dirname, '..', 'static', 'favicon.ico'))); app.use(Express.static(path.join(__dirname, '..', 'static'))); // Proxy to API server app.use('/api', (req, res) => { proxy.web(req, res); }); // added the error handling to avoid https://github.com/nodejitsu/node-http-proxy/issues/527 proxy.on('error', (error, req, res) => { let json; if (error.code !== 'ECONNRESET') { console.error('proxy error', error); } if (!res.headersSent) { res.writeHead(500, { 'content-type': 'application/json' }); } json = { error: 'proxy_error', reason: error.message }; res.end(JSON.stringify(json)); }); app.use((req, res) => { if (__DEVELOPMENT__) { // Do not cache webpack stats: the script file would change since // hot module replacement is enabled in the development env webpackIsomorphicTools.refresh(); } const client = new ApiClient(req); const history = createHistory(); const store = createStore(history, client); function hydrateOnClient() { res.send('<!doctype html>\n' + ReactDOM.renderToString(<Html assets={webpackIsomorphicTools.assets()} store={store}/>)); } if (__DISABLE_SSR__) { hydrateOnClient(); return; } match({ history, routes: getRoutes(store), location: req.originalUrl }, (error, redirectLocation, renderProps) => { if (redirectLocation) { res.redirect(redirectLocation.pathname + redirectLocation.search); } else if (error) { console.error('ROUTER ERROR:', pretty.render(error)); res.status(500); hydrateOnClient(); } else if (renderProps) { loadOnServer(renderProps, store, { client }).then(() => { const intlData = { lang: store.getState().application.lang, messages: i18n[store.getState().application.lang] }; const component = ( <Provider store={store} key="provider"> <IntlProvider key="intl" {...intlData}> <ReduxAsyncConnect {...renderProps} /> </IntlProvider> </Provider> ); res.status(200); global.navigator = { userAgent: req.headers['user-agent'] }; res.send('<!doctype html>\n' + ReactDOM.renderToString(<Html assets={webpackIsomorphicTools.assets()} component={component} store={store}/>)); }); } else { res.status(404).send('Not found'); } }); }); if (config.port) { if (config.isProduction) { const io = new SocketIo(server); io.path('/api/ws'); } server.listen(config.port, (err) => { if (err) { console.error(err); } console.info('----\n==> ✅ %s is running, talking to API server on %s.', config.app.title, config.apiPort); console.info('==> 💻 Open http://%s:%s in a browser to view the app.', config.host, config.port); }); } else { console.error('==> ERROR: No PORT environment variable has been specified'); }
src/index.js
nnecec/anteact
/* eslint-disable import/default */ import React from 'react'; import {render} from 'react-dom'; import { Provider } from 'react-redux'; import { Router, browserHistory } from 'react-router'; import routes from './routes'; import configureStore from './store/configureStore'; require('./favicon.ico'); // Tell webpack to load favicon.ico import './styles/index.less'; // Yep, that's right. You can import SASS/CSS files too! Webpack will run the associated loader and plug this into the page. import { syncHistoryWithStore } from 'react-router-redux'; const store = configureStore(); // Create an enhanced history that syncs navigation events with the store const history = syncHistoryWithStore(browserHistory, store); render( <Provider store={store}> <Router history={history} routes={routes} /> </Provider>, document.getElementById('root') );
examples/auth-with-shared-root/components/PageOne.js
stshort/react-router
import React from 'react' const PageOne = React.createClass({ render() { return <h2>Page One!</h2> } }) module.exports = PageOne
frontend/app_v2/src/common/icons/About.js
First-Peoples-Cultural-Council/fv-web-ui
import React from 'react' import PropTypes from 'prop-types' /** * @summary About * @component * * @param {object} props * * @returns {node} jsx markup */ function About({ styling }) { return ( <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" className={styling}> <circle cx={50.00006} cy={27.55846} r={19.96977} transform="rotate(-67.5 50 27.558)" /> <path d="M5.009 88.757a3.387 3.387 0 003.36 3.654H91.63a3.388 3.388 0 003.361-3.654c-1.36-19.25-13.848-34.307-44.99-34.307S6.37 69.506 5.008 88.757z" /> </svg> ) } // PROPTYPES const { string } = PropTypes About.propTypes = { styling: string, } export default About
ajax/libs/onsen/1.2.2/js/onsenui.min.js
sufuf3/cdnjs
/*! onsenui - v1.2.2 - 2015-02-26 */ function FastClick(layer){"use strict";function bind(method,context){return function(){return method.apply(context,arguments)}}var oldOnClick;this.trackingClick=!1,this.trackingClickStart=0,this.targetElement=null,this.touchStartX=0,this.touchStartY=0,this.lastTouchIdentifier=0,this.touchBoundary=10,this.layer=layer,FastClick.notNeeded(layer)||(deviceIsAndroid&&(layer.addEventListener("mouseover",bind(this.onMouse,this),!0),layer.addEventListener("mousedown",bind(this.onMouse,this),!0),layer.addEventListener("mouseup",bind(this.onMouse,this),!0)),layer.addEventListener("click",bind(this.onClick,this),!0),layer.addEventListener("touchstart",bind(this.onTouchStart,this),!1),layer.addEventListener("touchmove",bind(this.onTouchMove,this),!1),layer.addEventListener("touchend",bind(this.onTouchEnd,this),!1),layer.addEventListener("touchcancel",bind(this.onTouchCancel,this),!1),Event.prototype.stopImmediatePropagation||(layer.removeEventListener=function(type,callback,capture){var rmv=Node.prototype.removeEventListener;"click"===type?rmv.call(layer,type,callback.hijacked||callback,capture):rmv.call(layer,type,callback,capture)},layer.addEventListener=function(type,callback,capture){var adv=Node.prototype.addEventListener;"click"===type?adv.call(layer,type,callback.hijacked||(callback.hijacked=function(event){event.propagationStopped||callback(event)}),capture):adv.call(layer,type,callback,capture)}),"function"==typeof layer.onclick&&(oldOnClick=layer.onclick,layer.addEventListener("click",function(event){oldOnClick(event)},!1),layer.onclick=null))}!function(){var initializing=!1,fnTest=/xyz/.test(function(){})?/\b_super\b/:/.*/;this.Class=function(){},Class.extend=function(prop){function Class(){!initializing&&this.init&&this.init.apply(this,arguments)}var _super=this.prototype;initializing=!0;var prototype=new this;initializing=!1;for(var name in prop)prototype[name]="function"==typeof prop[name]&&"function"==typeof _super[name]&&fnTest.test(prop[name])?function(name,fn){return function(){var tmp=this._super;this._super=_super[name];var ret=fn.apply(this,arguments);return this._super=tmp,ret}}(name,prop[name]):prop[name];return Class.prototype=prototype,Class.prototype.constructor=Class,Class.extend=arguments.callee,Class}}();var deviceIsAndroid=navigator.userAgent.indexOf("Android")>0,deviceIsIOS=/iP(ad|hone|od)/.test(navigator.userAgent),deviceIsIOS4=deviceIsIOS&&/OS 4_\d(_\d)?/.test(navigator.userAgent),deviceIsIOSWithBadTarget=deviceIsIOS&&/OS ([6-9]|\d{2})_\d/.test(navigator.userAgent);FastClick.prototype.needsClick=function(target){"use strict";switch(target.nodeName.toLowerCase()){case"button":case"select":case"textarea":if(target.disabled)return!0;break;case"input":if(deviceIsIOS&&"file"===target.type||target.disabled)return!0;break;case"label":case"video":return!0}return/\bneedsclick\b/.test(target.className)},FastClick.prototype.needsFocus=function(target){"use strict";switch(target.nodeName.toLowerCase()){case"textarea":return!0;case"select":return!deviceIsAndroid;case"input":switch(target.type){case"button":case"checkbox":case"file":case"image":case"radio":case"submit":return!1}return!target.disabled&&!target.readOnly;default:return/\bneedsfocus\b/.test(target.className)}},FastClick.prototype.sendClick=function(targetElement,event){"use strict";var clickEvent,touch;document.activeElement&&document.activeElement!==targetElement&&document.activeElement.blur(),touch=event.changedTouches[0],clickEvent=document.createEvent("MouseEvents"),clickEvent.initMouseEvent(this.determineEventType(targetElement),!0,!0,window,1,touch.screenX,touch.screenY,touch.clientX,touch.clientY,!1,!1,!1,!1,0,null),clickEvent.forwardedTouchEvent=!0,targetElement.dispatchEvent(clickEvent)},FastClick.prototype.determineEventType=function(targetElement){"use strict";return deviceIsAndroid&&"select"===targetElement.tagName.toLowerCase()?"mousedown":"click"},FastClick.prototype.focus=function(targetElement){"use strict";var length;deviceIsIOS&&targetElement.setSelectionRange&&0!==targetElement.type.indexOf("date")&&"time"!==targetElement.type?(length=targetElement.value.length,targetElement.setSelectionRange(length,length)):targetElement.focus()},FastClick.prototype.updateScrollParent=function(targetElement){"use strict";var scrollParent,parentElement;if(scrollParent=targetElement.fastClickScrollParent,!scrollParent||!scrollParent.contains(targetElement)){parentElement=targetElement;do{if(parentElement.scrollHeight>parentElement.offsetHeight){scrollParent=parentElement,targetElement.fastClickScrollParent=parentElement;break}parentElement=parentElement.parentElement}while(parentElement)}scrollParent&&(scrollParent.fastClickLastScrollTop=scrollParent.scrollTop)},FastClick.prototype.getTargetElementFromEventTarget=function(eventTarget){"use strict";return eventTarget.nodeType===Node.TEXT_NODE?eventTarget.parentNode:eventTarget},FastClick.prototype.onTouchStart=function(event){"use strict";var targetElement,touch,selection;if(event.targetTouches.length>1)return!0;if(targetElement=this.getTargetElementFromEventTarget(event.target),touch=event.targetTouches[0],deviceIsIOS){if(selection=window.getSelection(),selection.rangeCount&&!selection.isCollapsed)return!0;if(!deviceIsIOS4){if(touch.identifier===this.lastTouchIdentifier)return event.preventDefault(),!1;this.lastTouchIdentifier=touch.identifier,this.updateScrollParent(targetElement)}}return this.trackingClick=!0,this.trackingClickStart=event.timeStamp,this.targetElement=targetElement,this.touchStartX=touch.pageX,this.touchStartY=touch.pageY,event.timeStamp-this.lastClickTime<200&&event.preventDefault(),!0},FastClick.prototype.touchHasMoved=function(event){"use strict";var touch=event.changedTouches[0],boundary=this.touchBoundary;return Math.abs(touch.pageX-this.touchStartX)>boundary||Math.abs(touch.pageY-this.touchStartY)>boundary?!0:!1},FastClick.prototype.onTouchMove=function(event){"use strict";return this.trackingClick?((this.targetElement!==this.getTargetElementFromEventTarget(event.target)||this.touchHasMoved(event))&&(this.trackingClick=!1,this.targetElement=null),!0):!0},FastClick.prototype.findControl=function(labelElement){"use strict";return void 0!==labelElement.control?labelElement.control:labelElement.htmlFor?document.getElementById(labelElement.htmlFor):labelElement.querySelector("button, input:not([type=hidden]), keygen, meter, output, progress, select, textarea")},FastClick.prototype.onTouchEnd=function(event){"use strict";var forElement,trackingClickStart,targetTagName,scrollParent,touch,targetElement=this.targetElement;if(!this.trackingClick)return!0;if(event.timeStamp-this.lastClickTime<200)return this.cancelNextClick=!0,!0;if(this.cancelNextClick=!1,this.lastClickTime=event.timeStamp,trackingClickStart=this.trackingClickStart,this.trackingClick=!1,this.trackingClickStart=0,deviceIsIOSWithBadTarget&&(touch=event.changedTouches[0],targetElement=document.elementFromPoint(touch.pageX-window.pageXOffset,touch.pageY-window.pageYOffset)||targetElement,targetElement.fastClickScrollParent=this.targetElement.fastClickScrollParent),targetTagName=targetElement.tagName.toLowerCase(),"label"===targetTagName){if(forElement=this.findControl(targetElement)){if(this.focus(targetElement),deviceIsAndroid)return!1;targetElement=forElement}}else if(this.needsFocus(targetElement))return event.timeStamp-trackingClickStart>100||deviceIsIOS&&window.top!==window&&"input"===targetTagName?(this.targetElement=null,!1):(this.focus(targetElement),this.sendClick(targetElement,event),deviceIsIOS4&&"select"===targetTagName||(this.targetElement=null,event.preventDefault()),!1);return deviceIsIOS&&!deviceIsIOS4&&(scrollParent=targetElement.fastClickScrollParent,scrollParent&&scrollParent.fastClickLastScrollTop!==scrollParent.scrollTop)?!0:(this.needsClick(targetElement)||(event.preventDefault(),this.sendClick(targetElement,event)),!1)},FastClick.prototype.onTouchCancel=function(){"use strict";this.trackingClick=!1,this.targetElement=null},FastClick.prototype.onMouse=function(event){"use strict";return this.targetElement?event.forwardedTouchEvent?!0:event.cancelable?!this.needsClick(this.targetElement)||this.cancelNextClick?(event.stopImmediatePropagation?event.stopImmediatePropagation():event.propagationStopped=!0,event.stopPropagation(),event.preventDefault(),!1):!0:!0:!0},FastClick.prototype.onClick=function(event){"use strict";var permitted;return this.trackingClick?(this.targetElement=null,this.trackingClick=!1,!0):"submit"===event.target.type&&0===event.detail?!0:(permitted=this.onMouse(event),permitted||(this.targetElement=null),permitted)},FastClick.prototype.destroy=function(){"use strict";var layer=this.layer;deviceIsAndroid&&(layer.removeEventListener("mouseover",this.onMouse,!0),layer.removeEventListener("mousedown",this.onMouse,!0),layer.removeEventListener("mouseup",this.onMouse,!0)),layer.removeEventListener("click",this.onClick,!0),layer.removeEventListener("touchstart",this.onTouchStart,!1),layer.removeEventListener("touchmove",this.onTouchMove,!1),layer.removeEventListener("touchend",this.onTouchEnd,!1),layer.removeEventListener("touchcancel",this.onTouchCancel,!1)},FastClick.notNeeded=function(layer){"use strict";var metaViewport,chromeVersion;if("undefined"==typeof window.ontouchstart)return!0;if(chromeVersion=+(/Chrome\/([0-9]+)/.exec(navigator.userAgent)||[,0])[1]){if(!deviceIsAndroid)return!0;if(metaViewport=document.querySelector("meta[name=viewport]")){if(-1!==metaViewport.content.indexOf("user-scalable=no"))return!0;if(chromeVersion>31&&window.innerWidth<=window.screen.width)return!0}}return"none"===layer.style.msTouchAction?!0:!1},FastClick.attach=function(layer){"use strict";return new FastClick(layer)},"undefined"!=typeof define&&define.amd?define(function(){"use strict";return FastClick}):"undefined"!=typeof module&&module.exports?(module.exports=FastClick.attach,module.exports.FastClick=FastClick):window.FastClick=FastClick,function(window,undefined){"use strict";function setup(){Hammer.READY||(Event.determineEventTypes(),Utils.each(Hammer.gestures,function(gesture){Detection.register(gesture)}),Event.onTouch(Hammer.DOCUMENT,EVENT_MOVE,Detection.detect),Event.onTouch(Hammer.DOCUMENT,EVENT_END,Detection.detect),Hammer.READY=!0)}var Hammer=function Hammer(element,options){return new Hammer.Instance(element,options||{})};Hammer.VERSION="1.1.3",Hammer.defaults={behavior:{userSelect:"none",touchAction:"pan-y",touchCallout:"none",contentZooming:"none",userDrag:"none",tapHighlightColor:"rgba(0,0,0,0)"}},Hammer.DOCUMENT=document,Hammer.HAS_POINTEREVENTS=navigator.pointerEnabled||navigator.msPointerEnabled,Hammer.HAS_TOUCHEVENTS="ontouchstart"in window,Hammer.IS_MOBILE=/mobile|tablet|ip(ad|hone|od)|android|silk/i.test(navigator.userAgent),Hammer.NO_MOUSEEVENTS=Hammer.HAS_TOUCHEVENTS&&Hammer.IS_MOBILE||Hammer.HAS_POINTEREVENTS,Hammer.CALCULATE_INTERVAL=25;var EVENT_TYPES={},DIRECTION_DOWN=Hammer.DIRECTION_DOWN="down",DIRECTION_LEFT=Hammer.DIRECTION_LEFT="left",DIRECTION_UP=Hammer.DIRECTION_UP="up",DIRECTION_RIGHT=Hammer.DIRECTION_RIGHT="right",POINTER_MOUSE=Hammer.POINTER_MOUSE="mouse",POINTER_TOUCH=Hammer.POINTER_TOUCH="touch",POINTER_PEN=Hammer.POINTER_PEN="pen",EVENT_START=Hammer.EVENT_START="start",EVENT_MOVE=Hammer.EVENT_MOVE="move",EVENT_END=Hammer.EVENT_END="end",EVENT_RELEASE=Hammer.EVENT_RELEASE="release",EVENT_TOUCH=Hammer.EVENT_TOUCH="touch";Hammer.READY=!1,Hammer.plugins=Hammer.plugins||{},Hammer.gestures=Hammer.gestures||{};var Utils=Hammer.utils={extend:function(dest,src,merge){for(var key in src)!src.hasOwnProperty(key)||dest[key]!==undefined&&merge||(dest[key]=src[key]);return dest},on:function(element,type,handler){element.addEventListener(type,handler,!1)},off:function(element,type,handler){element.removeEventListener(type,handler,!1)},each:function(obj,iterator,context){var i,len;if("forEach"in obj)obj.forEach(iterator,context);else if(obj.length!==undefined){for(i=0,len=obj.length;len>i;i++)if(iterator.call(context,obj[i],i,obj)===!1)return}else for(i in obj)if(obj.hasOwnProperty(i)&&iterator.call(context,obj[i],i,obj)===!1)return},inStr:function(src,find){return src.indexOf(find)>-1},inArray:function(src,find){if(src.indexOf){var index=src.indexOf(find);return-1===index?!1:index}for(var i=0,len=src.length;len>i;i++)if(src[i]===find)return i;return!1},toArray:function(obj){return Array.prototype.slice.call(obj,0)},hasParent:function(node,parent){for(;node;){if(node==parent)return!0;node=node.parentNode}return!1},getCenter:function(touches){var pageX=[],pageY=[],clientX=[],clientY=[],min=Math.min,max=Math.max;return 1===touches.length?{pageX:touches[0].pageX,pageY:touches[0].pageY,clientX:touches[0].clientX,clientY:touches[0].clientY}:(Utils.each(touches,function(touch){pageX.push(touch.pageX),pageY.push(touch.pageY),clientX.push(touch.clientX),clientY.push(touch.clientY)}),{pageX:(min.apply(Math,pageX)+max.apply(Math,pageX))/2,pageY:(min.apply(Math,pageY)+max.apply(Math,pageY))/2,clientX:(min.apply(Math,clientX)+max.apply(Math,clientX))/2,clientY:(min.apply(Math,clientY)+max.apply(Math,clientY))/2})},getVelocity:function(deltaTime,deltaX,deltaY){return{x:Math.abs(deltaX/deltaTime)||0,y:Math.abs(deltaY/deltaTime)||0}},getAngle:function(touch1,touch2){var x=touch2.clientX-touch1.clientX,y=touch2.clientY-touch1.clientY;return 180*Math.atan2(y,x)/Math.PI},getDirection:function(touch1,touch2){var x=Math.abs(touch1.clientX-touch2.clientX),y=Math.abs(touch1.clientY-touch2.clientY);return x>=y?touch1.clientX-touch2.clientX>0?DIRECTION_LEFT:DIRECTION_RIGHT:touch1.clientY-touch2.clientY>0?DIRECTION_UP:DIRECTION_DOWN},getDistance:function(touch1,touch2){var x=touch2.clientX-touch1.clientX,y=touch2.clientY-touch1.clientY;return Math.sqrt(x*x+y*y)},getScale:function(start,end){return start.length>=2&&end.length>=2?this.getDistance(end[0],end[1])/this.getDistance(start[0],start[1]):1},getRotation:function(start,end){return start.length>=2&&end.length>=2?this.getAngle(end[1],end[0])-this.getAngle(start[1],start[0]):0},isVertical:function(direction){return direction==DIRECTION_UP||direction==DIRECTION_DOWN},setPrefixedCss:function(element,prop,value,toggle){var prefixes=["","Webkit","Moz","O","ms"];prop=Utils.toCamelCase(prop);for(var i=0;i<prefixes.length;i++){var p=prop;if(prefixes[i]&&(p=prefixes[i]+p.slice(0,1).toUpperCase()+p.slice(1)),p in element.style){element.style[p]=(null==toggle||toggle)&&value||"";break}}},toggleBehavior:function(element,props,toggle){if(props&&element&&element.style){Utils.each(props,function(value,prop){Utils.setPrefixedCss(element,prop,value,toggle)});var falseFn=toggle&&function(){return!1};"none"==props.userSelect&&(element.onselectstart=falseFn),"none"==props.userDrag&&(element.ondragstart=falseFn)}},toCamelCase:function(str){return str.replace(/[_-]([a-z])/g,function(s){return s[1].toUpperCase()})}},Event=Hammer.event={preventMouseEvents:!1,started:!1,shouldDetect:!1,on:function(element,type,handler,hook){var types=type.split(" ");Utils.each(types,function(type){Utils.on(element,type,handler),hook&&hook(type)})},off:function(element,type,handler,hook){var types=type.split(" ");Utils.each(types,function(type){Utils.off(element,type,handler),hook&&hook(type)})},onTouch:function(element,eventType,handler){var self=this,onTouchHandler=function(ev){var triggerType,srcType=ev.type.toLowerCase(),isPointer=Hammer.HAS_POINTEREVENTS,isMouse=Utils.inStr(srcType,"mouse");isMouse&&self.preventMouseEvents||(isMouse&&eventType==EVENT_START&&0===ev.button?(self.preventMouseEvents=!1,self.shouldDetect=!0):isPointer&&eventType==EVENT_START?self.shouldDetect=1===ev.buttons||PointerEvent.matchType(POINTER_TOUCH,ev):isMouse||eventType!=EVENT_START||(self.preventMouseEvents=!0,self.shouldDetect=!0),isPointer&&eventType!=EVENT_END&&PointerEvent.updatePointer(eventType,ev),self.shouldDetect&&(triggerType=self.doDetect.call(self,ev,eventType,element,handler)),triggerType==EVENT_END&&(self.preventMouseEvents=!1,self.shouldDetect=!1,PointerEvent.reset()),isPointer&&eventType==EVENT_END&&PointerEvent.updatePointer(eventType,ev))};return this.on(element,EVENT_TYPES[eventType],onTouchHandler),onTouchHandler},doDetect:function(ev,eventType,element,handler){var touchList=this.getTouchList(ev,eventType),touchListLength=touchList.length,triggerType=eventType,triggerChange=touchList.trigger,changedLength=touchListLength;eventType==EVENT_START?triggerChange=EVENT_TOUCH:eventType==EVENT_END&&(triggerChange=EVENT_RELEASE,changedLength=touchList.length-(ev.changedTouches?ev.changedTouches.length:1)),changedLength>0&&this.started&&(triggerType=EVENT_MOVE),this.started=!0;var evData=this.collectEventData(element,triggerType,touchList,ev);return eventType!=EVENT_END&&handler.call(Detection,evData),triggerChange&&(evData.changedLength=changedLength,evData.eventType=triggerChange,handler.call(Detection,evData),evData.eventType=triggerType,delete evData.changedLength),triggerType==EVENT_END&&(handler.call(Detection,evData),this.started=!1),triggerType},determineEventTypes:function(){var types;return types=Hammer.HAS_POINTEREVENTS?window.PointerEvent?["pointerdown","pointermove","pointerup pointercancel lostpointercapture"]:["MSPointerDown","MSPointerMove","MSPointerUp MSPointerCancel MSLostPointerCapture"]:Hammer.NO_MOUSEEVENTS?["touchstart","touchmove","touchend touchcancel"]:["touchstart mousedown","touchmove mousemove","touchend touchcancel mouseup"],EVENT_TYPES[EVENT_START]=types[0],EVENT_TYPES[EVENT_MOVE]=types[1],EVENT_TYPES[EVENT_END]=types[2],EVENT_TYPES},getTouchList:function(ev,eventType){if(Hammer.HAS_POINTEREVENTS)return PointerEvent.getTouchList();if(ev.touches){if(eventType==EVENT_MOVE)return ev.touches;var identifiers=[],concat=[].concat(Utils.toArray(ev.touches),Utils.toArray(ev.changedTouches)),touchList=[];return Utils.each(concat,function(touch){Utils.inArray(identifiers,touch.identifier)===!1&&touchList.push(touch),identifiers.push(touch.identifier)}),touchList}return ev.identifier=1,[ev]},collectEventData:function(element,eventType,touches,ev){var pointerType=POINTER_TOUCH;return Utils.inStr(ev.type,"mouse")||PointerEvent.matchType(POINTER_MOUSE,ev)?pointerType=POINTER_MOUSE:PointerEvent.matchType(POINTER_PEN,ev)&&(pointerType=POINTER_PEN),{center:Utils.getCenter(touches),timeStamp:Date.now(),target:ev.target,touches:touches,eventType:eventType,pointerType:pointerType,srcEvent:ev,preventDefault:function(){var srcEvent=this.srcEvent;srcEvent.preventManipulation&&srcEvent.preventManipulation(),srcEvent.preventDefault&&srcEvent.preventDefault()},stopPropagation:function(){this.srcEvent.stopPropagation()},stopDetect:function(){return Detection.stopDetect()}}}},PointerEvent=Hammer.PointerEvent={pointers:{},getTouchList:function(){var touchlist=[];return Utils.each(this.pointers,function(pointer){touchlist.push(pointer)}),touchlist},updatePointer:function(eventType,pointerEvent){eventType==EVENT_END||eventType!=EVENT_END&&1!==pointerEvent.buttons?delete this.pointers[pointerEvent.pointerId]:(pointerEvent.identifier=pointerEvent.pointerId,this.pointers[pointerEvent.pointerId]=pointerEvent)},matchType:function(pointerType,ev){if(!ev.pointerType)return!1;var pt=ev.pointerType,types={};return types[POINTER_MOUSE]=pt===(ev.MSPOINTER_TYPE_MOUSE||POINTER_MOUSE),types[POINTER_TOUCH]=pt===(ev.MSPOINTER_TYPE_TOUCH||POINTER_TOUCH),types[POINTER_PEN]=pt===(ev.MSPOINTER_TYPE_PEN||POINTER_PEN),types[pointerType]},reset:function(){this.pointers={}}},Detection=Hammer.detection={gestures:[],current:null,previous:null,stopped:!1,startDetect:function(inst,eventData){this.current||(this.stopped=!1,this.current={inst:inst,startEvent:Utils.extend({},eventData),lastEvent:!1,lastCalcEvent:!1,futureCalcEvent:!1,lastCalcData:{},name:""},this.detect(eventData))},detect:function(eventData){if(this.current&&!this.stopped){eventData=this.extendEventData(eventData);var inst=this.current.inst,instOptions=inst.options;return Utils.each(this.gestures,function(gesture){!this.stopped&&inst.enabled&&instOptions[gesture.name]&&gesture.handler.call(gesture,eventData,inst)},this),this.current&&(this.current.lastEvent=eventData),eventData.eventType==EVENT_END&&this.stopDetect(),eventData}},stopDetect:function(){this.previous=Utils.extend({},this.current),this.current=null,this.stopped=!0},getCalculatedData:function(ev,center,deltaTime,deltaX,deltaY){var cur=this.current,recalc=!1,calcEv=cur.lastCalcEvent,calcData=cur.lastCalcData;calcEv&&ev.timeStamp-calcEv.timeStamp>Hammer.CALCULATE_INTERVAL&&(center=calcEv.center,deltaTime=ev.timeStamp-calcEv.timeStamp,deltaX=ev.center.clientX-calcEv.center.clientX,deltaY=ev.center.clientY-calcEv.center.clientY,recalc=!0),(ev.eventType==EVENT_TOUCH||ev.eventType==EVENT_RELEASE)&&(cur.futureCalcEvent=ev),(!cur.lastCalcEvent||recalc)&&(calcData.velocity=Utils.getVelocity(deltaTime,deltaX,deltaY),calcData.angle=Utils.getAngle(center,ev.center),calcData.direction=Utils.getDirection(center,ev.center),cur.lastCalcEvent=cur.futureCalcEvent||ev,cur.futureCalcEvent=ev),ev.velocityX=calcData.velocity.x,ev.velocityY=calcData.velocity.y,ev.interimAngle=calcData.angle,ev.interimDirection=calcData.direction},extendEventData:function(ev){var cur=this.current,startEv=cur.startEvent,lastEv=cur.lastEvent||startEv;(ev.eventType==EVENT_TOUCH||ev.eventType==EVENT_RELEASE)&&(startEv.touches=[],Utils.each(ev.touches,function(touch){startEv.touches.push({clientX:touch.clientX,clientY:touch.clientY})}));var deltaTime=ev.timeStamp-startEv.timeStamp,deltaX=ev.center.clientX-startEv.center.clientX,deltaY=ev.center.clientY-startEv.center.clientY;return this.getCalculatedData(ev,lastEv.center,deltaTime,deltaX,deltaY),Utils.extend(ev,{startEvent:startEv,deltaTime:deltaTime,deltaX:deltaX,deltaY:deltaY,distance:Utils.getDistance(startEv.center,ev.center),angle:Utils.getAngle(startEv.center,ev.center),direction:Utils.getDirection(startEv.center,ev.center),scale:Utils.getScale(startEv.touches,ev.touches),rotation:Utils.getRotation(startEv.touches,ev.touches)}),ev},register:function(gesture){var options=gesture.defaults||{};return options[gesture.name]===undefined&&(options[gesture.name]=!0),Utils.extend(Hammer.defaults,options,!0),gesture.index=gesture.index||1e3,this.gestures.push(gesture),this.gestures.sort(function(a,b){return a.index<b.index?-1:a.index>b.index?1:0}),this.gestures}};Hammer.Instance=function(element,options){var self=this;setup(),this.element=element,this.enabled=!0,Utils.each(options,function(value,name){delete options[name],options[Utils.toCamelCase(name)]=value}),this.options=Utils.extend(Utils.extend({},Hammer.defaults),options||{}),this.options.behavior&&Utils.toggleBehavior(this.element,this.options.behavior,!0),this.eventStartHandler=Event.onTouch(element,EVENT_START,function(ev){self.enabled&&ev.eventType==EVENT_START?Detection.startDetect(self,ev):ev.eventType==EVENT_TOUCH&&Detection.detect(ev)}),this.eventHandlers=[]},Hammer.Instance.prototype={on:function(gestures,handler){var self=this;return Event.on(self.element,gestures,handler,function(type){self.eventHandlers.push({gesture:type,handler:handler})}),self},off:function(gestures,handler){var self=this;return Event.off(self.element,gestures,handler,function(type){var index=Utils.inArray({gesture:type,handler:handler});index!==!1&&self.eventHandlers.splice(index,1)}),self},trigger:function(gesture,eventData){eventData||(eventData={});var event=Hammer.DOCUMENT.createEvent("Event");event.initEvent(gesture,!0,!0),event.gesture=eventData;var element=this.element;return Utils.hasParent(eventData.target,element)&&(element=eventData.target),element.dispatchEvent(event),this},enable:function(state){return this.enabled=state,this},dispose:function(){var i,eh;for(Utils.toggleBehavior(this.element,this.options.behavior,!1),i=-1;eh=this.eventHandlers[++i];)Utils.off(this.element,eh.gesture,eh.handler);return this.eventHandlers=[],Event.off(this.element,EVENT_TYPES[EVENT_START],this.eventStartHandler),null}},function(name){function dragGesture(ev,inst){var cur=Detection.current;if(!(inst.options.dragMaxTouches>0&&ev.touches.length>inst.options.dragMaxTouches))switch(ev.eventType){case EVENT_START:triggered=!1;break;case EVENT_MOVE:if(ev.distance<inst.options.dragMinDistance&&cur.name!=name)return;var startCenter=cur.startEvent.center;if(cur.name!=name&&(cur.name=name,inst.options.dragDistanceCorrection&&ev.distance>0)){var factor=Math.abs(inst.options.dragMinDistance/ev.distance);startCenter.pageX+=ev.deltaX*factor,startCenter.pageY+=ev.deltaY*factor,startCenter.clientX+=ev.deltaX*factor,startCenter.clientY+=ev.deltaY*factor,ev=Detection.extendEventData(ev)}(cur.lastEvent.dragLockToAxis||inst.options.dragLockToAxis&&inst.options.dragLockMinDistance<=ev.distance)&&(ev.dragLockToAxis=!0);var lastDirection=cur.lastEvent.direction;ev.dragLockToAxis&&lastDirection!==ev.direction&&(ev.direction=Utils.isVertical(lastDirection)?ev.deltaY<0?DIRECTION_UP:DIRECTION_DOWN:ev.deltaX<0?DIRECTION_LEFT:DIRECTION_RIGHT),triggered||(inst.trigger(name+"start",ev),triggered=!0),inst.trigger(name,ev),inst.trigger(name+ev.direction,ev);var isVertical=Utils.isVertical(ev.direction);(inst.options.dragBlockVertical&&isVertical||inst.options.dragBlockHorizontal&&!isVertical)&&ev.preventDefault();break;case EVENT_RELEASE:triggered&&ev.changedLength<=inst.options.dragMaxTouches&&(inst.trigger(name+"end",ev),triggered=!1);break;case EVENT_END:triggered=!1}}var triggered=!1;Hammer.gestures.Drag={name:name,index:50,handler:dragGesture,defaults:{dragMinDistance:10,dragDistanceCorrection:!0,dragMaxTouches:1,dragBlockHorizontal:!1,dragBlockVertical:!1,dragLockToAxis:!1,dragLockMinDistance:25}}}("drag"),Hammer.gestures.Gesture={name:"gesture",index:1337,handler:function(ev,inst){inst.trigger(this.name,ev)}},function(name){function holdGesture(ev,inst){var options=inst.options,current=Detection.current;switch(ev.eventType){case EVENT_START:clearTimeout(timer),current.name=name,timer=setTimeout(function(){current&&current.name==name&&inst.trigger(name,ev)},options.holdTimeout);break;case EVENT_MOVE:ev.distance>options.holdThreshold&&clearTimeout(timer);break;case EVENT_RELEASE:clearTimeout(timer)}}var timer;Hammer.gestures.Hold={name:name,index:10,defaults:{holdTimeout:500,holdThreshold:2},handler:holdGesture}}("hold"),Hammer.gestures.Release={name:"release",index:1/0,handler:function(ev,inst){ev.eventType==EVENT_RELEASE&&inst.trigger(this.name,ev)}},Hammer.gestures.Swipe={name:"swipe",index:40,defaults:{swipeMinTouches:1,swipeMaxTouches:1,swipeVelocityX:.6,swipeVelocityY:.6},handler:function(ev,inst){if(ev.eventType==EVENT_RELEASE){var touches=ev.touches.length,options=inst.options;if(touches<options.swipeMinTouches||touches>options.swipeMaxTouches)return;(ev.velocityX>options.swipeVelocityX||ev.velocityY>options.swipeVelocityY)&&(inst.trigger(this.name,ev),inst.trigger(this.name+ev.direction,ev))}}},function(name){function tapGesture(ev,inst){var sincePrev,didDoubleTap,options=inst.options,current=Detection.current,prev=Detection.previous;switch(ev.eventType){case EVENT_START:hasMoved=!1;break;case EVENT_MOVE:hasMoved=hasMoved||ev.distance>options.tapMaxDistance;break;case EVENT_END:!Utils.inStr(ev.srcEvent.type,"cancel")&&ev.deltaTime<options.tapMaxTime&&!hasMoved&&(sincePrev=prev&&prev.lastEvent&&ev.timeStamp-prev.lastEvent.timeStamp,didDoubleTap=!1,prev&&prev.name==name&&sincePrev&&sincePrev<options.doubleTapInterval&&ev.distance<options.doubleTapDistance&&(inst.trigger("doubletap",ev),didDoubleTap=!0),(!didDoubleTap||options.tapAlways)&&(current.name=name,inst.trigger(current.name,ev)))}}var hasMoved=!1;Hammer.gestures.Tap={name:name,index:100,handler:tapGesture,defaults:{tapMaxTime:250,tapMaxDistance:10,tapAlways:!0,doubleTapDistance:20,doubleTapInterval:300}}}("tap"),Hammer.gestures.Touch={name:"touch",index:-1/0,defaults:{preventDefault:!1,preventMouse:!1},handler:function(ev,inst){return inst.options.preventMouse&&ev.pointerType==POINTER_MOUSE?(ev.stopDetect(),void 0):(inst.options.preventDefault&&ev.preventDefault(),ev.eventType==EVENT_TOUCH&&inst.trigger("touch",ev),void 0)}},function(name){function transformGesture(ev,inst){switch(ev.eventType){case EVENT_START:triggered=!1;break;case EVENT_MOVE:if(ev.touches.length<2)return;var scaleThreshold=Math.abs(1-ev.scale),rotationThreshold=Math.abs(ev.rotation);if(scaleThreshold<inst.options.transformMinScale&&rotationThreshold<inst.options.transformMinRotation)return;Detection.current.name=name,triggered||(inst.trigger(name+"start",ev),triggered=!0),inst.trigger(name,ev),rotationThreshold>inst.options.transformMinRotation&&inst.trigger("rotate",ev),scaleThreshold>inst.options.transformMinScale&&(inst.trigger("pinch",ev),inst.trigger("pinch"+(ev.scale<1?"in":"out"),ev));break;case EVENT_RELEASE:triggered&&ev.changedLength<2&&(inst.trigger(name+"end",ev),triggered=!1)}}var triggered=!1;Hammer.gestures.Transform={name:name,index:45,defaults:{transformMinScale:.01,transformMinRotation:1},handler:transformGesture}}("transform"),"function"==typeof define&&define.amd?define(function(){return Hammer}):"undefined"!=typeof module&&module.exports?module.exports=Hammer:window.Hammer=Hammer}(window);var IScroll=function(window,document,Math){function IScroll(el,options){this.wrapper="string"==typeof el?document.querySelector(el):el,this.scroller=this.wrapper.children[0],this.scrollerStyle=this.scroller.style,this.options={startX:0,startY:0,scrollY:!0,directionLockThreshold:5,momentum:!0,bounce:!0,bounceTime:600,bounceEasing:"",preventDefault:!0,preventDefaultException:{tagName:/^(INPUT|TEXTAREA|BUTTON|SELECT)$/},HWCompositing:!0,useTransition:!0,useTransform:!0};for(var i in options)this.options[i]=options[i];this.translateZ=this.options.HWCompositing&&utils.hasPerspective?" translateZ(0)":"",this.options.useTransition=utils.hasTransition&&this.options.useTransition,this.options.useTransform=utils.hasTransform&&this.options.useTransform,this.options.eventPassthrough=this.options.eventPassthrough===!0?"vertical":this.options.eventPassthrough,this.options.preventDefault=!this.options.eventPassthrough&&this.options.preventDefault,this.options.scrollY="vertical"==this.options.eventPassthrough?!1:this.options.scrollY,this.options.scrollX="horizontal"==this.options.eventPassthrough?!1:this.options.scrollX,this.options.freeScroll=this.options.freeScroll&&!this.options.eventPassthrough,this.options.directionLockThreshold=this.options.eventPassthrough?0:this.options.directionLockThreshold,this.options.bounceEasing="string"==typeof this.options.bounceEasing?utils.ease[this.options.bounceEasing]||utils.ease.circular:this.options.bounceEasing,this.options.resizePolling=void 0===this.options.resizePolling?60:this.options.resizePolling,this.options.tap===!0&&(this.options.tap="tap"),this.x=0,this.y=0,this.directionX=0,this.directionY=0,this._events={},this._init(),this.refresh(),this.scrollTo(this.options.startX,this.options.startY),this.enable()}var rAF=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(callback){window.setTimeout(callback,1e3/60)},utils=function(){function _prefixStyle(style){return _vendor===!1?!1:""===_vendor?style:_vendor+style.charAt(0).toUpperCase()+style.substr(1)}var me={},_elementStyle=document.createElement("div").style,_vendor=function(){for(var transform,vendors=["t","webkitT","MozT","msT","OT"],i=0,l=vendors.length;l>i;i++)if(transform=vendors[i]+"ransform",transform in _elementStyle)return vendors[i].substr(0,vendors[i].length-1);return!1}();me.getTime=Date.now||function(){return(new Date).getTime()},me.extend=function(target,obj){for(var i in obj)target[i]=obj[i]},me.addEvent=function(el,type,fn,capture){el.addEventListener(type,fn,!!capture)},me.removeEvent=function(el,type,fn,capture){el.removeEventListener(type,fn,!!capture)},me.momentum=function(current,start,time,lowerMargin,wrapperSize){var destination,duration,distance=current-start,speed=Math.abs(distance)/time,deceleration=6e-4; return destination=current+speed*speed/(2*deceleration)*(0>distance?-1:1),duration=speed/deceleration,lowerMargin>destination?(destination=wrapperSize?lowerMargin-wrapperSize/2.5*(speed/8):lowerMargin,distance=Math.abs(destination-current),duration=distance/speed):destination>0&&(destination=wrapperSize?wrapperSize/2.5*(speed/8):0,distance=Math.abs(current)+destination,duration=distance/speed),{destination:Math.round(destination),duration:duration}};var _transform=_prefixStyle("transform");return me.extend(me,{hasTransform:_transform!==!1,hasPerspective:_prefixStyle("perspective")in _elementStyle,hasTouch:"ontouchstart"in window,hasPointer:navigator.msPointerEnabled,hasTransition:_prefixStyle("transition")in _elementStyle}),me.isAndroidBrowser=/Android/.test(window.navigator.appVersion)&&/Version\/\d/.test(window.navigator.appVersion),me.extend(me.style={},{transform:_transform,transitionTimingFunction:_prefixStyle("transitionTimingFunction"),transitionDuration:_prefixStyle("transitionDuration"),transformOrigin:_prefixStyle("transformOrigin")}),me.hasClass=function(e,c){var re=new RegExp("(^|\\s)"+c+"(\\s|$)");return re.test(e.className)},me.addClass=function(e,c){if(!me.hasClass(e,c)){var newclass=e.className.split(" ");newclass.push(c),e.className=newclass.join(" ")}},me.removeClass=function(e,c){if(me.hasClass(e,c)){var re=new RegExp("(^|\\s)"+c+"(\\s|$)","g");e.className=e.className.replace(re," ")}},me.offset=function(el){for(var left=-el.offsetLeft,top=-el.offsetTop;el=el.offsetParent;)left-=el.offsetLeft,top-=el.offsetTop;return{left:left,top:top}},me.preventDefaultException=function(el,exceptions){for(var i in exceptions)if(exceptions[i].test(el[i]))return!0;return!1},me.extend(me.eventType={},{touchstart:1,touchmove:1,touchend:1,mousedown:2,mousemove:2,mouseup:2,MSPointerDown:3,MSPointerMove:3,MSPointerUp:3}),me.extend(me.ease={},{quadratic:{style:"cubic-bezier(0.25, 0.46, 0.45, 0.94)",fn:function(k){return k*(2-k)}},circular:{style:"cubic-bezier(0.1, 0.57, 0.1, 1)",fn:function(k){return Math.sqrt(1- --k*k)}},back:{style:"cubic-bezier(0.175, 0.885, 0.32, 1.275)",fn:function(k){var b=4;return(k-=1)*k*((b+1)*k+b)+1}},bounce:{style:"",fn:function(k){return(k/=1)<1/2.75?7.5625*k*k:2/2.75>k?7.5625*(k-=1.5/2.75)*k+.75:2.5/2.75>k?7.5625*(k-=2.25/2.75)*k+.9375:7.5625*(k-=2.625/2.75)*k+.984375}},elastic:{style:"",fn:function(k){var f=.22,e=.4;return 0===k?0:1==k?1:e*Math.pow(2,-10*k)*Math.sin(2*(k-f/4)*Math.PI/f)+1}}}),me.tap=function(e,eventName){var ev=document.createEvent("Event");ev.initEvent(eventName,!0,!0),ev.pageX=e.pageX,ev.pageY=e.pageY,e.target.dispatchEvent(ev)},me.click=function(e){var ev,target=e.target;"SELECT"!=target.tagName&&"INPUT"!=target.tagName&&"TEXTAREA"!=target.tagName&&(ev=document.createEvent("MouseEvents"),ev.initMouseEvent("click",!0,!0,e.view,1,target.screenX,target.screenY,target.clientX,target.clientY,e.ctrlKey,e.altKey,e.shiftKey,e.metaKey,0,null),ev._constructed=!0,target.dispatchEvent(ev))},me}();return IScroll.prototype={version:"5.0.6",_init:function(){this._initEvents()},destroy:function(){this._initEvents(!0),this._execEvent("destroy")},_transitionEnd:function(e){e.target==this.scroller&&(this._transitionTime(0),this.resetPosition(this.options.bounceTime)||this._execEvent("scrollEnd"))},_start:function(e){if(!(1!=utils.eventType[e.type]&&0!==e.button||!this.enabled||this.initiated&&utils.eventType[e.type]!==this.initiated)){!this.options.preventDefault||utils.isAndroidBrowser||utils.preventDefaultException(e.target,this.options.preventDefaultException)||e.preventDefault();var pos,point=e.touches?e.touches[0]:e;this.initiated=utils.eventType[e.type],this.moved=!1,this.distX=0,this.distY=0,this.directionX=0,this.directionY=0,this.directionLocked=0,this._transitionTime(),this.isAnimating=!1,this.startTime=utils.getTime(),this.options.useTransition&&this.isInTransition&&(pos=this.getComputedPosition(),this._translate(Math.round(pos.x),Math.round(pos.y)),this._execEvent("scrollEnd"),this.isInTransition=!1),this.startX=this.x,this.startY=this.y,this.absStartX=this.x,this.absStartY=this.y,this.pointX=point.pageX,this.pointY=point.pageY,this._execEvent("beforeScrollStart")}},_move:function(e){if(this.enabled&&utils.eventType[e.type]===this.initiated){this.options.preventDefault&&e.preventDefault();var newX,newY,absDistX,absDistY,point=e.touches?e.touches[0]:e,deltaX=point.pageX-this.pointX,deltaY=point.pageY-this.pointY,timestamp=utils.getTime();if(this.pointX=point.pageX,this.pointY=point.pageY,this.distX+=deltaX,this.distY+=deltaY,absDistX=Math.abs(this.distX),absDistY=Math.abs(this.distY),!(timestamp-this.endTime>300&&10>absDistX&&10>absDistY)){if(this.directionLocked||this.options.freeScroll||(this.directionLocked=absDistX>absDistY+this.options.directionLockThreshold?"h":absDistY>=absDistX+this.options.directionLockThreshold?"v":"n"),"h"==this.directionLocked){if("vertical"==this.options.eventPassthrough)e.preventDefault();else if("horizontal"==this.options.eventPassthrough)return this.initiated=!1,void 0;deltaY=0}else if("v"==this.directionLocked){if("horizontal"==this.options.eventPassthrough)e.preventDefault();else if("vertical"==this.options.eventPassthrough)return this.initiated=!1,void 0;deltaX=0}deltaX=this.hasHorizontalScroll?deltaX:0,deltaY=this.hasVerticalScroll?deltaY:0,newX=this.x+deltaX,newY=this.y+deltaY,(newX>0||newX<this.maxScrollX)&&(newX=this.options.bounce?this.x+deltaX/3:newX>0?0:this.maxScrollX),(newY>0||newY<this.maxScrollY)&&(newY=this.options.bounce?this.y+deltaY/3:newY>0?0:this.maxScrollY),this.directionX=deltaX>0?-1:0>deltaX?1:0,this.directionY=deltaY>0?-1:0>deltaY?1:0,this.moved||this._execEvent("scrollStart"),this.moved=!0,this._translate(newX,newY),timestamp-this.startTime>300&&(this.startTime=timestamp,this.startX=this.x,this.startY=this.y)}}},_end:function(e){if(this.enabled&&utils.eventType[e.type]===this.initiated){this.options.preventDefault&&!utils.preventDefaultException(e.target,this.options.preventDefaultException)&&e.preventDefault();var momentumX,momentumY,duration=(e.changedTouches?e.changedTouches[0]:e,utils.getTime()-this.startTime),newX=Math.round(this.x),newY=Math.round(this.y),distanceX=Math.abs(newX-this.startX),distanceY=Math.abs(newY-this.startY),time=0,easing="";if(this.scrollTo(newX,newY),this.isInTransition=0,this.initiated=0,this.endTime=utils.getTime(),!this.resetPosition(this.options.bounceTime))return this.moved?this._events.flick&&200>duration&&100>distanceX&&100>distanceY?(this._execEvent("flick"),void 0):(this.options.momentum&&300>duration&&(momentumX=this.hasHorizontalScroll?utils.momentum(this.x,this.startX,duration,this.maxScrollX,this.options.bounce?this.wrapperWidth:0):{destination:newX,duration:0},momentumY=this.hasVerticalScroll?utils.momentum(this.y,this.startY,duration,this.maxScrollY,this.options.bounce?this.wrapperHeight:0):{destination:newY,duration:0},newX=momentumX.destination,newY=momentumY.destination,time=Math.max(momentumX.duration,momentumY.duration),this.isInTransition=1),newX!=this.x||newY!=this.y?((newX>0||newX<this.maxScrollX||newY>0||newY<this.maxScrollY)&&(easing=utils.ease.quadratic),this.scrollTo(newX,newY,time,easing),void 0):(this._execEvent("scrollEnd"),void 0)):(this.options.tap&&utils.tap(e,this.options.tap),this.options.click&&utils.click(e),void 0)}},_resize:function(){var that=this;clearTimeout(this.resizeTimeout),this.resizeTimeout=setTimeout(function(){that.refresh()},this.options.resizePolling)},resetPosition:function(time){var x=this.x,y=this.y;return time=time||0,!this.hasHorizontalScroll||this.x>0?x=0:this.x<this.maxScrollX&&(x=this.maxScrollX),!this.hasVerticalScroll||this.y>0?y=0:this.y<this.maxScrollY&&(y=this.maxScrollY),x==this.x&&y==this.y?!1:(this.scrollTo(x,y,time,this.options.bounceEasing),!0)},disable:function(){this.enabled=!1},enable:function(){this.enabled=!0},refresh:function(){this.wrapper.offsetHeight;this.wrapperWidth=this.wrapper.clientWidth,this.wrapperHeight=this.wrapper.clientHeight,this.scrollerWidth=this.scroller.offsetWidth,this.scrollerHeight=this.scroller.offsetHeight,this.maxScrollX=this.wrapperWidth-this.scrollerWidth,this.maxScrollY=this.wrapperHeight-this.scrollerHeight,this.hasHorizontalScroll=this.options.scrollX&&this.maxScrollX<0,this.hasVerticalScroll=this.options.scrollY&&this.maxScrollY<0,this.hasHorizontalScroll||(this.maxScrollX=0,this.scrollerWidth=this.wrapperWidth),this.hasVerticalScroll||(this.maxScrollY=0,this.scrollerHeight=this.wrapperHeight),this.endTime=0,this.directionX=0,this.directionY=0,this.wrapperOffset=utils.offset(this.wrapper),this._execEvent("refresh"),this.resetPosition()},on:function(type,fn){this._events[type]||(this._events[type]=[]),this._events[type].push(fn)},_execEvent:function(type){if(this._events[type]){var i=0,l=this._events[type].length;if(l)for(;l>i;i++)this._events[type][i].call(this)}},scrollBy:function(x,y,time,easing){x=this.x+x,y=this.y+y,time=time||0,this.scrollTo(x,y,time,easing)},scrollTo:function(x,y,time,easing){easing=easing||utils.ease.circular,!time||this.options.useTransition&&easing.style?(this._transitionTimingFunction(easing.style),this._transitionTime(time),this._translate(x,y)):this._animate(x,y,time,easing.fn)},scrollToElement:function(el,time,offsetX,offsetY,easing){if(el=el.nodeType?el:this.scroller.querySelector(el)){var pos=utils.offset(el);pos.left-=this.wrapperOffset.left,pos.top-=this.wrapperOffset.top,offsetX===!0&&(offsetX=Math.round(el.offsetWidth/2-this.wrapper.offsetWidth/2)),offsetY===!0&&(offsetY=Math.round(el.offsetHeight/2-this.wrapper.offsetHeight/2)),pos.left-=offsetX||0,pos.top-=offsetY||0,pos.left=pos.left>0?0:pos.left<this.maxScrollX?this.maxScrollX:pos.left,pos.top=pos.top>0?0:pos.top<this.maxScrollY?this.maxScrollY:pos.top,time=void 0===time||null===time||"auto"===time?Math.max(Math.abs(this.x-pos.left),Math.abs(this.y-pos.top)):time,this.scrollTo(pos.left,pos.top,time,easing)}},_transitionTime:function(time){time=time||0,this.scrollerStyle[utils.style.transitionDuration]=time+"ms"},_transitionTimingFunction:function(easing){this.scrollerStyle[utils.style.transitionTimingFunction]=easing},_translate:function(x,y){this.options.useTransform?this.scrollerStyle[utils.style.transform]="translate("+x+"px,"+y+"px)"+this.translateZ:(x=Math.round(x),y=Math.round(y),this.scrollerStyle.left=x+"px",this.scrollerStyle.top=y+"px"),this.x=x,this.y=y},_initEvents:function(remove){var eventType=remove?utils.removeEvent:utils.addEvent,target=this.options.bindToWrapper?this.wrapper:window;eventType(window,"orientationchange",this),eventType(window,"resize",this),this.options.click&&eventType(this.wrapper,"click",this,!0),this.options.disableMouse||(eventType(this.wrapper,"mousedown",this),eventType(target,"mousemove",this),eventType(target,"mousecancel",this),eventType(target,"mouseup",this)),utils.hasPointer&&!this.options.disablePointer&&(eventType(this.wrapper,"MSPointerDown",this),eventType(target,"MSPointerMove",this),eventType(target,"MSPointerCancel",this),eventType(target,"MSPointerUp",this)),utils.hasTouch&&!this.options.disableTouch&&(eventType(this.wrapper,"touchstart",this),eventType(target,"touchmove",this),eventType(target,"touchcancel",this),eventType(target,"touchend",this)),eventType(this.scroller,"transitionend",this),eventType(this.scroller,"webkitTransitionEnd",this),eventType(this.scroller,"oTransitionEnd",this),eventType(this.scroller,"MSTransitionEnd",this)},getComputedPosition:function(){var x,y,matrix=window.getComputedStyle(this.scroller,null);return this.options.useTransform?(matrix=matrix[utils.style.transform].split(")")[0].split(", "),x=+(matrix[12]||matrix[4]),y=+(matrix[13]||matrix[5])):(x=+matrix.left.replace(/[^-\d]/g,""),y=+matrix.top.replace(/[^-\d]/g,"")),{x:x,y:y}},_animate:function(destX,destY,duration,easingFn){function step(){var newX,newY,easing,now=utils.getTime();return now>=destTime?(that.isAnimating=!1,that._translate(destX,destY),that.resetPosition(that.options.bounceTime)||that._execEvent("scrollEnd"),void 0):(now=(now-startTime)/duration,easing=easingFn(now),newX=(destX-startX)*easing+startX,newY=(destY-startY)*easing+startY,that._translate(newX,newY),that.isAnimating&&rAF(step),void 0)}var that=this,startX=this.x,startY=this.y,startTime=utils.getTime(),destTime=startTime+duration;this.isAnimating=!0,step()},handleEvent:function(e){switch(e.type){case"touchstart":case"MSPointerDown":case"mousedown":this._start(e);break;case"touchmove":case"MSPointerMove":case"mousemove":this._move(e);break;case"touchend":case"MSPointerUp":case"mouseup":case"touchcancel":case"MSPointerCancel":case"mousecancel":this._end(e);break;case"orientationchange":case"resize":this._resize();break;case"transitionend":case"webkitTransitionEnd":case"oTransitionEnd":case"MSTransitionEnd":this._transitionEnd(e);break;case"DOMMouseScroll":case"mousewheel":this._wheel(e);break;case"keydown":this._key(e);break;case"click":e._constructed||(e.preventDefault(),e.stopPropagation())}}},IScroll.ease=utils.ease,IScroll}(window,document,Math),MicroEvent=function(){};MicroEvent.prototype={on:function(event,fct){this._events=this._events||{},this._events[event]=this._events[event]||[],this._events[event].push(fct)},once:function(event,fct){var self=this,wrapper=function(){return self.off(event,wrapper),fct.apply(null,arguments)};this.on(event,wrapper)},off:function(event,fct){this._events=this._events||{},event in this._events!=!1&&this._events[event].splice(this._events[event].indexOf(fct),1)},emit:function(event){if(this._events=this._events||{},event in this._events!=!1)for(var i=0;i<this._events[event].length;i++)this._events[event][i].apply(this,Array.prototype.slice.call(arguments,1))}},MicroEvent.mixin=function(destObject){for(var props=["on","once","off","emit"],i=0;i<props.length;i++)"function"==typeof destObject?destObject.prototype[props[i]]=MicroEvent.prototype[props[i]]:destObject[props[i]]=MicroEvent.prototype[props[i]]},"undefined"!=typeof module&&"exports"in module&&(module.exports=MicroEvent),window.Modernizr=function(window,document,undefined){function setCss(str){mStyle.cssText=str}function is(obj,type){return typeof obj===type}function contains(str,substr){return!!~(""+str).indexOf(substr)}function testProps(props,prefixed){for(var i in props){var prop=props[i];if(!contains(prop,"-")&&mStyle[prop]!==undefined)return"pfx"==prefixed?prop:!0}return!1}function testDOMProps(props,obj,elem){for(var i in props){var item=obj[props[i]];if(item!==undefined)return elem===!1?props[i]:is(item,"function")?item.bind(elem||obj):item}return!1}function testPropsAll(prop,prefixed,elem){var ucProp=prop.charAt(0).toUpperCase()+prop.slice(1),props=(prop+" "+cssomPrefixes.join(ucProp+" ")+ucProp).split(" ");return is(prefixed,"string")||is(prefixed,"undefined")?testProps(props,prefixed):(props=(prop+" "+domPrefixes.join(ucProp+" ")+ucProp).split(" "),testDOMProps(props,prefixed,elem))}var inputElem,featureName,hasOwnProp,version="2.6.2",Modernizr={},enableClasses=!0,docElement=document.documentElement,mod="modernizr",modElem=document.createElement(mod),mStyle=modElem.style,prefixes=({}.toString," -webkit- -moz- -o- -ms- ".split(" ")),omPrefixes="Webkit Moz O ms",cssomPrefixes=omPrefixes.split(" "),domPrefixes=omPrefixes.toLowerCase().split(" "),ns={svg:"http://www.w3.org/2000/svg"},tests={},classes=[],slice=classes.slice,injectElementWithStyles=function(rule,callback,nodes,testnames){var style,ret,node,docOverflow,div=document.createElement("div"),body=document.body,fakeBody=body||document.createElement("body");if(parseInt(nodes,10))for(;nodes--;)node=document.createElement("div"),node.id=testnames?testnames[nodes]:mod+(nodes+1),div.appendChild(node);return style=["&#173;",'<style id="s',mod,'">',rule,"</style>"].join(""),div.id=mod,(body?div:fakeBody).innerHTML+=style,fakeBody.appendChild(div),body||(fakeBody.style.background="",fakeBody.style.overflow="hidden",docOverflow=docElement.style.overflow,docElement.style.overflow="hidden",docElement.appendChild(fakeBody)),ret=callback(div,rule),body?div.parentNode.removeChild(div):(fakeBody.parentNode.removeChild(fakeBody),docElement.style.overflow=docOverflow),!!ret},_hasOwnProperty={}.hasOwnProperty;hasOwnProp=is(_hasOwnProperty,"undefined")||is(_hasOwnProperty.call,"undefined")?function(object,property){return property in object&&is(object.constructor.prototype[property],"undefined")}:function(object,property){return _hasOwnProperty.call(object,property)},Function.prototype.bind||(Function.prototype.bind=function(that){var target=this;if("function"!=typeof target)throw new TypeError;var args=slice.call(arguments,1),bound=function(){if(this instanceof bound){var F=function(){};F.prototype=target.prototype;var self=new F,result=target.apply(self,args.concat(slice.call(arguments)));return Object(result)===result?result:self}return target.apply(that,args.concat(slice.call(arguments)))};return bound}),tests.canvas=function(){var elem=document.createElement("canvas");return!(!elem.getContext||!elem.getContext("2d"))},tests.borderradius=function(){return testPropsAll("borderRadius")},tests.boxshadow=function(){return testPropsAll("boxShadow")},tests.cssanimations=function(){return testPropsAll("animationName")},tests.csstransforms=function(){return!!testPropsAll("transform")},tests.csstransforms3d=function(){var ret=!!testPropsAll("perspective");return ret&&"webkitPerspective"in docElement.style&&injectElementWithStyles("@media (transform-3d),(-webkit-transform-3d){#modernizr{left:9px;position:absolute;height:3px;}}",function(node){ret=9===node.offsetLeft&&3===node.offsetHeight}),ret},tests.csstransitions=function(){return testPropsAll("transition")},tests.svg=function(){return!!document.createElementNS&&!!document.createElementNS(ns.svg,"svg").createSVGRect};for(var feature in tests)hasOwnProp(tests,feature)&&(featureName=feature.toLowerCase(),Modernizr[featureName]=tests[feature](),classes.push((Modernizr[featureName]?"":"no-")+featureName));return Modernizr.addTest=function(feature,test){if("object"==typeof feature)for(var key in feature)hasOwnProp(feature,key)&&Modernizr.addTest(key,feature[key]);else{if(feature=feature.toLowerCase(),Modernizr[feature]!==undefined)return Modernizr;test="function"==typeof test?test():test,"undefined"!=typeof enableClasses&&enableClasses&&(docElement.className+=" "+(test?"":"no-")+feature),Modernizr[feature]=test}return Modernizr},setCss(""),modElem=inputElem=null,function(window,document){function addStyleSheet(ownerDocument,cssText){var p=ownerDocument.createElement("p"),parent=ownerDocument.getElementsByTagName("head")[0]||ownerDocument.documentElement;return p.innerHTML="x<style>"+cssText+"</style>",parent.insertBefore(p.lastChild,parent.firstChild)}function getElements(){var elements=html5.elements;return"string"==typeof elements?elements.split(" "):elements}function getExpandoData(ownerDocument){var data=expandoData[ownerDocument[expando]];return data||(data={},expanID++,ownerDocument[expando]=expanID,expandoData[expanID]=data),data}function createElement(nodeName,ownerDocument,data){if(ownerDocument||(ownerDocument=document),supportsUnknownElements)return ownerDocument.createElement(nodeName);data||(data=getExpandoData(ownerDocument));var node;return node=data.cache[nodeName]?data.cache[nodeName].cloneNode():saveClones.test(nodeName)?(data.cache[nodeName]=data.createElem(nodeName)).cloneNode():data.createElem(nodeName),node.canHaveChildren&&!reSkip.test(nodeName)?data.frag.appendChild(node):node}function createDocumentFragment(ownerDocument,data){if(ownerDocument||(ownerDocument=document),supportsUnknownElements)return ownerDocument.createDocumentFragment();data=data||getExpandoData(ownerDocument);for(var clone=data.frag.cloneNode(),i=0,elems=getElements(),l=elems.length;l>i;i++)clone.createElement(elems[i]);return clone}function shivMethods(ownerDocument,data){data.cache||(data.cache={},data.createElem=ownerDocument.createElement,data.createFrag=ownerDocument.createDocumentFragment,data.frag=data.createFrag()),ownerDocument.createElement=function(nodeName){return html5.shivMethods?createElement(nodeName,ownerDocument,data):data.createElem(nodeName)},ownerDocument.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+getElements().join().replace(/\w+/g,function(nodeName){return data.createElem(nodeName),data.frag.createElement(nodeName),'c("'+nodeName+'")'})+");return n}")(html5,data.frag)}function shivDocument(ownerDocument){ownerDocument||(ownerDocument=document);var data=getExpandoData(ownerDocument);return!html5.shivCSS||supportsHtml5Styles||data.hasCSS||(data.hasCSS=!!addStyleSheet(ownerDocument,"article,aside,figcaption,figure,footer,header,hgroup,nav,section{display:block}mark{background:#FF0;color:#000}")),supportsUnknownElements||shivMethods(ownerDocument,data),ownerDocument}var supportsHtml5Styles,supportsUnknownElements,options=window.html5||{},reSkip=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,saveClones=/^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i,expando="_html5shiv",expanID=0,expandoData={};!function(){try{var a=document.createElement("a");a.innerHTML="<xyz></xyz>",supportsHtml5Styles="hidden"in a,supportsUnknownElements=1==a.childNodes.length||function(){document.createElement("a");var frag=document.createDocumentFragment();return"undefined"==typeof frag.cloneNode||"undefined"==typeof frag.createDocumentFragment||"undefined"==typeof frag.createElement}()}catch(e){supportsHtml5Styles=!0,supportsUnknownElements=!0}}();var html5={elements:options.elements||"abbr article aside audio bdi canvas data datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video",shivCSS:options.shivCSS!==!1,supportsUnknownElements:supportsUnknownElements,shivMethods:options.shivMethods!==!1,type:"default",shivDocument:shivDocument,createElement:createElement,createDocumentFragment:createDocumentFragment};window.html5=html5,shivDocument(document)}(this,document),Modernizr._version=version,Modernizr._prefixes=prefixes,Modernizr._domPrefixes=domPrefixes,Modernizr._cssomPrefixes=cssomPrefixes,Modernizr.testProp=function(prop){return testProps([prop])},Modernizr.testAllProps=testPropsAll,Modernizr.testStyles=injectElementWithStyles,docElement.className=docElement.className.replace(/(^|\s)no-js(\s|$)/,"$1$2")+(enableClasses?" js "+classes.join(" "):""),Modernizr}(this,this.document),function(a,b,c){function d(a){return"[object Function]"==o.call(a)}function e(a){return"string"==typeof a}function f(){}function g(a){return!a||"loaded"==a||"complete"==a||"uninitialized"==a}function h(){var a=p.shift();q=1,a?a.t?m(function(){("c"==a.t?B.injectCss:B.injectJs)(a.s,0,a.a,a.x,a.e,1)},0):(a(),h()):q=0}function i(a,c,d,e,f,i,j){function k(b){if(!o&&g(l.readyState)&&(u.r=o=1,!q&&h(),l.onload=l.onreadystatechange=null,b)){"img"!=a&&m(function(){t.removeChild(l)},50);for(var d in y[c])y[c].hasOwnProperty(d)&&y[c][d].onload()}}var j=j||B.errorTimeout,l=b.createElement(a),o=0,r=0,u={t:d,s:c,e:f,a:i,x:j};1===y[c]&&(r=1,y[c]=[]),"object"==a?l.data=c:(l.src=c,l.type=a),l.width=l.height="0",l.onerror=l.onload=l.onreadystatechange=function(){k.call(this,r)},p.splice(e,0,u),"img"!=a&&(r||2===y[c]?(t.insertBefore(l,s?null:n),m(k,j)):y[c].push(l))}function j(a,b,c,d,f){return q=0,b=b||"j",e(a)?i("c"==b?v:u,a,b,this.i++,c,d,f):(p.splice(this.i++,0,a),1==p.length&&h()),this}function k(){var a=B;return a.loader={load:j,i:0},a}var A,B,l=b.documentElement,m=a.setTimeout,n=b.getElementsByTagName("script")[0],o={}.toString,p=[],q=0,r="MozAppearance"in l.style,s=r&&!!b.createRange().compareNode,t=s?l:n.parentNode,l=a.opera&&"[object Opera]"==o.call(a.opera),l=!!b.attachEvent&&!l,u=r?"object":l?"script":"img",v=l?"script":u,w=Array.isArray||function(a){return"[object Array]"==o.call(a)},x=[],y={},z={timeout:function(a,b){return b.length&&(a.timeout=b[0]),a}};B=function(a){function b(a){var e,f,g,a=a.split("!"),b=x.length,c=a.pop(),d=a.length,c={url:c,origUrl:c,prefixes:a};for(f=0;d>f;f++)g=a[f].split("="),(e=z[g.shift()])&&(c=e(c,g));for(f=0;b>f;f++)c=x[f](c);return c}function g(a,e,f,g,h){var i=b(a),j=i.autoCallback;i.url.split(".").pop().split("?").shift(),i.bypass||(e&&(e=d(e)?e:e[a]||e[g]||e[a.split("/").pop().split("?")[0]]),i.instead?i.instead(a,e,f,g,h):(y[i.url]?i.noexec=!0:y[i.url]=1,f.load(i.url,i.forceCSS||!i.forceJS&&"css"==i.url.split(".").pop().split("?").shift()?"c":c,i.noexec,i.attrs,i.timeout),(d(e)||d(j))&&f.load(function(){k(),e&&e(i.origUrl,h,g),j&&j(i.origUrl,h,g),y[i.url]=2})))}function h(a,b){function c(a,c){if(a){if(e(a))c||(j=function(){var a=[].slice.call(arguments);k.apply(this,a),l()}),g(a,j,b,0,h);else if(Object(a)===a)for(n in m=function(){var c,b=0;for(c in a)a.hasOwnProperty(c)&&b++;return b}(),a)a.hasOwnProperty(n)&&(!c&&!--m&&(d(j)?j=function(){var a=[].slice.call(arguments);k.apply(this,a),l()}:j[n]=function(a){return function(){var b=[].slice.call(arguments);a&&a.apply(this,b),l()}}(k[n])),g(a[n],j,b,n,h))}else!c&&l()}var m,n,h=!!a.test,i=a.load||a.both,j=a.callback||f,k=j,l=a.complete||f;c(h?a.yep:a.nope,!!i),i&&c(i)}var i,j,l=this.yepnope.loader;if(e(a))g(a,0,l,0);else if(w(a))for(i=0;i<a.length;i++)j=a[i],e(j)?g(j,0,l,0):w(j)?B(j):Object(j)===j&&h(j,l);else Object(a)===a&&h(a,l)},B.addPrefix=function(a,b){z[a]=b},B.addFilter=function(a){x.push(a)},B.errorTimeout=1e4,null==b.readyState&&b.addEventListener&&(b.readyState="loading",b.addEventListener("DOMContentLoaded",A=function(){b.removeEventListener("DOMContentLoaded",A,0),b.readyState="complete"},0)),a.yepnope=k(),a.yepnope.executeStack=h,a.yepnope.injectJs=function(a,c,d,e,i,j){var l,o,k=b.createElement("script"),e=e||B.errorTimeout;k.src=a;for(o in d)k.setAttribute(o,d[o]);c=j?h:c||f,k.onreadystatechange=k.onload=function(){!l&&g(k.readyState)&&(l=1,c(),k.onload=k.onreadystatechange=null)},m(function(){l||(l=1,c(1))},e),i?k.onload():n.parentNode.insertBefore(k,n)},a.yepnope.injectCss=function(a,c,d,e,g,i){var j,e=b.createElement("link"),c=i?h:c||f;e.href=a,e.rel="stylesheet",e.type="text/css";for(j in d)e.setAttribute(j,d[j]);g||(n.parentNode.insertBefore(e,n),m(c,0))}}(this,document),Modernizr.load=function(){yepnope.apply(window,[].slice.call(arguments,0))},function(global,undefined){"use strict";function addFromSetImmediateArguments(args){return tasksByHandle[nextHandle]=partiallyApplied.apply(undefined,args),nextHandle++}function partiallyApplied(handler){var args=[].slice.call(arguments,1);return function(){"function"==typeof handler?handler.apply(undefined,args):new Function(""+handler)()}}function runIfPresent(handle){if(currentlyRunningATask)setTimeout(partiallyApplied(runIfPresent,handle),0);else{var task=tasksByHandle[handle];if(task){currentlyRunningATask=!0;try{task()}finally{clearImmediate(handle),currentlyRunningATask=!1}}}}function clearImmediate(handle){delete tasksByHandle[handle]}function installNextTickImplementation(){setImmediate=function(){var handle=addFromSetImmediateArguments(arguments);return process.nextTick(partiallyApplied(runIfPresent,handle)),handle}}function canUsePostMessage(){if(global.postMessage&&!global.importScripts){var postMessageIsAsynchronous=!0,oldOnMessage=global.onmessage;return global.onmessage=function(){postMessageIsAsynchronous=!1},global.postMessage("","*"),global.onmessage=oldOnMessage,postMessageIsAsynchronous}}function installPostMessageImplementation(){var messagePrefix="setImmediate$"+Math.random()+"$",onGlobalMessage=function(event){event.source===global&&"string"==typeof event.data&&0===event.data.indexOf(messagePrefix)&&runIfPresent(+event.data.slice(messagePrefix.length))};global.addEventListener?global.addEventListener("message",onGlobalMessage,!1):global.attachEvent("onmessage",onGlobalMessage),setImmediate=function(){var handle=addFromSetImmediateArguments(arguments);return global.postMessage(messagePrefix+handle,"*"),handle}}function installMessageChannelImplementation(){var channel=new MessageChannel;channel.port1.onmessage=function(event){var handle=event.data;runIfPresent(handle)},setImmediate=function(){var handle=addFromSetImmediateArguments(arguments);return channel.port2.postMessage(handle),handle}}function installReadyStateChangeImplementation(){var html=doc.documentElement;setImmediate=function(){var handle=addFromSetImmediateArguments(arguments),script=doc.createElement("script");return script.onreadystatechange=function(){runIfPresent(handle),script.onreadystatechange=null,html.removeChild(script),script=null},html.appendChild(script),handle}}function installSetTimeoutImplementation(){setImmediate=function(){var handle=addFromSetImmediateArguments(arguments);return setTimeout(partiallyApplied(runIfPresent,handle),0),handle}}if(!global.setImmediate){var setImmediate,nextHandle=1,tasksByHandle={},currentlyRunningATask=!1,doc=global.document,attachTo=Object.getPrototypeOf&&Object.getPrototypeOf(global);attachTo=attachTo&&attachTo.setTimeout?attachTo:global,"[object process]"==={}.toString.call(global.process)?installNextTickImplementation():canUsePostMessage()?installPostMessageImplementation():global.MessageChannel?installMessageChannelImplementation():doc&&"onreadystatechange"in doc.createElement("script")?installReadyStateChangeImplementation():installSetTimeoutImplementation(),attachTo.setImmediate=setImmediate,attachTo.clearImmediate=clearImmediate}}(new Function("return this")()),function(){function Viewport(){return this.PRE_IOS7_VIEWPORT="initial-scale=1, maximum-scale=1, user-scalable=no",this.IOS7_VIEWPORT="width=device-width, height=device-height, initial-scale=1, maximum-scale=1, user-scalable=no",this.DEFAULT_VIEWPORT="initial-scale=1, maximum-scale=1, user-scalable=no",this.ensureViewportElement(),this.platform={},this.platform.name=this.getPlatformName(),this.platform.version=this.getPlatformVersion(),this}Viewport.prototype.ensureViewportElement=function(){this.viewportElement=document.querySelector("meta[name=viewport]"),this.viewportElement||(this.viewportElement=document.createElement("meta"),this.viewportElement.name="viewport",document.head.appendChild(this.viewportElement))},Viewport.prototype.setup=function(){function isWebView(){return!!(window.cordova||window.phonegap||window.PhoneGap)}this.viewportElement&&"true"!=this.viewportElement.getAttribute("data-no-adjust")&&("ios"==this.platform.name?this.platform.version>=7&&isWebView()?this.viewportElement.setAttribute("content",this.IOS7_VIEWPORT):this.viewportElement.setAttribute("content",this.PRE_IOS7_VIEWPORT):this.viewportElement.setAttribute("content",this.DEFAULT_VIEWPORT))},Viewport.prototype.getPlatformName=function(){return navigator.userAgent.match(/Android/i)?"android":navigator.userAgent.match(/iPhone|iPad|iPod/i)?"ios":void 0},Viewport.prototype.getPlatformVersion=function(){var start=window.navigator.userAgent.indexOf("OS ");return window.Number(window.navigator.userAgent.substr(start+3,3).replace("_","."))},window.Viewport=Viewport}(),function(){try{app=angular.module("templates-main")}catch(err){app=angular.module("templates-main",[])}app.run(["$templateCache",function($templateCache){"use strict";$templateCache.put("templates/back_button.tpl",'<span \n class="toolbar-button--quiet {{modifierTemplater(\'toolbar-button--*\')}}" \n ng-click="$root.ons.findParentComponentUntil(\'ons-navigator\', $event).popPage()" \n ng-show="showBackButton"\n style="height: 44px; line-height: 0; padding: 0 10px 0 0; position: relative;">\n \n <i \n class="ion-ios-arrow-back ons-back-button__icon" \n style="vertical-align: top; background-color: transparent; height: 44px; line-height: 44px; font-size: 36px; margin-left: 8px; margin-right: 2px; width: 16px; display: inline-block; padding-top: 1px;"></i>\n\n <span \n style="vertical-align: top; display: inline-block; line-height: 44px; height: 44px;" \n class="back-button__label"></span>\n</span>\n')}])}(),function(){try{app=angular.module("templates-main") }catch(err){app=angular.module("templates-main",[])}app.run(["$templateCache",function($templateCache){"use strict";$templateCache.put("templates/button.tpl",'<span class="label ons-button-inner"></span>\n<span class="spinner button__spinner {{modifierTemplater(\'button--*__spinner\')}}"></span>\n')}])}(),function(){try{app=angular.module("templates-main")}catch(err){app=angular.module("templates-main",[])}app.run(["$templateCache",function($templateCache){"use strict";$templateCache.put("templates/dialog.tpl",'<div class="dialog-mask"></div>\n<div class="dialog {{ modifierTemplater(\'dialog--*\') }}"></div>\n</div>\n')}])}(),function(){try{app=angular.module("templates-main")}catch(err){app=angular.module("templates-main",[])}app.run(["$templateCache",function($templateCache){"use strict";$templateCache.put("templates/icon.tpl",'<i class="fa fa-{{icon}} fa-{{spin}} fa-{{fixedWidth}} fa-rotate-{{rotate}} fa-flip-{{flip}}" ng-class="sizeClass" ng-style="style"></i>\n')}])}(),function(){try{app=angular.module("templates-main")}catch(err){app=angular.module("templates-main",[])}app.run(["$templateCache",function($templateCache){"use strict";$templateCache.put("templates/popover.tpl",'<div class="popover-mask"></div>\n<div class="popover popover--{{ direction }} {{ modifierTemplater(\'popover--*\') }}">\n <div class="popover__content {{ modifierTemplater(\'popover__content--*\') }}"></div>\n <div class="popover__{{ arrowPosition }}-arrow"></div>\n</div>\n')}])}(),function(){try{app=angular.module("templates-main")}catch(err){app=angular.module("templates-main",[])}app.run(["$templateCache",function($templateCache){"use strict";$templateCache.put("templates/row.tpl",'<div class="row row-{{align}} ons-row-inner"></div>\n')}])}(),function(){try{app=angular.module("templates-main")}catch(err){app=angular.module("templates-main",[])}app.run(["$templateCache",function($templateCache){"use strict";$templateCache.put("templates/sliding_menu.tpl",'<div class="onsen-sliding-menu__menu ons-sliding-menu-inner"></div>\n<div class="onsen-sliding-menu__main ons-sliding-menu-inner"></div>\n')}])}(),function(){try{app=angular.module("templates-main")}catch(err){app=angular.module("templates-main",[])}app.run(["$templateCache",function($templateCache){"use strict";$templateCache.put("templates/split_view.tpl",'<div class="onsen-split-view__secondary full-screen ons-split-view-inner"></div>\n<div class="onsen-split-view__main full-screen ons-split-view-inner"></div>\n')}])}(),function(){try{app=angular.module("templates-main")}catch(err){app=angular.module("templates-main",[])}app.run(["$templateCache",function($templateCache){"use strict";$templateCache.put("templates/switch.tpl",'<label class="switch {{modifierTemplater(\'switch--*\')}}">\n <input type="checkbox" class="switch__input {{modifierTemplater(\'switch--*__input\')}}" ng-model="model">\n <div class="switch__toggle {{modifierTemplater(\'switch--*__toggle\')}}"></div>\n</label>\n')}])}(),function(){try{app=angular.module("templates-main")}catch(err){app=angular.module("templates-main",[])}app.run(["$templateCache",function($templateCache){"use strict";$templateCache.put("templates/tab.tpl",'<input type="radio" name="tab-bar-{{tabbarId}}" style="display: none">\n<button class="tab-bar__button tab-bar-inner {{tabbarModifierTemplater(\'tab-bar--*__button\')}} {{modifierTemplater(\'tab-bar__button--*\')}}" ng-click="tryToChange()">\n</button>\n')}])}(),function(){try{app=angular.module("templates-main")}catch(err){app=angular.module("templates-main",[])}app.run(["$templateCache",function($templateCache){"use strict";$templateCache.put("templates/tab_bar.tpl",'<div class="ons-tab-bar__content tab-bar__content"></div>\n<div ng-hide="hideTabs" class="tab-bar ons-tab-bar__footer {{modifierTemplater(\'tab-bar--*\')}} ons-tabbar-inner"></div>\n')}])}(),function(){try{app=angular.module("templates-main")}catch(err){app=angular.module("templates-main",[])}app.run(["$templateCache",function($templateCache){"use strict";$templateCache.put("templates/toolbar_button.tpl","<span class=\"toolbar-button {{modifierTemplater('toolbar-button--*')}} navigation-bar__line-height\" ng-transclude></span>\n")}])}(),window.DoorLock=function(){var DoorLock=function(options){options=options||{},this._lockList=[],this._waitList=[],this._log=options.log||function(){}};return DoorLock.generateId=function(){var i=0;return function(){return i++}}(),DoorLock.prototype={lock:function(){var self=this,unlock=function(){self._unlock(unlock)};return unlock.id=DoorLock.generateId(),this._lockList.push(unlock),this._log("lock: "+unlock.id),unlock},_unlock:function(fn){var index=this._lockList.indexOf(fn);if(-1===index)throw new Error("This function is not registered in the lock list.");this._lockList.splice(index,1),this._log("unlock: "+fn.id),this._tryToFreeWaitList()},_tryToFreeWaitList:function(){for(;!this.isLocked()&&this._waitList.length>0;)this._waitList.shift()()},waitUnlock:function(callback){if(!(callback instanceof Function))throw new Error("The callback param must be a function.");this.isLocked()?this._waitList.push(callback):callback()},isLocked:function(){return this._lockList.length>0}},DoorLock}(),window.ons=function(){"use strict";function waitDeviceReady(){var unlockDeviceReady=ons._readyLock.lock();window.addEventListener("DOMContentLoaded",function(){ons.isWebView()?window.document.addEventListener("deviceready",unlockDeviceReady,!1):unlockDeviceReady()},!1)}function waitOnsenUILoad(){var unlockOnsenUI=ons._readyLock.lock();module.run(["$compile","$rootScope","$onsen",function($compile,$rootScope){if("loading"===document.readyState||"uninitialized"==document.readyState)window.addEventListener("DOMContentLoaded",function(){document.body.appendChild(document.createElement("ons-dummy-for-init"))});else{if(!document.body)throw new Error("Invalid initialization state.");document.body.appendChild(document.createElement("ons-dummy-for-init"))}document.querySelector("ons-alert-dialog")&&console.warn("Invalid usage of <ons-alert-dialog>."),$rootScope.$on("$ons-ready",unlockOnsenUI)}])}function initAngularModule(){module.value("$onsGlobal",ons),module.run(["$compile","$rootScope","$onsen","$q",function($compile,$rootScope,$onsen,$q){ons._onsenService=$onsen,ons._qService=$q,$rootScope.ons=window.ons,$rootScope.console=window.console,$rootScope.alert=window.alert,ons.$compile=$compile}])}function initKeyboardEvents(){ons.softwareKeyboard=new MicroEvent,ons.softwareKeyboard._visible=!1;var onShow=function(){ons.softwareKeyboard._visible=!0,ons.softwareKeyboard.emit("show")},onHide=function(){ons.softwareKeyboard._visible=!1,ons.softwareKeyboard.emit("hide")},bindEvents=function(){return"undefined"!=typeof Keyboard?(Keyboard.onshow=onShow,Keyboard.onhide=onHide,ons.softwareKeyboard.emit("init",{visible:Keyboard.isVisible}),!0):"undefined"!=typeof cordova.plugins&&"undefined"!=typeof cordova.plugins.Keyboard?(window.addEventListener("native.keyboardshow",onShow),window.addEventListener("native.keyboardhide",onHide),ons.softwareKeyboard.emit("init",{visible:cordova.plugins.Keyboard.isVisible}),!0):!1},noPluginError=function(){console.warn("ons-keyboard: Cordova Keyboard plugin is not present.")};document.addEventListener("deviceready",function(){bindEvents()||((document.querySelector("[ons-keyboard-active]")||document.querySelector("[ons-keyboard-inactive]"))&&noPluginError(),ons.softwareKeyboard.on=noPluginError)})}function createOnsenFacade(){var ons={_readyLock:new DoorLock,_onsenService:null,_config:{autoStatusBarFill:!0},_unlockersDict:{},componentBase:window,bootstrap:function(name,deps){angular.isArray(name)&&(deps=name,name=void 0),name||(name="myOnsenApp"),deps=["onsen"].concat(angular.isArray(deps)?deps:[]);var module=angular.module(name,deps),doc=window.document;if("loading"==doc.readyState||"uninitialized"==doc.readyState)doc.addEventListener("DOMContentLoaded",function(){angular.bootstrap(doc.documentElement,[name])},!1);else{if(!doc.documentElement)throw new Error("Invalid state");angular.bootstrap(doc.documentElement,[name])}return module},enableAutoStatusBarFill:function(){if(this.isReady())throw new Error("This method must be called before ons.isReady() is true.");this._config.autoStatusBarFill=!0},disableAutoStatusBarFill:function(){if(this.isReady())throw new Error("This method must be called before ons.isReady() is true.");this._config.autoStatusBarFill=!1},findParentComponentUntil:function(name,dom){var element;return dom instanceof HTMLElement?element=angular.element(dom):dom instanceof angular.element?element=dom:dom.target&&(element=angular.element(dom.target)),element.inheritedData(name)},setDefaultDeviceBackButtonListener:function(listener){this._getOnsenService().getDefaultDeviceBackButtonHandler().setListener(listener)},disableDeviceBackButtonHandler:function(){this._getOnsenService().DeviceBackButtonHandler.disable()},enableDeviceBackButtonHandler:function(){this._getOnsenService().DeviceBackButtonHandler.enable()},findComponent:function(selector,dom){var target=(dom?dom:document).querySelector(selector);return target?angular.element(target).data(target.nodeName.toLowerCase())||null:null},isReady:function(){return!ons._readyLock.isLocked()},compile:function(dom){if(!ons.$compile)throw new Error("ons.$compile() is not ready. Wait for initialization with ons.ready().");if(!(dom instanceof HTMLElement))throw new Error("First argument must be an instance of HTMLElement.");var scope=angular.element(dom).scope();if(!scope)throw new Error("AngularJS Scope is null. Argument DOM element must be attached in DOM document.");ons.$compile(dom)(scope)},_getOnsenService:function(){if(!this._onsenService)throw new Error("$onsen is not loaded, wait for ons.ready().");return this._onsenService},ready:function(callback){if(callback instanceof Function)ons.isReady()?callback():ons._readyLock.waitUnlock(callback);else if(angular.isArray(callback)&&arguments[1]instanceof Function){var dependencies=callback;callback=arguments[1],ons.ready(function(){var $onsen=ons._getOnsenService();$onsen.waitForVariables(dependencies,callback)})}},isWebView:function(){if("loading"===document.readyState||"uninitialized"==document.readyState)throw new Error("isWebView() method is available after dom contents loaded.");return!!(window.cordova||window.phonegap||window.PhoneGap)},createAlertDialog:function(page){if(!page)throw new Error("Page url must be defined.");var alertDialog=angular.element("<ons-alert-dialog>"),$onsen=this._getOnsenService();return angular.element(document.body).append(angular.element(alertDialog)),$onsen.getPageHTMLAsync(page).then(function(html){var div=document.createElement("div");div.innerHTML=html;for(var el=angular.element(div.querySelector("ons-alert-dialog")),attrs=el.prop("attributes"),i=0,l=attrs.length;l>i;i++)alertDialog.attr(attrs[i].name,attrs[i].value);return alertDialog.html(el.html()),ons.compile(alertDialog[0]),el.attr("disabled")&&alertDialog.attr("disabled","disabled"),alertDialog.data("ons-alert-dialog")})},createDialog:function(page){if(!page)throw new Error("Page url must be defined.");var dialog=angular.element("<ons-dialog>"),$onsen=this._getOnsenService();return angular.element(document.body).append(angular.element(dialog)),$onsen.getPageHTMLAsync(page).then(function(html){var div=document.createElement("div");div.innerHTML=html;for(var el=angular.element(div.querySelector("ons-dialog")),attrs=el.prop("attributes"),i=0,l=attrs.length;l>i;i++)dialog.attr(attrs[i].name,attrs[i].value);dialog.html(el.html()),ons.compile(dialog[0]),el.attr("disabled")&&dialog.attr("disabled","disabled");var deferred=ons._qService.defer();return dialog.on("ons-dialog:init",function(e){var child=dialog[0].querySelector(".dialog");if(el[0].hasAttribute("style")){var parentStyle=el[0].getAttribute("style"),childStyle=child.getAttribute("style"),newStyle=function(a,b){var c=(";"===a.substr(-1)?a:a+";")+(";"===b.substr(-1)?b:b+";");return c}(parentStyle,childStyle);child.setAttribute("style",newStyle)}deferred.resolve(e.component)}),deferred.promise})},createPopover:function(page){if(!page)throw new Error("Page url must be defined.");var popover=angular.element("<ons-popover>"),$onsen=this._getOnsenService();return angular.element(document.body).append(angular.element(popover)),$onsen.getPageHTMLAsync(page).then(function(html){var div=document.createElement("div");div.innerHTML=html;for(var el=angular.element(div.querySelector("ons-popover")),attrs=el.prop("attributes"),i=0,l=attrs.length;l>i;i++)popover.attr(attrs[i].name,attrs[i].value);popover.html(el.html()),ons.compile(popover[0]),el.attr("disabled")&&popover.attr("disabled","disabled");var deferred=ons._qService.defer();return popover.on("ons-popover:init",function(e){var child=popover[0].querySelector(".popover");if(el[0].hasAttribute("style")){var parentStyle=el[0].getAttribute("style"),childStyle=child.getAttribute("style"),newStyle=function(a,b){var c=(";"===a.substr(-1)?a:a+";")+(";"===b.substr(-1)?b:b+";");return c}(parentStyle,childStyle);child.setAttribute("style",newStyle)}deferred.resolve(e.component)}),deferred.promise})}};return ons}var module=angular.module("onsen",["templates-main"]);angular.module("onsen.directives",["onsen"]);var ons=createOnsenFacade();return initKeyboardEvents(),waitDeviceReady(),waitOnsenUILoad(),initAngularModule(),ons}(),function(){"use strict";var module=angular.module("onsen");module.factory("AlertDialogView",["$onsen","DialogAnimator","SlideDialogAnimator","AndroidAlertDialogAnimator","IOSAlertDialogAnimator",function($onsen,DialogAnimator,SlideDialogAnimator,AndroidAlertDialogAnimator,IOSAlertDialogAnimator){var AlertDialogView=Class.extend({init:function(scope,element,attrs){if(this._scope=scope,this._element=element,this._element.css({display:"none",zIndex:20001}),this._dialog=element,this._visible=!1,this._doorLock=new DoorLock,this._animation=AlertDialogView._animatorDict["undefined"!=typeof attrs.animation?attrs.animation:"default"],!this._animation)throw new Error("No such animation: "+attrs.animation);this._deviceBackButtonHandler=$onsen.DeviceBackButtonHandler.create(this._element,this._onDeviceBackButton.bind(this)),this._createMask(attrs.maskColor)},show:function(options){options=options||{};var cancel=!1,callback=options.callback||function(){};this.emit("preshow",{alertDialog:this,cancel:function(){cancel=!0}}),cancel||this._doorLock.waitUnlock(function(){var unlock=this._doorLock.lock(),animation=this._animation;this._mask.css("display","block"),this._mask.css("opacity",1),this._element.css("display","block"),options.animation&&(animation=AlertDialogView._animatorDict[options.animation]),animation.show(this,function(){this._visible=!0,unlock(),this.emit("postshow",{alertDialog:this}),callback()}.bind(this))}.bind(this))},hide:function(options){options=options||{};var cancel=!1,callback=options.callback||function(){};this.emit("prehide",{alertDialog:this,cancel:function(){cancel=!0}}),cancel||this._doorLock.waitUnlock(function(){var unlock=this._doorLock.lock(),animation=this._animation;options.animation&&(animation=AlertDialogView._animatorDict[options.animation]),animation.hide(this,function(){this._element.css("display","none"),this._mask.css("display","none"),this._visible=!1,unlock(),this.emit("posthide",{alertDialog:this}),callback()}.bind(this))}.bind(this))},isShown:function(){return this._visible},destroy:function(){this._mask.off(),this._element.remove(),this._mask.remove(),this._deviceBackButtonHandler.destroy(),this._scope.$destroy(),this._deviceBackButtonHandler=this._element=this._mask=null},setDisabled:function(disabled){if("boolean"!=typeof disabled)throw new Error("Argument must be a boolean.");disabled?this._element.attr("disabled",!0):this._element.removeAttr("disabled")},isDisabled:function(){return this._element[0].hasAttribute("disabled")},setCancelable:function(cancelable){if("boolean"!=typeof cancelable)throw new Error("Argument must be a boolean.");cancelable?this._element.attr("cancelable",!0):this._element.removeAttr("cancelable")},isCancelable:function(){return this._element[0].hasAttribute("cancelable")},_cancel:function(){this.isCancelable()&&this.hide({callback:function(){this.emit("cancel")}.bind(this)})},_onDeviceBackButton:function(event){this.isCancelable()?this._cancel.bind(this)():event.callParentHandler()},_createMask:function(color){this._mask=angular.element("<div>").addClass("alert-dialog-mask").css({zIndex:2e4,display:"none"}),this._mask.on("click",this._cancel.bind(this)),color&&this._mask.css("background-color",color),angular.element(document.body).append(this._mask)}});return AlertDialogView._animatorDict={"default":$onsen.isAndroid()?new AndroidAlertDialogAnimator:new IOSAlertDialogAnimator,fade:$onsen.isAndroid()?new AndroidAlertDialogAnimator:new IOSAlertDialogAnimator,slide:new SlideDialogAnimator,none:new DialogAnimator},AlertDialogView.registerAnimator=function(name,animator){if(!(animator instanceof DialogAnimator))throw new Error('"animator" param must be an instance of DialogAnimator');this._animatorDict[name]=animator},MicroEvent.mixin(AlertDialogView),AlertDialogView}])}(),function(){"use strict;";var module=angular.module("onsen");module.factory("AndroidAlertDialogAnimator",["DialogAnimator",function(DialogAnimator){var AndroidAlertDialogAnimator=DialogAnimator.extend({timing:"cubic-bezier(.1, .7, .4, 1)",duration:.2,init:function(options){options=options||{},this.timing=options.timing||this.timing,this.duration=void 0!==options.duration?options.duration:this.duration},show:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask[0]).queue({opacity:0}).queue({opacity:1},{duration:this.duration,timing:this.timing}),animit(dialog._dialog[0]).queue({css:{transform:"translate3d(-50%, -50%, 0) scale3d(0.9, 0.9, 1.0)",opacity:0},duration:0}).queue({css:{transform:"translate3d(-50%, -50%, 0) scale3d(1.0, 1.0, 1.0)",opacity:1},duration:this.duration,timing:this.timing}).resetStyle().queue(function(done){callback(),done()}))},hide:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask[0]).queue({opacity:1}).queue({opacity:0},{duration:this.duration,timing:this.timing}),animit(dialog._dialog[0]).queue({css:{transform:"translate3d(-50%, -50%, 0) scale3d(1.0, 1.0, 1.0)",opacity:1},duration:0}).queue({css:{transform:"translate3d(-50%, -50%, 0) scale3d(0.9, 0.9, 1.0)",opacity:0},duration:this.duration,timing:this.timing}).resetStyle().queue(function(done){callback(),done()}))}});return AndroidAlertDialogAnimator}])}(),function(){"use strict;";var module=angular.module("onsen");module.factory("AndroidDialogAnimator",["DialogAnimator",function(DialogAnimator){var AndroidDialogAnimator=DialogAnimator.extend({timing:"ease-in-out",duration:.3,init:function(options){options=options||{},this.timing=options.timing||this.timing,this.duration=void 0!==options.duration?options.duration:this.duration},show:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask[0]).queue({opacity:0}).queue({opacity:1},{duration:this.duration,timing:this.timing}),animit(dialog._dialog[0]).queue({css:{transform:"translate3d(-50%, -60%, 0)",opacity:0},duration:0}).queue({css:{transform:"translate3d(-50%, -50%, 0)",opacity:1},duration:this.duration,timing:this.timing}).resetStyle().queue(function(done){callback(),done()}))},hide:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask[0]).queue({opacity:1}).queue({opacity:0},{duration:this.duration,timing:this.timing}),animit(dialog._dialog[0]).queue({css:{transform:"translate3d(-50%, -50%, 0)",opacity:1},duration:0}).queue({css:{transform:"translate3d(-50%, -60%, 0)",opacity:0},duration:this.duration,timing:this.timing}).resetStyle().queue(function(done){callback(),done()}))}});return AndroidDialogAnimator}])}(),function(){"use strict";var module=angular.module("onsen");module.factory("ButtonView",["$onsen",function(){var ButtonView=Class.extend({init:function(scope,element,attrs){this._element=element,this._scope=scope,this._attrs=attrs},startSpin:function(){this._attrs.$set("shouldSpin","true")},stopSpin:function(){this._attrs.$set("shouldSpin","false")},isSpinning:function(){return"true"===this._attrs.shouldSpin},setSpinAnimation:function(animation){this._scope.$apply(function(){var animations=["slide-left","slide-right","slide-up","slide-down","expand-left","expand-right","expand-up","expand-down","zoom-out","zoom-in"];animations.indexOf(animation)<0&&(console.warn("Animation "+animation+"doesn't exist."),animation="slide-left"),this._scope.animation=animation}.bind(this))},isDisabled:function(){return this._element[0].hasAttribute("disabled")},setDisabled:function(disabled){if("boolean"!=typeof disabled)throw new Error("Argument must be a boolean.");disabled?this._element[0].setAttribute("disabled",""):this._element[0].removeAttribute("disabled")}});return MicroEvent.mixin(ButtonView),ButtonView}])}(),function(){"use strict;";var module=angular.module("onsen");module.factory("CarouselView",["$onsen",function(){var VerticalModeTrait={_getScrollDelta:function(event){return event.gesture.deltaY},_getScrollVelocity:function(event){return event.gesture.velocityY},_getElementSize:function(){return this._element[0].getBoundingClientRect().height},_generateScrollTransform:function(scroll){return"translate3d(0px, "+-scroll+"px, 0px)"},_layoutCarouselItems:function(){for(var children=this._getCarouselItemElements(),sizeAttr=this._getCarouselItemSizeAttr(),sizeInfo=this._decomposeSizeString(sizeAttr),i=0;i<children.length;i++)angular.element(children[i]).css({position:"absolute",height:sizeAttr,width:"100%",visibility:"visible",left:"0px",top:i*sizeInfo.number+sizeInfo.unit})}},HorizontalModeTrait={_getScrollDelta:function(event){return event.gesture.deltaX},_getScrollVelocity:function(event){return event.gesture.velocityX},_getElementSize:function(){return this._element[0].getBoundingClientRect().width},_generateScrollTransform:function(scroll){return"translate3d("+-scroll+"px, 0px, 0px)"},_layoutCarouselItems:function(){for(var children=this._getCarouselItemElements(),sizeAttr=this._getCarouselItemSizeAttr(),sizeInfo=this._decomposeSizeString(sizeAttr),i=0;i<children.length;i++)angular.element(children[i]).css({position:"absolute",width:sizeAttr,height:"100%",top:"0px",visibility:"visible",left:i*sizeInfo.number+sizeInfo.unit})}},CarouselView=Class.extend({_element:void 0,_scope:void 0,_doorLock:void 0,_scroll:void 0,init:function(scope,element,attrs){this._element=element,this._scope=scope,this._attrs=attrs,this._doorLock=new DoorLock,this._scroll=0,this._lastActiveIndex=0,this._bindedOnDrag=this._onDrag.bind(this),this._bindedOnDragEnd=this._onDragEnd.bind(this),this._bindedOnResize=this._onResize.bind(this),this._mixin(this._isVertical()?VerticalModeTrait:HorizontalModeTrait),this._prepareEventListeners(),this._layoutCarouselItems(),this._setupInitialIndex(),this._attrs.$observe("direction",this._onDirectionChange.bind(this)),this._scope.$on("$destroy",this._destroy.bind(this)),this._saveLastState()},_onResize:function(){this.refresh()},_onDirectionChange:function(){this._isVertical()?this._element.css({overflowX:"auto",overflowY:""}):this._element.css({overflowX:"",overflowY:"auto"})},_saveLastState:function(){this._lastState={elementSize:this._getCarouselItemSize(),carouselElementCount:this._getCarouselItemCount(),width:this._getCarouselItemSize()*this._getCarouselItemCount()}},_getCarouselItemSize:function(){var sizeAttr=this._getCarouselItemSizeAttr(),sizeInfo=this._decomposeSizeString(sizeAttr),elementSize=this._getElementSize();if("%"===sizeInfo.unit)return Math.round(sizeInfo.number/100*elementSize);if("px"===sizeInfo.unit)return sizeInfo.number;throw new Error("Invalid state")},_getInitialIndex:function(){var index=parseInt(this._element.attr("initial-index"),10);return"number"!=typeof index||isNaN(index)?0:Math.max(Math.min(index,this._getCarouselItemCount()-1),0)},_getCarouselItemSizeAttr:function(){var attrName="item-"+(this._isVertical()?"height":"width"),itemSizeAttr=(""+this._element.attr(attrName)).trim();return itemSizeAttr.match(/^\d+(px|%)$/)?itemSizeAttr:"100%"},_decomposeSizeString:function(size){var matches=size.match(/^(\d+)(px|%)/);return{number:parseInt(matches[1],10),unit:matches[2]}},_setupInitialIndex:function(){this._scroll=this._getCarouselItemSize()*this._getInitialIndex(),this._lastActiveIndex=this._getInitialIndex(),this._scrollTo(this._scroll)},setSwipeable:function(swipeable){swipeable?this._element[0].setAttribute("swipeable",""):this._element[0].removeAttribute("swipeable")},isSwipeable:function(){return this._element[0].hasAttribute("swipeable")},setAutoScrollRatio:function(ratio){if(0>ratio||ratio>1)throw new Error("Invalid ratio.");this._element[0].setAttribute("auto-scroll-ratio",ratio)},getAutoScrollRatio:function(){var attr=this._element[0].getAttribute("auto-scroll-ratio");if(!attr)return.5;var scrollRatio=parseFloat(attr);if(0>scrollRatio||scrollRatio>1)throw new Error("Invalid ratio.");return isNaN(scrollRatio)?.5:scrollRatio},setActiveCarouselItemIndex:function(index,options){options=options||{},index=Math.max(0,Math.min(index,this._getCarouselItemCount()-1));var scroll=this._getCarouselItemSize()*index,max=this._calculateMaxScroll();this._scroll=Math.max(0,Math.min(max,scroll)),this._scrollTo(this._scroll,{animate:"none"!==options.animation,callback:options.callback}),this._tryFirePostChangeEvent()},getActiveCarouselItemIndex:function(){var scroll=this._scroll,count=this._getCarouselItemCount(),size=this._getCarouselItemSize();if(0>scroll)return 0;for(var i=0;count>i;i++)if(scroll>=size*i&&size*(i+1)>scroll)return i;return i},next:function(options){this.setActiveCarouselItemIndex(this.getActiveCarouselItemIndex()+1,options)},prev:function(options){this.setActiveCarouselItemIndex(this.getActiveCarouselItemIndex()-1,options)},setAutoScrollEnabled:function(enabled){enabled?this._element[0].setAttribute("auto-scroll",""):this._element[0].removeAttribute("auto-scroll")},isAutoScrollEnabled:function(){return this._element[0].hasAttribute("auto-scroll")},setDisabled:function(disabled){disabled?this._element[0].setAttribute("disabled",""):this._element[0].removeAttribute("disabled")},isDisabled:function(){return this._element[0].hasAttribute("disabled")},setOverscrollable:function(scrollable){scrollable?this._element[0].setAttribute("overscrollable",""):this._element[0].removeAttribute("overscrollable")},_mixin:function(trait){Object.keys(trait).forEach(function(key){this[key]=trait[key]}.bind(this))},_isEnabledChangeEvent:function(){var elementSize=this._getElementSize(),carouselItemSize=this._getCarouselItemSize();return this.isAutoScrollEnabled()&&elementSize===carouselItemSize},_isVertical:function(){return"vertical"===this._element.attr("direction")},_prepareEventListeners:function(){this._hammer=new Hammer(this._element[0],{dragMinDistance:1}),this._hammer.on("drag dragleft dragright dragup dragdown swipe swipeleft swiperight swipeup swipedown",this._bindedOnDrag),this._hammer.on("dragend",this._bindedOnDragEnd),angular.element(window).on("resize",this._bindedOnResize)},_tryFirePostChangeEvent:function(){var currentIndex=this.getActiveCarouselItemIndex();if(this._lastActiveIndex!==currentIndex){var lastActiveIndex=this._lastActiveIndex;this._lastActiveIndex=currentIndex,this.emit("postchange",{carousel:this,activeIndex:currentIndex,lastActiveIndex:lastActiveIndex})}},_onDrag:function(event){if(this.isSwipeable()){var direction=event.gesture.direction;if((!this._isVertical()||"left"!==direction&&"right"!==direction)&&(this._isVertical()||"up"!==direction&&"down"!==direction)){event.stopPropagation(),this._lastDragEvent=event;var scroll=this._scroll-this._getScrollDelta(event);this._scrollTo(scroll),event.gesture.preventDefault(),this._tryFirePostChangeEvent()}}},_onDragEnd:function(event){if(this.isSwipeable()){if(this._scroll=this._scroll-this._getScrollDelta(event),0!==this._getScrollDelta(event)&&event.stopPropagation(),this._isOverScroll(this._scroll)){var waitForAction=!1;this.emit("overscroll",{carousel:this,activeIndex:this.getActiveCarouselItemIndex(),direction:this._getOverScrollDirection(),waitToReturn:function(promise){waitForAction=!0,promise.then(function(){this._scrollToKillOverScroll()}.bind(this))}.bind(this)}),waitForAction||this._scrollToKillOverScroll()}else null!==this._lastDragEvent&&this._startMomemtumScroll(event);this._lastDragEvent=null,event.gesture.preventDefault()}},_getTouchEvents:function(){var EVENTS=["drag","dragstart","dragend","dragup","dragdown","dragleft","dragright","swipe","swipeup","swipedown","swipeleft","swiperight"];return EVENTS.join(" ")},isOverscrollable:function(){return this._element[0].hasAttribute("overscrollable")},_startMomemtumScroll:function(){if(null!==this._lastDragEvent){var velocity=this._getScrollVelocity(this._lastDragEvent),duration=.3,scrollDelta=100*duration*velocity,scroll=this._scroll+(this._getScrollDelta(this._lastDragEvent)>0?-scrollDelta:scrollDelta);scroll=this._normalizeScrollPosition(scroll),this._scroll=scroll,animit(this._getCarouselItemElements()).queue({transform:this._generateScrollTransform(this._scroll)},{duration:duration,timing:"cubic-bezier(.1, .7, .1, 1)"}).queue(function(done){done(),this._tryFirePostChangeEvent()}.bind(this)).play()}},_normalizeScrollPosition:function(scroll){var max=this._calculateMaxScroll();if(this.isAutoScrollEnabled()){for(var arr=[],size=this._getCarouselItemSize(),i=0;i<this._getCarouselItemCount();i++)max>=i*size&&arr.push(i*size);arr.push(max),arr.sort(function(left,right){return left=Math.abs(left-scroll),right=Math.abs(right-scroll),left-right}),arr=arr.filter(function(item,pos){return!pos||item!=arr[pos-1]});var lastScroll=this._lastActiveIndex*size,scrollRatio=Math.abs(scroll-lastScroll)/size;return scrollRatio<=this.getAutoScrollRatio()?lastScroll:scrollRatio>this.getAutoScrollRatio()&&1>scrollRatio&&arr[0]===lastScroll&&arr.length>1?arr[1]:arr[0]}return Math.max(0,Math.min(max,scroll))},_getCarouselItemElements:function(){for(var items=[],children=this._element.children(),i=0;i<children.length;i++)"ons-carousel-item"===children[i].nodeName.toLowerCase()&&items.push(children[i]);return items},_scrollTo:function(scroll,options){function normalizeScroll(scroll){var ratio=.35;if(0>scroll)return isOverscrollable?Math.round(scroll*ratio):0;var maxScroll=self._calculateMaxScroll();return scroll>maxScroll?isOverscrollable?maxScroll+Math.round((scroll-maxScroll)*ratio):maxScroll:scroll}options=options||{};var self=this,isOverscrollable=this.isOverscrollable();options.animate?animit(this._getCarouselItemElements()).queue({transform:this._generateScrollTransform(normalizeScroll(scroll))},{duration:.3,timing:"cubic-bezier(.1, .7, .1, 1)"}).play(options.callback):animit(this._getCarouselItemElements()).queue({transform:this._generateScrollTransform(normalizeScroll(scroll))}).play(options.callback)},_calculateMaxScroll:function(){var max=this._getCarouselItemCount()*this._getCarouselItemSize()-this._getElementSize();return 0>max?0:max},_isOverScroll:function(scroll){return 0>scroll||scroll>this._calculateMaxScroll()?!0:!1},_getOverScrollDirection:function(){return this._isVertical()?this._scroll<=0?"up":"down":this._scroll<=0?"left":"right"},_scrollToKillOverScroll:function(){var duration=.4;if(this._scroll<0)return animit(this._getCarouselItemElements()).queue({transform:this._generateScrollTransform(0)},{duration:duration,timing:"cubic-bezier(.1, .4, .1, 1)"}).play(),this._scroll=0,void 0;var maxScroll=this._calculateMaxScroll();return maxScroll<this._scroll?(animit(this._getCarouselItemElements()).queue({transform:this._generateScrollTransform(maxScroll)},{duration:duration,timing:"cubic-bezier(.1, .4, .1, 1)"}).play(),this._scroll=maxScroll,void 0):void 0},_getCarouselItemCount:function(){return this._getCarouselItemElements().length },refresh:function(){if(0!==this._getCarouselItemSize()){if(this._mixin(this._isVertical()?VerticalModeTrait:HorizontalModeTrait),this._layoutCarouselItems(),this._lastState&&this._lastState.width>0){var scroll=this._scroll;this._isOverScroll(scroll)?this._scrollToKillOverScroll():(this.isAutoScrollEnabled()&&(scroll=this._normalizeScrollPosition(scroll)),this._scrollTo(scroll))}this._saveLastState(),this.emit("refresh",{carousel:this})}},first:function(){this.setActiveCarouselItemIndex(0)},last:function(){this.setActiveCarouselItemIndex(Math.max(this._getCarouselItemCount()-1,0))},_destroy:function(){this.emit("destroy",{navigator:this}),this._hammer.off("drag dragleft dragright dragup dragdown swipe swipeleft swiperight swipeup swipedown",this._bindedOnDrag),this._hammer.off("dragend",this._bindedOnDragEnd),angular.element(window).off("resize",this._bindedOnResize),this._element=this._scope=this._attrs=null}});return MicroEvent.mixin(CarouselView),CarouselView}])}(),function(){"use strict";var module=angular.module("onsen");module.factory("DialogView",["$onsen","DialogAnimator","IOSDialogAnimator","AndroidDialogAnimator","SlideDialogAnimator",function($onsen,DialogAnimator,IOSDialogAnimator,AndroidDialogAnimator,SlideDialogAnimator){var DialogView=Class.extend({init:function(scope,element,attrs){if(this._scope=scope,this._element=element,this._element.css("display","none"),this._dialog=angular.element(element[0].querySelector(".dialog")),this._mask=angular.element(element[0].querySelector(".dialog-mask")),this._dialog.css("z-index",20001),this._mask.css("z-index",2e4),this._mask.on("click",this._cancel.bind(this)),this._visible=!1,this._doorLock=new DoorLock,this._animation=DialogView._animatorDict["undefined"!=typeof attrs.animation?attrs.animation:"default"],!this._animation)throw new Error("No such animation: "+attrs.animation);this._deviceBackButtonHandler=$onsen.DeviceBackButtonHandler.create(this._element,this._onDeviceBackButton.bind(this))},getDeviceBackButtonHandler:function(){return this._deviceBackButtonHandler},show:function(options){options=options||{};var cancel=!1,callback=options.callback||function(){};this.emit("preshow",{dialog:this,cancel:function(){cancel=!0}}),cancel||this._doorLock.waitUnlock(function(){var unlock=this._doorLock.lock(),animation=this._animation;this._element.css("display","block"),this._mask.css("opacity",1),options.animation&&(animation=DialogView._animatorDict[options.animation]),animation.show(this,function(){this._visible=!0,unlock(),this.emit("postshow",{dialog:this}),callback()}.bind(this))}.bind(this))},hide:function(options){options=options||{};var cancel=!1,callback=options.callback||function(){};this.emit("prehide",{dialog:this,cancel:function(){cancel=!0}}),cancel||this._doorLock.waitUnlock(function(){var unlock=this._doorLock.lock(),animation=this._animation;options.animation&&(animation=DialogView._animatorDict[options.animation]),animation.hide(this,function(){this._element.css("display","none"),this._visible=!1,unlock(),this.emit("posthide",{dialog:this}),callback()}.bind(this))}.bind(this))},isShown:function(){return this._visible},destroy:function(){this._element.remove(),this._deviceBackButtonHandler.destroy(),this._mask.off(),this._scope.$destroy(),this._deviceBackButtonHandler=this._element=this._dialog=this._mask=null},setDisabled:function(disabled){if("boolean"!=typeof disabled)throw new Error("Argument must be a boolean.");disabled?this._element.attr("disabled",!0):this._element.removeAttr("disabled")},isDisabled:function(){return this._element[0].hasAttribute("disabled")},setCancelable:function(cancelable){if("boolean"!=typeof cancelable)throw new Error("Argument must be a boolean.");cancelable?this._element.attr("cancelable",!0):this._element.removeAttr("cancelable")},isCancelable:function(){return this._element[0].hasAttribute("cancelable")},_cancel:function(){this.isCancelable()&&this.hide({callback:function(){this.emit("cancel")}.bind(this)})},_onDeviceBackButton:function(event){this.isCancelable()?this._cancel.bind(this)():event.callParentHandler()}});return DialogView._animatorDict={"default":$onsen.isAndroid()?new AndroidDialogAnimator:new IOSDialogAnimator,fade:$onsen.isAndroid()?new AndroidDialogAnimator:new IOSDialogAnimator,slide:new SlideDialogAnimator,none:new DialogAnimator},DialogView.registerAnimator=function(name,animator){if(!(animator instanceof DialogAnimator))throw new Error('"animator" param must be an instance of DialogAnimator');this._animatorDict[name]=animator},MicroEvent.mixin(DialogView),DialogView}])}(),function(){"use strict;";var module=angular.module("onsen");module.factory("DialogAnimator",function(){var DialogAnimator=Class.extend({show:function(dialog,callback){callback()},hide:function(dialog,callback){callback()}});return DialogAnimator})}(),function(){"use strict";var module=angular.module("onsen");module.factory("FadePopoverAnimator",["PopoverAnimator",function(PopoverAnimator){var FadePopoverAnimator=PopoverAnimator.extend({timing:"cubic-bezier(.1, .7, .4, 1)",duration:.2,init:function(options){options=options||{},this.timing=options.timing||this.timing,this.duration=void 0!==options.duration?options.duration:this.duration},show:function(popover,callback){var pop=popover._element[0].querySelector(".popover"),mask=popover._element[0].querySelector(".popover-mask");animit.runAll(animit(mask).queue({opacity:0}).queue({opacity:1},{duration:this.duration,timing:this.timing}),animit(pop).queue({transform:"scale3d(1.3, 1.3, 1.0)",opacity:0}).queue({transform:"scale3d(1.0, 1.0, 1.0)",opacity:1},{duration:this.duration,timing:this.timing}).resetStyle().queue(function(done){callback(),done()}))},hide:function(popover,callback){var pop=popover._element[0].querySelector(".popover"),mask=popover._element[0].querySelector(".popover-mask");animit.runAll(animit(mask).queue({opacity:1}).queue({opacity:0},{duration:this.duration,timing:this.timing}),animit(pop).queue({opacity:1}).queue({opacity:0},{duration:this.duration,timing:this.timing}).resetStyle().queue(function(done){callback(),done()}))}});return FadePopoverAnimator}])}(),function(){"use strict;";var module=angular.module("onsen");module.factory("FadeTransitionAnimator",["NavigatorTransitionAnimator",function(NavigatorTransitionAnimator){var FadeTransitionAnimator=NavigatorTransitionAnimator.extend({push:function(enterPage,leavePage,callback){animit.runAll(animit([enterPage.getPageView().getContentElement(),enterPage.getPageView().getBackgroundElement()]).queue({css:{transform:"translate3D(0, 0, 0)",opacity:0},duration:0}).queue({css:{transform:"translate3D(0, 0, 0)",opacity:1},duration:.4,timing:"linear"}).resetStyle().queue(function(done){callback(),done()}),animit(enterPage.getPageView().getToolbarElement()).queue({css:{transform:"translate3D(0, 0, 0)",opacity:0},duration:0}).queue({css:{transform:"translate3D(0, 0, 0)",opacity:1},duration:.4,timing:"linear"}).resetStyle())},pop:function(enterPage,leavePage,callback){animit.runAll(animit([leavePage.getPageView().getContentElement(),leavePage.getPageView().getBackgroundElement()]).queue({css:{transform:"translate3D(0, 0, 0)",opacity:1},duration:0}).queue({css:{transform:"translate3D(0, 0, 0)",opacity:0},duration:.4,timing:"linear"}).queue(function(done){callback(),done()}),animit(leavePage.getPageView().getToolbarElement()).queue({css:{transform:"translate3D(0, 0, 0)",opacity:1},duration:0}).queue({css:{transform:"translate3D(0, 0, 0)",opacity:0},duration:.4,timing:"linear"}))}});return FadeTransitionAnimator}])}(),function(){"use strict";var module=angular.module("onsen");module.factory("GenericView",["$onsen",function(){var GenericView=Class.extend({init:function(scope,element){this._element=element,this._scope=scope}});return MicroEvent.mixin(GenericView),GenericView}])}(),function(){"use strict;";var module=angular.module("onsen");module.factory("IOSAlertDialogAnimator",["DialogAnimator",function(DialogAnimator){var IOSAlertDialogAnimator=DialogAnimator.extend({timing:"cubic-bezier(.1, .7, .4, 1)",duration:.2,init:function(options){options=options||{},this.timing=options.timing||this.timing,this.duration=void 0!==options.duration?options.duration:this.duration},show:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask[0]).queue({opacity:0}).queue({opacity:1},{duration:this.duration,timing:this.timing}),animit(dialog._dialog[0]).queue({css:{transform:"translate3d(-50%, -50%, 0) scale3d(1.3, 1.3, 1.0)",opacity:0},duration:0}).queue({css:{transform:"translate3d(-50%, -50%, 0) scale3d(1.0, 1.0, 1.0)",opacity:1},duration:this.duration,timing:this.timing}).resetStyle().queue(function(done){callback(),done()}))},hide:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask[0]).queue({opacity:1}).queue({opacity:0},{duration:this.duration,timing:this.timing}),animit(dialog._dialog[0]).queue({css:{opacity:1},duration:0}).queue({css:{opacity:0},duration:this.duration,timing:this.timing}).resetStyle().queue(function(done){callback(),done()}))}});return IOSAlertDialogAnimator}])}(),function(){"use strict;";var module=angular.module("onsen");module.factory("IOSDialogAnimator",["DialogAnimator",function(DialogAnimator){var IOSDialogAnimator=DialogAnimator.extend({timing:"ease-in-out",duration:.3,init:function(options){options=options||{},this.timing=options.timing||this.timing,this.duration=void 0!==options.duration?options.duration:this.duration},show:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask[0]).queue({opacity:0}).queue({opacity:1},{duration:this.duration,timing:this.timing}),animit(dialog._dialog[0]).queue({css:{transform:"translate3d(-50%, 300%, 0)"},duration:0}).queue({css:{transform:"translate3d(-50%, -50%, 0)"},duration:this.duration,timing:this.timing}).resetStyle().queue(function(done){callback(),done()}))},hide:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask[0]).queue({opacity:1}).queue({opacity:0},{duration:this.duration,timing:this.timing}),animit(dialog._dialog[0]).queue({css:{transform:"translate3d(-50%, -50%, 0)"},duration:0}).queue({css:{transform:"translate3d(-50%, 300%, 0)"},duration:this.duration,timing:this.timing}).resetStyle().queue(function(done){callback(),done()}))}});return IOSDialogAnimator}])}(),function(){"use strict;";var module=angular.module("onsen");module.factory("IOSSlideTransitionAnimator",["NavigatorTransitionAnimator","PageView",function(NavigatorTransitionAnimator){var IOSSlideTransitionAnimator=NavigatorTransitionAnimator.extend({backgroundMask:angular.element('<div style="position: absolute; width: 100%;height: 100%; background-color: black; opacity: 0;"></div>'),_decompose:function(page){function excludeBackButtonLabel(elements){for(var result=[],i=0;i<elements.length;i++)"ons-back-button"===elements[i].nodeName.toLowerCase()?result.push(elements[i].querySelector(".ons-back-button__icon")):result.push(elements[i]);return result}var left=page.getPageView().getToolbarLeftItemsElement(),right=page.getPageView().getToolbarRightItemsElement(),other=[].concat(0===left.children.length?left:excludeBackButtonLabel(left.children)).concat(0===right.children.length?right:excludeBackButtonLabel(right.children)),pageLabels=[page.getPageView().getToolbarCenterItemsElement(),page.getPageView().getToolbarBackButtonLabelElement()];return{pageLabels:pageLabels,other:other,content:page.getPageView().getContentElement(),background:page.getPageView().getBackgroundElement(),toolbar:page.getPageView().getToolbarElement(),bottomToolbar:page.getPageView().getBottomToolbarElement()}},_shouldAnimateToolbar:function(enterPage,leavePage){var bothPageHasToolbar=enterPage.getPageView().hasToolbarElement()&&leavePage.getPageView().hasToolbarElement(),noAndroidLikeToolbar=!angular.element(enterPage.getPageView().getToolbarElement()).hasClass("navigation-bar--android")&&!angular.element(leavePage.getPageView().getToolbarElement()).hasClass("navigation-bar--android");return bothPageHasToolbar&&noAndroidLikeToolbar},push:function(enterPage,leavePage,callback){var mask=this.backgroundMask.remove();leavePage.element[0].parentNode.insertBefore(mask[0],leavePage.element[0].nextSibling);var enterPageDecomposition=this._decompose(enterPage),leavePageDecomposition=this._decompose(leavePage),delta=function(){var rect=leavePage.element[0].getBoundingClientRect();return Math.round((rect.right-rect.left)/2*.6)}(),maskClear=animit(mask[0]).queue({opacity:0,transform:"translate3d(0, 0, 0)"}).queue({opacity:.1},{duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}).resetStyle().queue(function(done){mask.remove(),done()}),shouldAnimateToolbar=this._shouldAnimateToolbar(enterPage,leavePage);shouldAnimateToolbar?(enterPage.element.css({zIndex:"auto"}),leavePage.element.css({zIndex:"auto"}),animit.runAll(maskClear,animit([enterPageDecomposition.content,enterPageDecomposition.bottomToolbar,enterPageDecomposition.background]).queue({css:{transform:"translate3D(100%, 0px, 0px)"},duration:0}).queue({css:{transform:"translate3D(0px, 0px, 0px)"},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}).resetStyle(),animit(enterPageDecomposition.toolbar).queue({css:{background:"none",backgroundColor:"rgba(0, 0, 0, 0)",borderColor:"rgba(0, 0, 0, 0)"},duration:0}).wait(.3).resetStyle({duration:.1,transition:"background-color 0.1s linear, border-color 0.1s linear"}),animit(enterPageDecomposition.pageLabels).queue({css:{transform:"translate3d("+delta+"px, 0, 0)",opacity:0},duration:0}).queue({css:{transform:"translate3d(0, 0, 0)",opacity:1},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}).resetStyle(),animit(enterPageDecomposition.other).queue({css:{opacity:0},duration:0}).queue({css:{opacity:1},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}).resetStyle(),animit([leavePageDecomposition.content,leavePageDecomposition.bottomToolbar,leavePageDecomposition.background]).queue({css:{transform:"translate3D(0, 0, 0)"},duration:0}).queue({css:{transform:"translate3D(-25%, 0px, 0px)"},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}).resetStyle().queue(function(done){enterPage.element.css({zIndex:""}),leavePage.element.css({zIndex:""}),callback(),done()}),animit(leavePageDecomposition.pageLabels).queue({css:{transform:"translate3d(0, 0, 0)",opacity:1},duration:0}).queue({css:{transform:"translate3d(-"+delta+"px, 0, 0)",opacity:0},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}).resetStyle(),animit(leavePageDecomposition.other).queue({css:{opacity:1},duration:0}).queue({css:{opacity:0},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}).resetStyle())):animit.runAll(maskClear,animit(enterPage.element[0]).queue({css:{transform:"translate3D(100%, 0px, 0px)"},duration:0}).queue({css:{transform:"translate3D(0px, 0px, 0px)"},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}).resetStyle(),animit(leavePage.element[0]).queue({css:{transform:"translate3D(0, 0, 0)"},duration:0}).queue({css:{transform:"translate3D(-25%, 0px, 0px)"},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}).resetStyle().queue(function(done){callback(),done()}))},pop:function(enterPage,leavePage,done){var mask=this.backgroundMask.remove();enterPage.element[0].parentNode.insertBefore(mask[0],enterPage.element[0].nextSibling);var enterPageDecomposition=this._decompose(enterPage),leavePageDecomposition=this._decompose(leavePage),delta=function(){var rect=leavePage.element[0].getBoundingClientRect();return Math.round((rect.right-rect.left)/2*.6)}(),maskClear=animit(mask[0]).queue({opacity:.1,transform:"translate3d(0, 0, 0)"}).queue({opacity:0},{duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}).resetStyle().queue(function(done){mask.remove(),done()}),shouldAnimateToolbar=this._shouldAnimateToolbar(enterPage,leavePage);shouldAnimateToolbar?(enterPage.element.css({zIndex:"auto"}),leavePage.element.css({zIndex:"auto"}),animit.runAll(maskClear,animit([enterPageDecomposition.content,enterPageDecomposition.bottomToolbar,enterPageDecomposition.background]).queue({css:{transform:"translate3D(-25%, 0px, 0px)",opacity:.9},duration:0}).queue({css:{transform:"translate3D(0px, 0px, 0px)",opacity:1},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}).resetStyle(),animit(enterPageDecomposition.pageLabels).queue({css:{transform:"translate3d(-"+delta+"px, 0, 0)",opacity:0},duration:0}).queue({css:{transform:"translate3d(0, 0, 0)",opacity:1},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}).resetStyle(),animit(enterPageDecomposition.toolbar).queue({css:{transform:"translate3d(0, 0, 0)",opacity:1},duration:0}).queue({css:{transform:"translate3d(0, 0, 0)",opacity:1},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}).resetStyle(),animit(enterPageDecomposition.other).queue({css:{opacity:0},duration:0}).queue({css:{opacity:1},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}).resetStyle(),animit([leavePageDecomposition.content,leavePageDecomposition.bottomToolbar,leavePageDecomposition.background]).queue({css:{transform:"translate3D(0px, 0px, 0px)"},duration:0}).queue({css:{transform:"translate3D(100%, 0px, 0px)"},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}).wait(0).queue(function(finish){enterPage.element.css({zIndex:""}),leavePage.element.css({zIndex:""}),done(),finish()}),animit(leavePageDecomposition.other).queue({css:{transform:"translate3d(0, 0, 0)",opacity:1},duration:0}).queue({css:{transform:"translate3d(0, 0, 0)",opacity:0},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}),animit(leavePageDecomposition.toolbar).queue({css:{background:"none",backgroundColor:"rgba(0, 0, 0, 0)",borderColor:"rgba(0, 0, 0, 0)"},duration:0}),animit(leavePageDecomposition.pageLabels).queue({css:{transform:"translate3d(0, 0, 0)",opacity:1},duration:0}).queue({css:{transform:"translate3d("+delta+"px, 0, 0)",opacity:0},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}))):animit.runAll(maskClear,animit(enterPage.element[0]).queue({css:{transform:"translate3D(-25%, 0px, 0px)",opacity:.9},duration:0}).queue({css:{transform:"translate3D(0px, 0px, 0px)",opacity:1},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}).resetStyle(),animit(leavePage.element[0]).queue({css:{transform:"translate3D(0px, 0px, 0px)"},duration:0}).queue({css:{transform:"translate3D(100%, 0px, 0px)"},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}).queue(function(finish){done(),finish()}))}});return IOSSlideTransitionAnimator}])}(),function(){"use strict";var module=angular.module("onsen");module.factory("LazyRepeatView",["$onsen","$document","$compile",function($onsen,$document,$compile){var LazyRepeatView=Class.extend({init:function(scope,element,attrs,linker){this._element=element,this._scope=scope,this._attrs=attrs,this._linker=linker,this._parentElement=element.parent(),this._itemHeightSum=[],this._maxIndex=0,this._doorLock=new DoorLock,this._delegate=this._getDelegate(),this._renderedElements={},this._addEventListeners(),this._scope.$watch(function(){this._render()}.bind(this)),this._scope.$on("$destroy",this._destroy.bind(this)),this._onChange()},_getDelegate:function(){var delegate=this._scope.$eval(this._attrs.onsLazyRepeat);return"undefined"==typeof delegate&&(delegate=eval(this._attrs.onsLazyRepeat)),delegate},_countItems:function(){return this._delegate.countItems()},_getItemHeight:function(i){return this._delegate.calculateItemHeight(i)},_getTopOffset:function(){return this._parentElement[0].getBoundingClientRect().top},_render:function(){var items=this._getItemsInView(),keep={};this._parentElement.css("height",this._itemHeightSum[this._maxIndex]+"px");for(var i=0,l=items.length;l>i;i++){var _item=items[i];this._renderElement(_item),keep[_item.index]=!0}for(var key in this._renderedElements)this._renderedElements.hasOwnProperty(key)&&!keep.hasOwnProperty(key)&&this._removeElement(key)},_isRendered:function(i){return this._renderedElements.hasOwnProperty(i)},_renderElement:function(item){if(this._isRendered(item.index)){var currentItem=this._renderedElements[item.index];if(this._delegate.configureItemScope)this._delegate.configureItemScope(item.index,currentItem.scope);else if(this._delegate.createItemContent){var oldContent=currentItem.element.children(),newContent=angular.element(this._delegate.createItemContent(item.index,oldContent[0]));newContent.html()!==oldContent.html()&&(currentItem.element.append(newContent),oldContent.remove())}}else{var childScope=this._scope.$new();this._addSpecialProperties(item.index,childScope),this._linker(childScope,function(clone){this._delegate.configureItemScope?this._delegate.configureItemScope(item.index,childScope):this._delegate.createItemContent&&clone.append(this._delegate.createItemContent(item.index)),this._parentElement.append(clone),clone.removeAttr("ons-lazy-repeat"),clone.css({position:"absolute",top:item.top+"px",left:"0px",right:"0px",display:"none"});var element={element:clone,scope:childScope};$compile(clone)(childScope),this._scope.$evalAsync(function(){clone.css("display","block")}),this._renderedElements[item.index]=element}.bind(this))}},_removeElement:function(i){if(this._isRendered(i)){var element=this._renderedElements[i];this._delegate.destroyItemScope?this._delegate.destroyItemScope(i,element.scope):this._delegate.destroyItemContent&&this._delegate.destroyItemContent(i,element.element.children()[0]),element.element.remove(),element.scope.$destroy(),element.element=element.scope=null,delete this._renderedElements[i]}},_removeAllElements:function(){for(var key in this._renderedElements)this._removeElement.hasOwnProperty(key)&&this._removeElement(key)},_calculateStartIndex:function(current){for(var start=0,end=this._maxIndex;;){var middle=Math.floor((start+end)/2),value=current+this._itemHeightSum[middle];if(start>end)return 0;if(value>=0&&value-this._getItemHeight(middle)<0)return middle;isNaN(value)||value>=0?end=middle-1:start=middle+1}},_getItemsInView:function(){var topOffset=this._getTopOffset(),topPosition=topOffset,cnt=this._countItems(),startIndex=this._calculateStartIndex(topPosition);startIndex=Math.max(startIndex-30,0),startIndex>0&&(topPosition+=this._itemHeightSum[startIndex-1]);for(var items=[],i=startIndex;cnt>i&&topPosition<4*window.innerHeight;i++){var h=this._getItemHeight();i>=this._itemHeightSum.length&&(this._itemHeightSum=this._itemHeightSum.concat(new Array(100))),this._itemHeightSum[i]=i>0?this._itemHeightSum[i-1]+h:h,this._maxIndex=Math.max(i,this._maxIndex),items.push({index:i,top:topPosition-topOffset}),topPosition+=h}return items},_addSpecialProperties:function(i,scope){scope.$index=i,scope.$first=0===i,scope.$last=i===this._countItems()-1,scope.$middle=!scope.$first&&!scope.$last,scope.$even=i%2===0,scope.$odd=!scope.$even},_onChange:function(){this._doorLock._waitList.length>0||this._doorLock.waitUnlock(function(){var unlock=this._doorLock.lock();setTimeout(function(){unlock()},200),this._render()}.bind(this))},_addEventListeners:function(){this._bindedOnChange=this._onChange.bind(this),$document[0].addEventListener("scroll",this._bindedOnChange,!0),$document[0].addEventListener("resize",this._bindedOnChange,!0)},_removeEventListeners:function(){$document[0].removeEventListener("scroll",this._bindedOnChange,!0),$document[0].removeEventListener("resize",this._bindedOnChange,!0)},_destroy:function(){this._removeEventListeners(),this._removeAllElements(),this._parentElement=this._renderedElements=this._element=this._scope=this._attrs=null}});return LazyRepeatView}])}(),function(){"use strict;";var module=angular.module("onsen");module.factory("LiftTransitionAnimator",["NavigatorTransitionAnimator",function(NavigatorTransitionAnimator){var LiftTransitionAnimator=NavigatorTransitionAnimator.extend({backgroundMask:angular.element('<div style="position: absolute; width: 100%;height: 100%; background-color: black;"></div>'),push:function(enterPage,leavePage,callback){var mask=this.backgroundMask.remove();leavePage.element[0].parentNode.insertBefore(mask[0],leavePage.element[0]);var maskClear=animit(mask[0]).wait(.6).queue(function(done){mask.remove(),done()});animit.runAll(maskClear,animit(enterPage.element[0]).queue({css:{transform:"translate3D(0, 100%, 0)"},duration:0}).queue({css:{transform:"translate3D(0, 0, 0)"},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}).wait(.2).resetStyle().queue(function(done){callback(),done()}),animit(leavePage.element[0]).queue({css:{transform:"translate3D(0, 0, 0)",opacity:1},duration:0}).queue({css:{transform:"translate3D(0, -10%, 0)",opacity:.9},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}))},pop:function(enterPage,leavePage,callback){var mask=this.backgroundMask.remove();enterPage.element[0].parentNode.insertBefore(mask[0],enterPage.element[0]),animit.runAll(animit(mask[0]).wait(.4).queue(function(done){mask.remove(),done()}),animit(enterPage.element[0]).queue({css:{transform:"translate3D(0, -10%, 0)",opacity:.9},duration:0}).queue({css:{transform:"translate3D(0, 0, 0)",opacity:1},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}).resetStyle().wait(.4).queue(function(done){callback(),done()}),animit(leavePage.element[0]).queue({css:{transform:"translate3D(0, 0, 0)"},duration:0}).queue({css:{transform:"translate3D(0, 100%, 0)"},duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)"}))}});return LiftTransitionAnimator}])}(),function(){"use strict;";var module=angular.module("onsen");module.factory("ModalView",["$onsen","$rootScope",function($onsen,$rootScope){var ModalView=Class.extend({_element:void 0,_scope:void 0,init:function(scope,element){this._scope=scope,this._element=element;var pageView=$rootScope.ons.findParentComponentUntil("ons-page",this._element);pageView&&(this._pageContent=angular.element(pageView._element[0].querySelector(".page__content"))),this._scope.$on("$destroy",this._destroy.bind(this)),this._deviceBackButtonHandler=$onsen.DeviceBackButtonHandler.create(this._element,this._onDeviceBackButton.bind(this)),this.hide()},getDeviceBackButtonHandler:function(){return this._deviceBackButtonHandler},show:function(){this._element.css("display","table")},_isVisible:function(){return this._element[0].clientWidth>0},_onDeviceBackButton:function(){},hide:function(){this._element.css("display","none")},toggle:function(){return this._isVisible()?this.hide.apply(this,arguments):this.show.apply(this,arguments)},_destroy:function(){this.emit("destroy",{page:this}),this._deviceBackButtonHandler.destroy(),this._element=this._scope=null}});return MicroEvent.mixin(ModalView),ModalView}])}(),function(){"use strict;";var module=angular.module("onsen"),NavigatorPageObject=Class.extend({init:function(params){this.page=params.page,this.name=params.page,this.element=params.element,this.pageScope=params.pageScope,this.options=params.options,this.navigator=params.navigator},getPageView:function(){if(!this._pageView&&(this._pageView=this.element.inheritedData("ons-page"),!this._pageView))throw new Error("Fail to fetch PageView from ons-page element.");return this._pageView},destroy:function(){this.pageScope.$destroy(),this.element.remove(),this._pageView=null,this.element=null,this.pageScope=null,this.options=null;var index=this.navigator.pages.indexOf(this);-1!==index&&this.navigator.pages.splice(index,1),this.navigator=null}});module.factory("NavigatorView",["$http","$parse","$templateCache","$compile","$onsen","$timeout","SimpleSlideTransitionAnimator","NavigatorTransitionAnimator","LiftTransitionAnimator","NullTransitionAnimator","IOSSlideTransitionAnimator","FadeTransitionAnimator",function($http,$parse,$templateCache,$compile,$onsen,$timeout,SimpleSlideTransitionAnimator,NavigatorTransitionAnimator,LiftTransitionAnimator,NullTransitionAnimator,IOSSlideTransitionAnimator,FadeTransitionAnimator){var NavigatorView=Class.extend({_element:void 0,pages:void 0,_scope:void 0,_doorLock:void 0,_profiling:!1,init:function(options){options=options||options,this._element=options.element||angular.element(window.document.body),this._scope=options.scope||this._element.scope(),this._doorLock=new DoorLock,this.pages=[],this._deviceBackButtonHandler=$onsen.DeviceBackButtonHandler.create(this._element,this._onDeviceBackButton.bind(this)),this._scope.$on("$destroy",this._destroy.bind(this))},_destroy:function(){this.emit("destroy",{navigator:this}),this.pages.forEach(function(page){page.destroy()}),this._deviceBackButtonHandler.destroy(),this._deviceBackButtonHandler=null},_onDeviceBackButton:function(event){this.pages.length>1?this.popPage():event.callParentHandler()},_normalizePageElement:function(element){for(var i=0;i<element.length;i++)if(1===element[i].nodeType)return angular.element(element[i]);throw new Error("invalid state")},_createPageElementAndLinkFunction:function(templateHTML,pageScope){function safeApply(scope){var phase=scope.$root.$$phase;"$apply"!==phase&&"$digest"!==phase&&scope.$apply()}var div=document.createElement("div");div.innerHTML=templateHTML.trim();var pageElement=angular.element(div),hasPage=1===div.childElementCount&&"ons-page"===div.childNodes[0].nodeName.toLowerCase();if(!hasPage)throw new Error('You can not supply no "ons-page" element to "ons-navigator".');pageElement=angular.element(div.childNodes[0]);var link=$compile(pageElement);return{element:pageElement,link:function(){link(pageScope),safeApply(pageScope)}}},insertPage:function(index,page,options){if(options=options||{},options&&"object"!=typeof options)throw new Error("options must be an object. You supplied "+options);if(0===this.pages.length)return this.pushPage.apply(this,arguments);this._doorLock.waitUnlock(function(){var unlock=this._doorLock.lock();$onsen.getPageHTMLAsync(page).then(function(templateHTML){var pageScope=this._createPageScope(),object=this._createPageElementAndLinkFunction(templateHTML,pageScope),element=object.element,link=object.link;element=this._normalizePageElement(element);var pageObject=this._createPageObject(page,element,pageScope,options);this.pages.length>0?(index=normalizeIndex(index),this._element[0].insertBefore(element[0],this.pages[index]?this.pages[index].element[0]:null),this.pages.splice(index,0,pageObject),link(),setTimeout(function(){this.getCurrentPage()!==pageObject&&element.css("display","none"),unlock(),element=null}.bind(this),1e3/60)):(this._element.append(element),this.pages.push(pageObject),link(),unlock(),element=null)}.bind(this),function(){throw unlock(),new Error("Page is not found: "+page)})}.bind(this));var normalizeIndex=function(index){return 0>index&&(index=this.pages.length+index),index}.bind(this)},pushPage:function(page,options){if(this._profiling&&console.time("pushPage"),options=options||{},options&&"object"!=typeof options)throw new Error("options must be an object. You supplied "+options);this._emitPrePushEvent()||this._doorLock.waitUnlock(function(){this._pushPage(page,options)}.bind(this))},_pushPage:function(page,options){var unlock=this._doorLock.lock(),done=function(){unlock(),this._profiling&&console.timeEnd("pushPage")};$onsen.getPageHTMLAsync(page).then(function(templateHTML){var pageScope=this._createPageScope(),object=this._createPageElementAndLinkFunction(templateHTML,pageScope);setImmediate(function(){this._pushPageDOM(page,object.element,object.link,pageScope,options,done),object=null}.bind(this))}.bind(this),function(){throw done(),new Error("Page is not found: "+page)}.bind(this))},getDeviceBackButtonHandler:function(){return this._deviceBackButtonHandler},_getAnimatorOption:function(options){var animator=null;if(options.animation instanceof NavigatorTransitionAnimator)return options.animation;if("string"==typeof options.animation&&(animator=NavigatorView._transitionAnimatorDict[options.animation]),!animator&&this._element.attr("animation")&&(animator=NavigatorView._transitionAnimatorDict[this._element.attr("animation")]),animator||(animator=NavigatorView._transitionAnimatorDict["default"]),!(animator instanceof NavigatorTransitionAnimator))throw new Error('"animator" is not an instance of NavigatorTransitionAnimator.');return animator},_createPageScope:function(){return this._scope.$new() },_createPageObject:function(page,element,pageScope,options){return options.animator=this._getAnimatorOption(options),new NavigatorPageObject({page:page,element:element,pageScope:pageScope,options:options,navigator:this})},_pushPageDOM:function(page,element,link,pageScope,options,unlock){this._profiling&&console.time("pushPageDOM"),unlock=unlock||function(){},options=options||{},element=this._normalizePageElement(element);var pageObject=this._createPageObject(page,element,pageScope,options),event={enterPage:pageObject,leavePage:this.pages[this.pages.length-1],navigator:this};this.pages.push(pageObject);var done=function(){this.pages[this.pages.length-2]&&this.pages[this.pages.length-2].element.css("display","none"),this._profiling&&console.timeEnd("pushPageDOM"),unlock(),this.emit("postpush",event),"function"==typeof options.onTransitionEnd&&options.onTransitionEnd(),element=null}.bind(this);if(this.pages.length>1){var leavePage=this.pages.slice(-2)[0],enterPage=this.pages.slice(-1)[0];this._element.append(element),link(),options.animator.push(enterPage,leavePage,done),element=null}else this._element.append(element),link(),done(),element=null},_emitPrePushEvent:function(){var isCanceled=!1,prePushEvent={navigator:this,currentPage:this.getCurrentPage(),cancel:function(){isCanceled=!0}};return this.emit("prepush",prePushEvent),isCanceled},_emitPrePopEvent:function(){var isCanceled=!1,prePopEvent={navigator:this,currentPage:this.getCurrentPage(),cancel:function(){isCanceled=!0}};return this.emit("prepop",prePopEvent),isCanceled},popPage:function(options){options=options||{},this._doorLock.waitUnlock(function(){if(this.pages.length<=1)throw new Error("NavigatorView's page stack is empty.");this._emitPrePopEvent()||this._popPage(options)}.bind(this))},_popPage:function(options){var unlock=this._doorLock.lock(),leavePage=this.pages.pop();this.pages[this.pages.length-1]&&this.pages[this.pages.length-1].element.css("display","block");var enterPage=this.pages[this.pages.length-1],event={leavePage:leavePage,enterPage:this.pages[this.pages.length-1],navigator:this},callback=function(){leavePage.destroy(),unlock(),this.emit("postpop",event),event.leavePage=null,"function"==typeof options.onTransitionEnd&&options.onTransitionEnd()}.bind(this);leavePage.options.animator.pop(enterPage,leavePage,callback)},resetToPage:function(page,options){options=options||{},options.animator||options.animation||(options.animation="none");var onTransitionEnd=options.onTransitionEnd||function(){},self=this;options.onTransitionEnd=function(){for(;self.pages.length>1;)self.pages.shift().destroy();onTransitionEnd()},this.pushPage(page,options)},getCurrentPage:function(){return this.pages[this.pages.length-1]},getPages:function(){return this.pages},canPopPage:function(){return this.pages.length>1}});return NavigatorView._transitionAnimatorDict={"default":$onsen.isAndroid()?new SimpleSlideTransitionAnimator:new IOSSlideTransitionAnimator,slide:$onsen.isAndroid()?new SimpleSlideTransitionAnimator:new IOSSlideTransitionAnimator,simpleslide:new SimpleSlideTransitionAnimator,lift:new LiftTransitionAnimator,fade:new FadeTransitionAnimator,none:new NullTransitionAnimator},NavigatorView.registerTransitionAnimator=function(name,animator){if(!(animator instanceof NavigatorTransitionAnimator))throw new Error('"animator" param must be an instance of NavigatorTransitionAnimator');this._transitionAnimatorDict[name]=animator},MicroEvent.mixin(NavigatorView),NavigatorView}])}(),function(){"use strict;";var module=angular.module("onsen");module.factory("NavigatorTransitionAnimator",function(){var NavigatorTransitionAnimator=Class.extend({push:function(enterPage,leavePage,callback){callback()},pop:function(enterPage,leavePage,callback){callback()}});return NavigatorTransitionAnimator})}(),function(){"use strict;";var module=angular.module("onsen");module.factory("NullTransitionAnimator",["NavigatorTransitionAnimator",function(NavigatorTransitionAnimator){var NullTransitionAnimator=NavigatorTransitionAnimator.extend({});return NullTransitionAnimator}])}(),function(){"use strict";var module=angular.module("onsen");module.factory("OverlaySlidingMenuAnimator",["SlidingMenuAnimator",function(SlidingMenuAnimator){var OverlaySlidingMenuAnimator=SlidingMenuAnimator.extend({_blackMask:void 0,_isRight:!1,_element:!1,_menuPage:!1,_mainPage:!1,_width:!1,_duration:!1,setup:function(element,mainPage,menuPage,options){options=options||{},this._width=options.width||"90%",this._isRight=!!options.isRight,this._element=element,this._mainPage=mainPage,this._menuPage=menuPage,this._duration=.4,menuPage.css("box-shadow","0px 0 10px 0px rgba(0, 0, 0, 0.2)"),menuPage.css({width:options.width,display:"none",zIndex:2}),mainPage.css({zIndex:1}),this._isRight?menuPage.css({right:"-"+options.width,left:"auto"}):menuPage.css({right:"auto",left:"-"+options.width}),this._blackMask=angular.element("<div></div>").css({backgroundColor:"black",top:"0px",left:"0px",right:"0px",bottom:"0px",position:"absolute",display:"none",zIndex:0}),element.prepend(this._blackMask)},onResized:function(options){if(this._menuPage.css("width",options.width),this._isRight?this._menuPage.css({right:"-"+options.width,left:"auto"}):this._menuPage.css({right:"auto",left:"-"+options.width}),options.isOpened){var max=this._menuPage[0].clientWidth,menuStyle=this._generateMenuPageStyle(max);animit(this._menuPage[0]).queue(menuStyle).play()}},destroy:function(){this._blackMask&&(this._blackMask.remove(),this._blackMask=null),this._mainPage.removeAttr("style"),this._menuPage.removeAttr("style"),this._element=this._mainPage=this._menuPage=null},openMenu:function(callback,instant){var duration=instant===!0?0:this._duration;this._menuPage.css("display","block"),this._blackMask.css("display","block");var max=this._menuPage[0].clientWidth,menuStyle=this._generateMenuPageStyle(max),mainPageStyle=this._generateMainPageStyle(max);setTimeout(function(){animit(this._mainPage[0]).queue(mainPageStyle,{duration:duration,timing:"cubic-bezier(.1, .7, .1, 1)"}).queue(function(done){callback(),done()}).play(),animit(this._menuPage[0]).queue(menuStyle,{duration:duration,timing:"cubic-bezier(.1, .7, .1, 1)"}).play()}.bind(this),1e3/60)},closeMenu:function(callback,instant){var duration=instant===!0?0:this._duration;this._blackMask.css({display:"block"});var menuPageStyle=this._generateMenuPageStyle(0),mainPageStyle=this._generateMainPageStyle(0);setTimeout(function(){animit(this._mainPage[0]).queue(mainPageStyle,{duration:duration,timing:"cubic-bezier(.1, .7, .1, 1)"}).queue(function(done){this._menuPage.css("display","none"),callback(),done()}.bind(this)).play(),animit(this._menuPage[0]).queue(menuPageStyle,{duration:duration,timing:"cubic-bezier(.1, .7, .1, 1)"}).play()}.bind(this),1e3/60)},translateMenu:function(options){this._menuPage.css("display","block"),this._blackMask.css({display:"block"});var menuPageStyle=this._generateMenuPageStyle(Math.min(options.maxDistance,options.distance)),mainPageStyle=this._generateMainPageStyle(Math.min(options.maxDistance,options.distance));delete mainPageStyle.opacity,animit(this._menuPage[0]).queue(menuPageStyle).play(),Object.keys(mainPageStyle).length>0&&animit(this._mainPage[0]).queue(mainPageStyle).play()},_generateMenuPageStyle:function(distance){var x=(this._menuPage[0].clientWidth,this._isRight?-distance:distance),transform="translate3d("+x+"px, 0, 0)";return{transform:transform,"box-shadow":0===distance?"none":"0px 0 10px 0px rgba(0, 0, 0, 0.2)"}},_generateMainPageStyle:function(distance){var max=this._menuPage[0].clientWidth,opacity=1-.1*distance/max;return{opacity:opacity}},copy:function(){return new OverlaySlidingMenuAnimator}});return OverlaySlidingMenuAnimator}])}(),function(){"use strict;";var module=angular.module("onsen");module.factory("PageView",["$onsen","$parse",function($onsen,$parse){var PageView=Class.extend({_registeredToolbarElement:!1,_registeredBottomToolbarElement:!1,_nullElement:window.document.createElement("div"),_toolbarElement:null,_bottomToolbarElement:null,init:function(scope,element,attrs){this._scope=scope,this._element=element,this._attrs=attrs,this._registeredToolbarElement=!1,this._registeredBottomToolbarElement=!1,this._nullElement=window.document.createElement("div"),this._toolbarElement=angular.element(this._nullElement),this._bottomToolbarElement=angular.element(this._nullElement),this._clearListener=scope.$on("$destroy",this._destroy.bind(this)),this._userDeviceBackButtonListener=angular.noop,(this._attrs.ngDeviceBackbutton||this._attrs.onDeviceBackbutton)&&(this._deviceBackButtonHandler=$onsen.DeviceBackButtonHandler.create(this._element,this._onDeviceBackButton.bind(this)))},_onDeviceBackButton:function($event){if(this._userDeviceBackButtonListener($event),this._attrs.ngDeviceBackbutton&&$parse(this._attrs.ngDeviceBackbutton)(this._scope,{$event:$event}),this._attrs.onDeviceBackbutton){var lastEvent=window.$event;window.$event=$event,new Function(this._attrs.onDeviceBackbutton)(),window.$event=lastEvent}},setDeviceBackButtonHandler:function(callback){this._deviceBackButtonHandler||(this._deviceBackButtonHandler=$onsen.DeviceBackButtonHandler.create(this._element,this._onDeviceBackButton.bind(this))),this._userDeviceBackButtonListener=callback},getDeviceBackButtonHandler:function(){return this._deviceBackButtonHandler||null},registerToolbar:function(element){if(this._registeredToolbarElement)throw new Error("This page's toolbar is already registered.");angular.element(this.getContentElement()).attr("no-status-bar-fill",""),element.remove();var statusFill=this._element[0].querySelector(".page__status-bar-fill");statusFill?angular.element(statusFill).after(element):this._element.prepend(element),this._toolbarElement=element,this._registeredToolbarElement=!0},registerBottomToolbar:function(element){if(this._registeredBottomToolbarElement)throw new Error("This page's bottom-toolbar is already registered.");element.remove(),this._bottomToolbarElement=element,this._registeredBottomToolbarElement=!0;var fill=angular.element(document.createElement("div"));fill.addClass("page__bottom-bar-fill"),fill.css({width:"0px",height:"0px"}),this._element.prepend(fill),this._element.append(element)},registerExtraElement:function(element){this._extraElement||(this._extraElement=angular.element("<div></div>"),this._extraElement.addClass("page__extra"),this._extraElement.css({"z-index":"10001"}),this._element.append(this._extraElement)),this._extraElement.append(element.remove())},hasToolbarElement:function(){return!!this._registeredToolbarElement},hasBottomToolbarElement:function(){return!!this._registeredBottomToolbarElement},getContentElement:function(){for(var i=0;i<this._element.length;i++)if(this._element[i].querySelector){var content=this._element[i].querySelector(".page__content");if(content)return content}throw Error('fail to get ".page__content" element.')},getBackgroundElement:function(){for(var i=0;i<this._element.length;i++)if(this._element[i].querySelector){var content=this._element[i].querySelector(".page__background");if(content)return content}throw Error('fail to get ".page__background" element.')},getToolbarElement:function(){return this._toolbarElement[0]||this._nullElement},getBottomToolbarElement:function(){return this._bottomToolbarElement[0]||this._nullElement},getToolbarLeftItemsElement:function(){return this._toolbarElement[0].querySelector(".left")||this._nullElement},getToolbarCenterItemsElement:function(){return this._toolbarElement[0].querySelector(".center")||this._nullElement},getToolbarRightItemsElement:function(){return this._toolbarElement[0].querySelector(".right")||this._nullElement},getToolbarBackButtonLabelElement:function(){return this._toolbarElement[0].querySelector("ons-back-button .back-button__label")||this._nullElement},_destroy:function(){this.emit("destroy",{page:this}),this._deviceBackButtonHandler&&(this._deviceBackButtonHandler.destroy(),this._deviceBackButtonHandler=null),this._element=null,this._toolbarElement=null,this._nullElement=null,this._bottomToolbarElement=null,this._extraElement=null,this._scope=null,this._clearListener()}});return MicroEvent.mixin(PageView),PageView}])}(),function(){"use strict";var module=angular.module("onsen");module.factory("PopoverView",["$onsen","PopoverAnimator","FadePopoverAnimator",function($onsen,PopoverAnimator,FadePopoverAnimator){var PopoverView=Class.extend({init:function(scope,element,attrs){if(this._element=element,this._scope=scope,this._mask=angular.element(this._element[0].querySelector(".popover-mask")),this._popover=angular.element(this._element[0].querySelector(".popover")),this._mask.css("z-index",2e4),this._popover.css("z-index",20001),this._element.css("display","none"),attrs.maskColor&&this._mask.css("background-color",attrs.maskColor),this._mask.on("click",this._cancel.bind(this)),this._visible=!1,this._doorLock=new DoorLock,this._animation=PopoverView._animatorDict["undefined"!=typeof attrs.animation?attrs.animation:"fade"],!this._animation)throw new Error("No such animation: "+attrs.animation);this._deviceBackButtonHandler=$onsen.DeviceBackButtonHandler.create(this._element,this._onDeviceBackButton.bind(this)),this._onChange=function(){setImmediate(function(){this._currentTarget&&this._positionPopover(this._currentTarget)}.bind(this))}.bind(this),this._popover[0].addEventListener("DOMNodeInserted",this._onChange,!1),this._popover[0].addEventListener("DOMNodeRemoved",this._onChange,!1),window.addEventListener("resize",this._onChange,!1)},_onDeviceBackButton:function(event){this.isCancelable()?this._cancel.bind(this)():event.callParentHandler()},_setDirection:function(direction){if("up"===direction)this._scope.direction=direction,this._scope.arrowPosition="bottom";else if("left"===direction)this._scope.direction=direction,this._scope.arrowPosition="right";else if("down"===direction)this._scope.direction=direction,this._scope.arrowPosition="top";else{if("right"!=direction)throw new Error("Invalid direction.");this._scope.direction=direction,this._scope.arrowPosition="left"}this._scope.$$phase||this._scope.$apply()},_positionPopoverByDirection:function(target,direction){var el=angular.element(this._element[0].querySelector(".popover")),pos=target.getBoundingClientRect(),own=el[0].getBoundingClientRect(),arrow=angular.element(el.children()[1]),offset=14,margin=6,radius=parseInt(window.getComputedStyle(el[0].querySelector(".popover__content")).borderRadius);arrow.css({top:"",left:""});var diff=function(x){return x/2*Math.sqrt(2)-x/2}(parseInt(window.getComputedStyle(arrow[0]).width)),limit=margin+radius+diff;this._setDirection(direction),["left","right"].indexOf(direction)>-1?("left"==direction?el.css("left",pos.right-pos.width-own.width-offset+"px"):el.css("left",pos.right+offset+"px"),el.css("top",pos.bottom-pos.height/2-own.height/2+"px")):("up"==direction?el.css("top",pos.bottom-pos.height-own.height-offset+"px"):el.css("top",pos.bottom+offset+"px"),el.css("left",pos.right-pos.width/2-own.width/2+"px")),own=el[0].getBoundingClientRect(),["left","right"].indexOf(direction)>-1?own.top<margin?(arrow.css("top",Math.max(own.height/2+own.top-margin,limit)+"px"),el.css("top",margin+"px")):own.bottom>window.innerHeight-margin&&(arrow.css("top",Math.min(own.height/2-(window.innerHeight-own.bottom)+margin,own.height-limit)+"px"),el.css("top",window.innerHeight-own.height-margin+"px")):own.left<margin?(arrow.css("left",Math.max(own.width/2+own.left-margin,limit)+"px"),el.css("left",margin+"px")):own.right>window.innerWidth-margin&&(arrow.css("left",Math.min(own.width/2-(window.innerWidth-own.right)+margin,own.width-limit)+"px"),el.css("left",window.innerWidth-own.width-margin+"px"))},_positionPopover:function(target){var directions;directions=this._element.attr("direction")?this._element.attr("direction").split(/\s+/):["up","down","left","right"];for(var position=target.getBoundingClientRect(),scores={left:position.left,right:window.innerWidth-position.right,up:position.top,down:window.innerHeight-position.bottom},orderedDirections=Object.keys(scores).sort(function(a,b){return-(scores[a]-scores[b])}),i=0,l=orderedDirections.length;l>i;i++){var direction=orderedDirections[i];if(directions.indexOf(direction)>-1)return this._positionPopoverByDirection(target,direction),void 0}},show:function(target,options){if("string"==typeof target?target=document.querySelector(target):target instanceof Event&&(target=target.target),!target)throw new Error("Target undefined");options=options||{};var cancel=!1;this.emit("preshow",{popover:this,cancel:function(){cancel=!0}}),cancel||this._doorLock.waitUnlock(function(){var unlock=this._doorLock.lock(),animation=this._animation;this._element.css("display","block"),this._currentTarget=target,this._positionPopover(target),options.animation&&(animation=PopoverView._animatorDict[options.animation]),animation.show(this,function(){this._visible=!0,this._positionPopover(target),unlock(),this.emit("postshow",{popover:this})}.bind(this))}.bind(this))},hide:function(options){options=options||{};var cancel=!1;this.emit("prehide",{popover:this,cancel:function(){cancel=!0}}),cancel||this._doorLock.waitUnlock(function(){var unlock=this._doorLock.lock(),animation=this._animation;options.animation&&(animation=PopoverView._animatorDict[options.animation]),animation.hide(this,function(){this._element.css("display","none"),this._visible=!1,unlock(),this.emit("posthide",{popover:this})}.bind(this))}.bind(this))},isShown:function(){return this._visible},destroy:function(){this._scope.$destroy(),this._mask.off(),this._mask.remove(),this._popover.remove(),this._element.remove(),this._deviceBackButtonHandler.destroy(),this._popover[0].removeEventListener("DOMNodeInserted",this._onChange,!1),this._popover[0].removeEventListener("DOMNodeRemoved",this._onChange,!1),window.removeEventListener("resize",this._onChange,!1),this._onChange=this._deviceBackButtonHandler=this._mask=this._popover=this._element=this._scope=null},setCancelable:function(cancelable){if("boolean"!=typeof cancelable)throw new Error("Argument must be a boolean.");cancelable?this._element.attr("cancelable",!0):this._element.removeAttr("cancelable")},isCancelable:function(){return this._element[0].hasAttribute("cancelable")},_cancel:function(){this.isCancelable()&&this.hide()}});return PopoverView._animatorDict={fade:new FadePopoverAnimator,none:new PopoverAnimator},PopoverView.registerAnimator=function(name,animator){if(!(animator instanceof PopoverAnimator))throw new Error('"animator" param must be an instance of PopoverAnimator');this._animatorDict[name]=animator},MicroEvent.mixin(PopoverView),PopoverView}])}(),function(){"use strict";var module=angular.module("onsen");module.factory("PopoverAnimator",function(){var PopoverAnimator=Class.extend({show:function(popover,callback){callback()},hide:function(popover,callback){callback()}});return PopoverAnimator})}(),function(){"use strict";var module=angular.module("onsen");module.factory("PullHookView",["$onsen","$parse",function($onsen,$parse){var PullHookView=Class.extend({STATE_INITIAL:"initial",STATE_PREACTION:"preaction",STATE_ACTION:"action",init:function(scope,element,attrs){if(this._element=element,this._scope=scope,this._attrs=attrs,this._scrollElement=this._createScrollElement(),this._pageElement=this._scrollElement.parent(),!this._pageElement.hasClass("page__content")&&!this._pageElement.hasClass("ons-scroller__content"))throw new Error("<ons-pull-hook> must be a direct descendant of an <ons-page> or an <ons-scroller> element.");this._currentTranslation=0,this._createEventListeners(),this._setState(this.STATE_INITIAL,!0),this._setStyle(),this._scope.$on("$destroy",this._destroy.bind(this))},_createScrollElement:function(){var scrollElement=angular.element("<div>").addClass("scroll"),pageElement=this._element.parent(),children=pageElement.children();return pageElement.append(scrollElement),scrollElement.append(children),scrollElement},_setStyle:function(){var h=this._getHeight();this._element.css({top:"-"+h+"px",height:h+"px",lineHeight:h+"px"})},_onScroll:function(){var el=this._pageElement[0];el.scrollTop<0&&(el.scrollTop=0)},_generateTranslationTransform:function(scroll){return"translate3d(0px, "+scroll+"px, 0px)"},_onDrag:function(event){if(!this.isDisabled()&&"left"!==event.gesture.direction&&"right"!==event.gesture.direction){var el=this._pageElement[0];if(el.scrollTop=this._startScroll-event.gesture.deltaY,el.scrollTop<window.innerHeight&&"up"!==event.gesture.direction&&event.gesture.preventDefault(),0===this._currentTranslation&&0===this._getCurrentScroll()){this._transitionDragLength=event.gesture.deltaY;var direction=event.gesture.interimDirection;"down"===direction?this._transitionDragLength-=1:this._transitionDragLength+=1}var scroll=event.gesture.deltaY-this._startScroll;scroll=Math.max(scroll,0),this._thresholdHeightEnabled()&&scroll>=this._getThresholdHeight()?(event.gesture.stopDetect(),setImmediate(function(){this._setState(this.STATE_ACTION),this._translateTo(this._getHeight(),{animate:!0}),this._waitForAction(this._onDone.bind(this))}.bind(this))):scroll>=this._getHeight()?this._setState(this.STATE_PREACTION):this._setState(this.STATE_INITIAL),event.stopPropagation(),this._translateTo(scroll)}},_onDragStart:function(){this.isDisabled()||(this._startScroll=this._getCurrentScroll())},_onDragEnd:function(){if(!this.isDisabled()&&this._currentTranslation>0){var scroll=this._currentTranslation;scroll>this._getHeight()?(this._setState(this.STATE_ACTION),this._translateTo(this._getHeight(),{animate:!0}),this._waitForAction(this._onDone.bind(this))):this._translateTo(0,{animate:!0})}},_waitForAction:function(done){this._attrs.ngAction?this._scope.$eval(this._attrs.ngAction,{$done:done}):this._attrs.onAction?eval(this._attrs.onAction):done()},_onDone:function(){this._translateTo(0,{animate:!0}),this._setState(this.STATE_INITIAL)},_getHeight:function(){return parseInt(this._element[0].getAttribute("height")||"64",10)},setHeight:function(height){this._element[0].setAttribute("height",height+"px"),this._setStyle()},setThresholdHeight:function(thresholdHeight){this._element[0].setAttribute("threshold-height",thresholdHeight+"px")},_getThresholdHeight:function(){return parseInt(this._element[0].getAttribute("threshold-height")||"96",10)},_thresholdHeightEnabled:function(){var th=this._getThresholdHeight();return th>0&&th>=this._getHeight()},_setState:function(state,noEvent){var oldState=this._getState();this._scope.$evalAsync(function(){this._element[0].setAttribute("state",state)}.bind(this)),noEvent||oldState===this._getState()||this.emit("changestate",{state:state,pullHook:this})},_getState:function(){return this._element[0].getAttribute("state")},getCurrentState:function(){return this._getState()},_getCurrentScroll:function(){return this._pageElement[0].scrollTop},isDisabled:function(){return this._element[0].hasAttribute("disabled")},setDisabled:function(disabled){disabled?this._element[0].setAttribute("disabled",""):this._element[0].removeAttribute("disabled")},_translateTo:function(scroll,options){options=options||{},this._currentTranslation=scroll,options.animate?animit(this._scrollElement[0]).queue({transform:this._generateTranslationTransform(scroll)},{duration:.3,timing:"cubic-bezier(.1, .7, .1, 1)"}).play(options.callback):animit(this._scrollElement[0]).queue({transform:this._generateTranslationTransform(scroll)}).play(options.callback)},_getMinimumScroll:function(){var scrollHeight=this._scrollElement[0].getBoundingClientRect().height,pageHeight=this._pageElement[0].getBoundingClientRect().height;return scrollHeight>pageHeight?-(scrollHeight-pageHeight):0},_createEventListeners:function(){var element=this._scrollElement.parent();this._hammer=new Hammer(element[0],{dragMinDistance:1,dragDistanceCorrection:!1}),this._bindedOnDrag=this._onDrag.bind(this),this._bindedOnDragStart=this._onDragStart.bind(this),this._bindedOnDragEnd=this._onDragEnd.bind(this),this._bindedOnScroll=this._onScroll.bind(this),this._hammer.on("drag",this._bindedOnDrag),this._hammer.on("dragstart",this._bindedOnDragStart),this._hammer.on("dragend",this._bindedOnDragEnd),element.on("scroll",this._bindedOnScroll)},_destroyEventListeners:function(){var element=this._scrollElement[0].parentNode;this._hammer.off("drag",this._bindedOnDrag),this._hammer.off("dragstart",this._bindedOnDragStart),this._hammer.off("dragend",this._bindedOnDragEnd),element.off("scroll",this._bindedOnScroll)},_destroy:function(){this._destroyEventListeners(),this._element=this._scope=this._attrs=null}});return MicroEvent.mixin(PullHookView),PullHookView}])}(),function(){"use strict";var module=angular.module("onsen");module.factory("PushSlidingMenuAnimator",["SlidingMenuAnimator",function(SlidingMenuAnimator){var PushSlidingMenuAnimator=SlidingMenuAnimator.extend({_isRight:!1,_element:void 0,_menuPage:void 0,_mainPage:void 0,_width:void 0,_duration:!1,setup:function(element,mainPage,menuPage,options){options=options||{},this._element=element,this._mainPage=mainPage,this._menuPage=menuPage,this._isRight=!!options.isRight,this._width=options.width||"90%",this._duration=.4,menuPage.css({width:options.width,display:"none"}),this._isRight?menuPage.css({right:"-"+options.width,left:"auto"}):menuPage.css({right:"auto",left:"-"+options.width})},onResized:function(options){if(this._menuPage.css("width",options.width),this._isRight?this._menuPage.css({right:"-"+options.width,left:"auto"}):this._menuPage.css({right:"auto",left:"-"+options.width}),options.isOpened){var max=this._menuPage[0].clientWidth,mainPageTransform=this._generateAbovePageTransform(max),menuPageStyle=this._generateBehindPageStyle(max);animit(this._mainPage[0]).queue({transform:mainPageTransform}).play(),animit(this._menuPage[0]).queue(menuPageStyle).play()}},destroy:function(){this._mainPage.removeAttr("style"),this._menuPage.removeAttr("style"),this._element=this._mainPage=this._menuPage=null},openMenu:function(callback,instant){var duration=instant===!0?0:this._duration;this._menuPage.css("display","block");var max=this._menuPage[0].clientWidth,aboveTransform=this._generateAbovePageTransform(max),behindStyle=this._generateBehindPageStyle(max);setTimeout(function(){animit(this._mainPage[0]).queue({transform:aboveTransform},{duration:duration,timing:"cubic-bezier(.1, .7, .1, 1)"}).queue(function(done){callback(),done()}).play(),animit(this._menuPage[0]).queue(behindStyle,{duration:duration,timing:"cubic-bezier(.1, .7, .1, 1)"}).play()}.bind(this),1e3/60)},closeMenu:function(callback,instant){var duration=instant===!0?0:this._duration,aboveTransform=this._generateAbovePageTransform(0),behindStyle=this._generateBehindPageStyle(0);setTimeout(function(){animit(this._mainPage[0]).queue({transform:aboveTransform},{duration:duration,timing:"cubic-bezier(.1, .7, .1, 1)"}).queue({transform:"translate3d(0, 0, 0)"}).queue(function(done){this._menuPage.css("display","none"),callback(),done()}.bind(this)).play(),animit(this._menuPage[0]).queue(behindStyle,{duration:duration,timing:"cubic-bezier(.1, .7, .1, 1)"}).queue(function(done){done()}).play()}.bind(this),1e3/60)},translateMenu:function(options){this._menuPage.css("display","block");var aboveTransform=this._generateAbovePageTransform(Math.min(options.maxDistance,options.distance)),behindStyle=this._generateBehindPageStyle(Math.min(options.maxDistance,options.distance));animit(this._mainPage[0]).queue({transform:aboveTransform}).play(),animit(this._menuPage[0]).queue(behindStyle).play()},_generateAbovePageTransform:function(distance){var x=this._isRight?-distance:distance,aboveTransform="translate3d("+x+"px, 0, 0)";return aboveTransform},_generateBehindPageStyle:function(distance){var behindX=(this._menuPage[0].clientWidth,this._isRight?-distance:distance),behindTransform="translate3d("+behindX+"px, 0, 0)";return{transform:behindTransform}},copy:function(){return new PushSlidingMenuAnimator}});return PushSlidingMenuAnimator}])}(),function(){"use strict";var module=angular.module("onsen");module.factory("RevealSlidingMenuAnimator",["SlidingMenuAnimator",function(SlidingMenuAnimator){var RevealSlidingMenuAnimator=SlidingMenuAnimator.extend({_blackMask:void 0,_isRight:!1,_menuPage:void 0,_element:void 0,_mainPage:void 0,_duration:void 0,setup:function(element,mainPage,menuPage,options){this._element=element,this._menuPage=menuPage,this._mainPage=mainPage,this._isRight=!!options.isRight,this._width=options.width||"90%",this._duration=.4,mainPage.css({boxShadow:"0px 0 10px 0px rgba(0, 0, 0, 0.2)"}),menuPage.css({width:options.width,opacity:.9,display:"none"}),this._isRight?menuPage.css({right:"0px",left:"auto"}):menuPage.css({right:"auto",left:"0px"}),this._blackMask=angular.element("<div></div>").css({backgroundColor:"black",top:"0px",left:"0px",right:"0px",bottom:"0px",position:"absolute",display:"none"}),element.prepend(this._blackMask),animit(mainPage[0]).queue({transform:"translate3d(0, 0, 0)"}).play()},onResized:function(options){if(this._width=options.width,this._menuPage.css("width",this._width),options.isOpened){var max=this._menuPage[0].clientWidth,aboveTransform=this._generateAbovePageTransform(max),behindStyle=this._generateBehindPageStyle(max);animit(this._mainPage[0]).queue({transform:aboveTransform}).play(),animit(this._menuPage[0]).queue(behindStyle).play()}},destroy:function(){this._blackMask&&(this._blackMask.remove(),this._blackMask=null),this._mainPage&&this._mainPage.attr("style",""),this._menuPage&&this._menuPage.attr("style",""),this._mainPage=this._menuPage=this._element=void 0},openMenu:function(callback,instant){var duration=instant===!0?0:this._duration;this._menuPage.css("display","block"),this._blackMask.css("display","block");var max=this._menuPage[0].clientWidth,aboveTransform=this._generateAbovePageTransform(max),behindStyle=this._generateBehindPageStyle(max);setTimeout(function(){animit(this._mainPage[0]).queue({transform:aboveTransform},{duration:duration,timing:"cubic-bezier(.1, .7, .1, 1)"}).queue(function(done){callback(),done()}).play(),animit(this._menuPage[0]).queue(behindStyle,{duration:duration,timing:"cubic-bezier(.1, .7, .1, 1)"}).play()}.bind(this),1e3/60)},closeMenu:function(callback,instant){var duration=instant===!0?0:this._duration;this._blackMask.css("display","block");var aboveTransform=this._generateAbovePageTransform(0),behindStyle=this._generateBehindPageStyle(0);setTimeout(function(){animit(this._mainPage[0]).queue({transform:aboveTransform},{duration:duration,timing:"cubic-bezier(.1, .7, .1, 1)"}).queue({transform:"translate3d(0, 0, 0)"}).queue(function(done){this._menuPage.css("display","none"),callback(),done()}.bind(this)).play(),animit(this._menuPage[0]).queue(behindStyle,{duration:duration,timing:"cubic-bezier(.1, .7, .1, 1)"}).queue(function(done){done()}).play()}.bind(this),1e3/60)},translateMenu:function(options){this._menuPage.css("display","block"),this._blackMask.css("display","block");var aboveTransform=this._generateAbovePageTransform(Math.min(options.maxDistance,options.distance)),behindStyle=this._generateBehindPageStyle(Math.min(options.maxDistance,options.distance));delete behindStyle.opacity,animit(this._mainPage[0]).queue({transform:aboveTransform}).play(),animit(this._menuPage[0]).queue(behindStyle).play()},_generateAbovePageTransform:function(distance){var x=this._isRight?-distance:distance,aboveTransform="translate3d("+x+"px, 0, 0)";return aboveTransform},_generateBehindPageStyle:function(distance){var max=this._menuPage[0].getBoundingClientRect().width,behindDistance=(distance-max)/max*10;behindDistance=isNaN(behindDistance)?0:Math.max(Math.min(behindDistance,0),-10);var behindX=this._isRight?-behindDistance:behindDistance,behindTransform="translate3d("+behindX+"%, 0, 0)",opacity=1+behindDistance/100;return{transform:behindTransform,opacity:opacity}},copy:function(){return new RevealSlidingMenuAnimator}});return RevealSlidingMenuAnimator}])}(),function(){"use strict;";var module=angular.module("onsen"); module.factory("SimpleSlideTransitionAnimator",["NavigatorTransitionAnimator",function(NavigatorTransitionAnimator){var SimpleSlideTransitionAnimator=NavigatorTransitionAnimator.extend({backgroundMask:angular.element('<div style="z-index: 2; position: absolute; width: 100%;height: 100%; background-color: black; opacity: 0;"></div>'),timing:"cubic-bezier(.1, .7, .4, 1)",duration:.3,blackMaskOpacity:.4,init:function(options){options=options||{},this.timing=options.timing||this.timing,this.duration=void 0!==options.duration?options.duration:this.duration},push:function(enterPage,leavePage,callback){var mask=this.backgroundMask.remove();leavePage.element[0].parentNode.insertBefore(mask[0],leavePage.element[0].nextSibling),animit.runAll(animit(mask[0]).queue({opacity:0,transform:"translate3d(0, 0, 0)"}).queue({opacity:this.blackMaskOpacity},{duration:this.duration,timing:this.timing}).resetStyle().queue(function(done){mask.remove(),done()}),animit(enterPage.element[0]).queue({css:{transform:"translate3D(100%, 0, 0)"},duration:0}).queue({css:{transform:"translate3D(0, 0, 0)"},duration:this.duration,timing:this.timing}).resetStyle(),animit(leavePage.element[0]).queue({css:{transform:"translate3D(0, 0, 0)"},duration:0}).queue({css:{transform:"translate3D(-45%, 0px, 0px)"},duration:this.duration,timing:this.timing}).resetStyle().wait(.2).queue(function(done){callback(),done()}))},pop:function(enterPage,leavePage,done){var mask=this.backgroundMask.remove();enterPage.element[0].parentNode.insertBefore(mask[0],enterPage.element[0].nextSibling),animit.runAll(animit(mask[0]).queue({opacity:this.blackMaskOpacity,transform:"translate3d(0, 0, 0)"}).queue({opacity:0},{duration:this.duration,timing:this.timing}).resetStyle().queue(function(done){mask.remove(),done()}),animit(enterPage.element[0]).queue({css:{transform:"translate3D(-45%, 0px, 0px)",opacity:.9},duration:0}).queue({css:{transform:"translate3D(0px, 0px, 0px)",opacity:1},duration:this.duration,timing:this.timing}).resetStyle(),animit(leavePage.element[0]).queue({css:{transform:"translate3D(0px, 0px, 0px)"},duration:0}).queue({css:{transform:"translate3D(100%, 0px, 0px)"},duration:this.duration,timing:this.timing}).wait(.2).queue(function(finish){done(),finish()}))}});return SimpleSlideTransitionAnimator}])}(),function(){"use strict;";var module=angular.module("onsen");module.factory("SlideDialogAnimator",["DialogAnimator",function(DialogAnimator){var SlideDialogAnimator=DialogAnimator.extend({timing:"cubic-bezier(.1, .7, .4, 1)",duration:.2,init:function(options){options=options||{},this.timing=options.timing||this.timing,this.duration=void 0!==options.duration?options.duration:this.duration},show:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask[0]).queue({opacity:0}).queue({opacity:1},{duration:this.duration,timing:this.timing}),animit(dialog._dialog[0]).queue({css:{transform:"translate3D(-50%, -350%, 0)"},duration:0}).queue({css:{transform:"translate3D(-50%, -50%, 0)"},duration:this.duration,timing:this.timing}).resetStyle().queue(function(done){callback(),done()}))},hide:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask[0]).queue({opacity:1}).queue({opacity:0},{duration:this.duration,timing:this.timing}),animit(dialog._dialog[0]).queue({css:{transform:"translate3D(-50%, -50%, 0)"},duration:0}).queue({css:{transform:"translate3D(-50%, -350%, 0)"},duration:this.duration,timing:this.timing}).resetStyle().queue(function(done){callback(),done()}))}});return SlideDialogAnimator}])}(),function(){"use strict";var module=angular.module("onsen"),SlidingMenuViewModel=Class.extend({_distance:0,_maxDistance:void 0,init:function(options){if(!angular.isNumber(options.maxDistance))throw new Error("options.maxDistance must be number");this.setMaxDistance(options.maxDistance)},setMaxDistance:function(maxDistance){if(0>=maxDistance)throw new Error("maxDistance must be greater then zero.");this.isOpened()&&(this._distance=maxDistance),this._maxDistance=maxDistance},shouldOpen:function(){return!this.isOpened()&&this._distance>=this._maxDistance/2},shouldClose:function(){return!this.isClosed()&&this._distance<this._maxDistance/2},openOrClose:function(options){this.shouldOpen()?this.open(options):this.shouldClose()&&this.close(options)},close:function(options){var callback=options.callback||function(){};this.isClosed()?callback():(this._distance=0,this.emit("close",options))},open:function(options){var callback=options.callback||function(){};this.isOpened()?callback():(this._distance=this._maxDistance,this.emit("open",options))},isClosed:function(){return 0===this._distance},isOpened:function(){return this._distance===this._maxDistance},getX:function(){return this._distance},getMaxDistance:function(){return this._maxDistance},translate:function(x){this._distance=Math.max(1,Math.min(this._maxDistance-1,x));var options={distance:this._distance,maxDistance:this._maxDistance};this.emit("translate",options)},toggle:function(){this.isClosed()?this.open():this.close()}});MicroEvent.mixin(SlidingMenuViewModel),module.factory("SlidingMenuView",["$onsen","$compile","SlidingMenuAnimator","RevealSlidingMenuAnimator","PushSlidingMenuAnimator","OverlaySlidingMenuAnimator",function($onsen,$compile,SlidingMenuAnimator,RevealSlidingMenuAnimator,PushSlidingMenuAnimator,OverlaySlidingMenuAnimator){var SlidingMenuView=Class.extend({_scope:void 0,_attrs:void 0,_element:void 0,_menuPage:void 0,_mainPage:void 0,_doorLock:void 0,_isRightMenu:!1,init:function(scope,element,attrs){this._scope=scope,this._attrs=attrs,this._element=element,this._menuPage=angular.element(element[0].querySelector(".onsen-sliding-menu__menu")),this._mainPage=angular.element(element[0].querySelector(".onsen-sliding-menu__main")),this._doorLock=new DoorLock,this._isRightMenu="right"===attrs.side,this._mainPageHammer=new Hammer(this._mainPage[0]),this._bindedOnTap=this._onTap.bind(this);var maxDistance=this._normalizeMaxSlideDistanceAttr();this._logic=new SlidingMenuViewModel({maxDistance:Math.max(maxDistance,1)}),this._logic.on("translate",this._translate.bind(this)),this._logic.on("open",function(options){this._open(options)}.bind(this)),this._logic.on("close",function(options){this._close(options)}.bind(this)),attrs.$observe("maxSlideDistance",this._onMaxSlideDistanceChanged.bind(this)),attrs.$observe("swipeable",this._onSwipeableChanged.bind(this)),this._bindedOnWindowResize=this._onWindowResize.bind(this),window.addEventListener("resize",this._bindedOnWindowResize),this._boundHandleEvent=this._handleEvent.bind(this),this._bindEvents(),attrs.mainPage&&this.setMainPage(attrs.mainPage),attrs.menuPage&&this.setMenuPage(attrs.menuPage),this._deviceBackButtonHandler=$onsen.DeviceBackButtonHandler.create(this._element,this._onDeviceBackButton.bind(this));var unlock=this._doorLock.lock();window.setTimeout(function(){var maxDistance=this._normalizeMaxSlideDistanceAttr();this._logic.setMaxDistance(maxDistance),this._menuPage.css({opacity:1}),this._animator=this._getAnimatorOption(),this._animator.setup(this._element,this._mainPage,this._menuPage,{isRight:this._isRightMenu,width:this._attrs.maxSlideDistance||"90%"}),unlock()}.bind(this),400),scope.$on("$destroy",this._destroy.bind(this))},getDeviceBackButtonHandler:function(){return this._deviceBackButtonHandler},_onDeviceBackButton:function(event){this.isMenuOpened()?this.closeMenu():event.callParentHandler()},_onTap:function(){this.isMenuOpened()&&this.closeMenu()},_refreshMenuPageWidth:function(){var width="maxSlideDistance"in this._attrs?this._attrs.maxSlideDistance:"90%";this._animator&&this._animator.onResized({isOpened:this._logic.isOpened(),width:width})},_destroy:function(){this.emit("destroy",{slidingMenu:this}),this._deviceBackButtonHandler.destroy(),window.removeEventListener("resize",this._bindedOnWindowResize),this._mainPageHammer.off("tap",this._bindedOnTap),this._element=this._scope=this._attrs=null},_getAnimatorOption:function(){var animator=SlidingMenuView._animatorDict[this._attrs.type];return animator instanceof SlidingMenuAnimator||(animator=SlidingMenuView._animatorDict["default"]),animator.copy()},_onSwipeableChanged:function(swipeable){swipeable=""===swipeable||void 0===swipeable||"true"==swipeable,this.setSwipeable(swipeable)},setSwipeable:function(enabled){enabled?this._activateHammer():this._deactivateHammer()},_onWindowResize:function(){this._recalculateMAX(),this._refreshMenuPageWidth()},_onMaxSlideDistanceChanged:function(){this._recalculateMAX(),this._refreshMenuPageWidth()},_normalizeMaxSlideDistanceAttr:function(){var maxDistance=this._attrs.maxSlideDistance;if("maxSlideDistance"in this._attrs){if("string"!=typeof maxDistance)throw new Error("invalid state");-1!==maxDistance.indexOf("px",maxDistance.length-2)?maxDistance=parseInt(maxDistance.replace("px",""),10):maxDistance.indexOf("%",maxDistance.length-1)>0&&(maxDistance=maxDistance.replace("%",""),maxDistance=parseFloat(maxDistance)/100*this._mainPage[0].clientWidth)}else maxDistance=.9*this._mainPage[0].clientWidth;return maxDistance},_recalculateMAX:function(){var maxDistance=this._normalizeMaxSlideDistanceAttr();maxDistance&&this._logic.setMaxDistance(parseInt(maxDistance,10))},_activateHammer:function(){this._hammertime.on("touch dragleft dragright swipeleft swiperight release",this._boundHandleEvent)},_deactivateHammer:function(){this._hammertime.off("touch dragleft dragright swipeleft swiperight release",this._boundHandleEvent)},_bindEvents:function(){this._hammertime=new Hammer(this._element[0],{dragMinDistance:1})},_appendMainPage:function(pageUrl,templateHTML){var pageScope=this._scope.$parent.$new(),pageContent=angular.element(templateHTML),link=$compile(pageContent);this._mainPage.append(pageContent),this._currentPageElement&&(this._currentPageElement.remove(),this._currentPageScope.$destroy()),link(pageScope),this._currentPageElement=pageContent,this._currentPageScope=pageScope,this._currentPageUrl=pageUrl},_appendMenuPage:function(templateHTML){var pageScope=this._scope.$parent.$new(),pageContent=angular.element(templateHTML),link=$compile(pageContent);this._menuPage.append(pageContent),this._currentMenuPageScope&&(this._currentMenuPageScope.$destroy(),this._currentMenuPageElement.remove()),link(pageScope),this._currentMenuPageElement=pageContent,this._currentMenuPageScope=pageScope},setMenuPage:function(page,options){if(!page)throw new Error("cannot set undefined page");options=options||{},options.callback=options.callback||function(){};var self=this;$onsen.getPageHTMLAsync(page).then(function(html){self._appendMenuPage(angular.element(html)),options.closeMenu&&self.close(),options.callback()},function(){throw new Error("Page is not found: "+page)})},setMainPage:function(pageUrl,options){options=options||{},options.callback=options.callback||function(){};var done=function(){options.closeMenu&&this.close(),options.callback()}.bind(this);if(this.currentPageUrl===pageUrl)return done(),void 0;if(!pageUrl)throw new Error("cannot set undefined page");var self=this;$onsen.getPageHTMLAsync(pageUrl).then(function(html){self._appendMainPage(pageUrl,html),done()},function(){throw new Error("Page is not found: "+page)})},_handleEvent:function(event){if(!this._doorLock.isLocked())switch(this._isInsideIgnoredElement(event.target)&&event.gesture.stopDetect(),event.type){case"touch":this._logic.isClosed()&&(this._isInsideSwipeTargetArea(event)||event.gesture.stopDetect());break;case"dragleft":case"dragright":event.gesture.preventDefault();var deltaX=event.gesture.deltaX,deltaDistance=this._isRightMenu?-deltaX:deltaX,startEvent=event.gesture.startEvent;if("isOpened"in startEvent||(startEvent.isOpened=this._logic.isOpened()),0>deltaDistance&&this._logic.isClosed())break;if(deltaDistance>0&&this._logic.isOpened())break;var distance=startEvent.isOpened?deltaDistance+this._logic.getMaxDistance():deltaDistance;this._logic.translate(distance);break;case"swipeleft":event.gesture.preventDefault(),this._isRightMenu?this.open():this.close(),event.gesture.stopDetect();break;case"swiperight":event.gesture.preventDefault(),this._isRightMenu?this.close():this.open(),event.gesture.stopDetect();break;case"release":this._lastDistance=null,this._logic.shouldOpen()?this.open():this._logic.shouldClose()&&this.close()}},_isInsideIgnoredElement:function(element){do{if(element.getAttribute&&element.getAttribute("sliding-menu-ignore"))return!0;element=element.parentNode}while(element);return!1},_isInsideSwipeTargetArea:function(event){var x=event.gesture.center.pageX;"_swipeTargetWidth"in event.gesture.startEvent||(event.gesture.startEvent._swipeTargetWidth=this._getSwipeTargetWidth());var targetWidth=event.gesture.startEvent._swipeTargetWidth;return this._isRightMenu?this._mainPage[0].clientWidth-x<targetWidth:targetWidth>x},_getSwipeTargetWidth:function(){var targetWidth=this._attrs.swipeTargetWidth;"string"==typeof targetWidth&&(targetWidth=targetWidth.replace("px",""));var width=parseInt(targetWidth,10);return 0>width||!targetWidth?this._mainPage[0].clientWidth:width},closeMenu:function(){return this.close.apply(this,arguments)},close:function(options){options=options||{},options="function"==typeof options?{callback:options}:options,this.emit("preclose"),this._doorLock.waitUnlock(function(){this._logic.close(options)}.bind(this))},_close:function(options){var callback=options.callback||function(){},unlock=this._doorLock.lock(),instant="none"==options.animation;this._animator.closeMenu(function(){unlock(),this._mainPage.children().css("pointer-events",""),this._mainPageHammer.off("tap",this._bindedOnTap),this.emit("postclose"),callback()}.bind(this),instant)},openMenu:function(){return this.open.apply(this,arguments)},open:function(options){options=options||{},options="function"==typeof options?{callback:options}:options,this.emit("preopen"),this._doorLock.waitUnlock(function(){this._logic.open(options)}.bind(this))},_open:function(options){var callback=options.callback||function(){},unlock=this._doorLock.lock(),instant="none"==options.animation;this._animator.openMenu(function(){unlock(),this._mainPage.children().css("pointer-events","none"),this._mainPageHammer.on("tap",this._bindedOnTap),this.emit("postopen"),callback()}.bind(this),instant)},toggle:function(options){this._logic.isClosed()?this.open(options):this.close(options)},toggleMenu:function(){return this.toggle.apply(this,arguments)},isMenuOpened:function(){return this._logic.isOpened()},_translate:function(event){this._animator.translateMenu(event)}});return SlidingMenuView._animatorDict={"default":new RevealSlidingMenuAnimator,overlay:new OverlaySlidingMenuAnimator,reveal:new RevealSlidingMenuAnimator,push:new PushSlidingMenuAnimator},SlidingMenuView.registerSlidingMenuAnimator=function(name,animator){if(!(animator instanceof SlidingMenuAnimator))throw new Error('"animator" param must be an instance of SlidingMenuAnimator');this._animatorDict[name]=animator},MicroEvent.mixin(SlidingMenuView),SlidingMenuView}])}(),function(){"use strict";var module=angular.module("onsen");module.factory("SlidingMenuAnimator",function(){return Class.extend({setup:function(){},onResized:function(){},openMenu:function(){},closeClose:function(){},destroy:function(){},translateMenu:function(){},copy:function(){throw new Error("Override copy method.")}})})}(),function(){"use strict";var module=angular.module("onsen");module.factory("SplitView",["$compile","RevealSlidingMenuAnimator","$onsen","$onsGlobal",function($compile,RevealSlidingMenuAnimator,$onsen,$onsGlobal){function isNumber(n){return!isNaN(parseFloat(n))&&isFinite(n)}var SPLIT_MODE=0,COLLAPSE_MODE=1,MAIN_PAGE_RATIO=.9,SplitView=Class.extend({init:function(scope,element){element.addClass("onsen-sliding-menu"),this._element=element,this._scope=scope,this._mainPage=angular.element(element[0].querySelector(".onsen-split-view__main")),this._secondaryPage=angular.element(element[0].querySelector(".onsen-split-view__secondary")),this._max=this._mainPage[0].clientWidth*MAIN_PAGE_RATIO,this._mode=SPLIT_MODE,this._doorLock=new DoorLock,this._doSplit=!1,this._doCollapse=!1,$onsGlobal.orientation.on("change",this._onResize.bind(this)),this._animator=new RevealSlidingMenuAnimator,this._element.css("display","none"),scope.mainPage&&this.setMainPage(scope.mainPage),scope.secondaryPage&&this.setSecondaryPage(scope.secondaryPage);var unlock=this._doorLock.lock();this._considerChangingCollapse(),this._setSize(),setTimeout(function(){this._element.css("display","block"),unlock()}.bind(this),1e3/60*2),scope.$on("$destroy",this._destroy.bind(this))},_appendSecondPage:function(templateHTML){var pageScope=this._scope.$parent.$new(),pageContent=$compile(templateHTML)(pageScope);this._secondaryPage.append(pageContent),this._currentSecondaryPageElement&&(this._currentSecondaryPageElement.remove(),this._currentSecondaryPageScope.$destroy()),this._currentSecondaryPageElement=pageContent,this._currentSecondaryPageScope=pageScope},_appendMainPage:function(templateHTML){var pageScope=this._scope.$parent.$new(),pageContent=$compile(templateHTML)(pageScope);this._mainPage.append(pageContent),this._currentPage&&(this._currentPage.remove(),this._currentPageScope.$destroy()),this._currentPage=pageContent,this._currentPageScope=pageScope},setSecondaryPage:function(page){if(!page)throw new Error("cannot set undefined page");$onsen.getPageHTMLAsync(page).then(function(html){this._appendSecondPage(angular.element(html.trim()))}.bind(this),function(){throw new Error("Page is not found: "+page)})},setMainPage:function(page){if(!page)throw new Error("cannot set undefined page");$onsen.getPageHTMLAsync(page).then(function(html){this._appendMainPage(angular.element(html.trim()))}.bind(this),function(){throw new Error("Page is not found: "+page)})},_onResize:function(){var lastMode=this._mode;$onsen.isAndroid()?setTimeout(function(){this._considerChangingCollapse()}.bind(this),200):this._considerChangingCollapse(),lastMode===COLLAPSE_MODE&&this._mode===COLLAPSE_MODE&&this._animator.onResized({isOpened:!1,width:"90%"}),this._max=this._mainPage[0].clientWidth*MAIN_PAGE_RATIO},_considerChangingCollapse:function(){var should=this._shouldCollapse();should&&this._mode!==COLLAPSE_MODE?(this._fireUpdateEvent(),this._doSplit?this._activateSplitMode():this._activateCollapseMode()):should||this._mode!==COLLAPSE_MODE||(this._fireUpdateEvent(),this._doCollapse?this._activateCollapseMode():this._activateSplitMode()),this._doCollapse=this._doSplit=!1},update:function(){this._fireUpdateEvent();var should=this._shouldCollapse();this._doSplit?this._activateSplitMode():this._doCollapse?this._activateCollapseMode():should?this._activateCollapseMode():should||this._activateSplitMode(),this._doSplit=this._doCollapse=!1},_getOrientation:function(){return $onsGlobal.orientation.isPortrait()?"portrait":"landscape"},getCurrentMode:function(){return this._mode===COLLAPSE_MODE?"collapse":"split"},_shouldCollapse:function(){var c="portrait";if("string"==typeof this._scope.collapse&&(c=this._scope.collapse.trim()),"portrait"==c)return $onsGlobal.orientation.isPortrait();if("landscape"==c)return $onsGlobal.orientation.isLandscape();if("width"==c.substr(0,5)){var num=c.split(" ")[1];num.indexOf("px")>=0&&(num=num.substr(0,num.length-2));var width=window.innerWidth;return $onsen.isAndroid()&&(width=screen.width),isNumber(num)&&num>width}var mq=window.matchMedia(c);return mq.matches},_setSize:function(){if(this._mode===SPLIT_MODE){this._scope.mainPageWidth||(this._scope.mainPageWidth="70");var secondarySize=100-this._scope.mainPageWidth.replace("%","");this._secondaryPage.css({width:secondarySize+"%",opacity:1}),this._mainPage.css({width:this._scope.mainPageWidth+"%"}),this._mainPage.css("left",secondarySize+"%")}},_fireEvent:function(name){this.emit(name,{splitView:this,width:window.innerWidth,orientation:this._getOrientation()})},_fireUpdateEvent:function(){var that=this;this.emit("update",{splitView:this,shouldCollapse:this._shouldCollapse(),currentMode:this.getCurrentMode(),split:function(){that._doSplit=!0,that._doCollapse=!1},collapse:function(){that._doSplit=!1,that._doCollapse=!0},width:window.innerWidth,orientation:this._getOrientation()})},_activateCollapseMode:function(){this._mode!==COLLAPSE_MODE&&(this._fireEvent("precollapse"),this._secondaryPage.attr("style",""),this._mainPage.attr("style",""),this._mode=COLLAPSE_MODE,this._animator.setup(this._element,this._mainPage,this._secondaryPage,{isRight:!1,width:"90%"}),this._fireEvent("postcollapse"))},_activateSplitMode:function(){this._mode!==SPLIT_MODE&&(this._fireEvent("presplit"),this._animator.destroy(),this._secondaryPage.attr("style",""),this._mainPage.attr("style",""),this._mode=SPLIT_MODE,this._setSize(),this._fireEvent("postsplit"))},_destroy:function(){this.emit("destroy",{splitView:this}),this._element=null,this._scope=null}});return MicroEvent.mixin(SplitView),SplitView}])}(),function(){"use strict";var module=angular.module("onsen");module.factory("SwitchView",["$onsen",function(){var SwitchView=Class.extend({init:function(element,scope,attrs){this._element=element,this._checkbox=angular.element(element[0].querySelector("input[type=checkbox]")),this._scope=scope,attrs.$observe("disabled",function(){element.attr("disabled")?this._checkbox.attr("disabled","disabled"):this._checkbox.removeAttr("disabled")}.bind(this)),this._checkbox.on("change",function(){this.emit("change",{"switch":this,value:this._checkbox[0].checked,isInteractive:!0})}.bind(this))},isChecked:function(){return this._checkbox[0].checked},setChecked:function(isChecked){isChecked=!!isChecked,this._checkbox[0].checked!=isChecked&&(this._scope.model=isChecked,this._checkbox[0].checked=isChecked,this._scope.$evalAsync(),this.emit("change",{"switch":this,value:isChecked,isInteractive:!1}))},getCheckboxElement:function(){return this._checkbox[0]}});return MicroEvent.mixin(SwitchView),SwitchView}])}(),function(){"use strict;";var module=angular.module("onsen");module.factory("TabbarAnimator",function(){var TabbarAnimator=Class.extend({apply:function(){throw new Error("This method must be implemented.")}});return TabbarAnimator}),module.factory("TabbarNoneAnimator",["TabbarAnimator",function(TabbarAnimator){var TabbarNoneAnimator=TabbarAnimator.extend({apply:function(enterPage,leavePage,done){done()}});return TabbarNoneAnimator}]),module.factory("TabbarFadeAnimator",["TabbarAnimator",function(TabbarAnimator){var TabbarFadeAnimator=TabbarAnimator.extend({apply:function(enterPage,leavePage,done){animit.runAll(animit(enterPage[0]).queue({transform:"translate3D(0, 0, 0)",opacity:0}).queue({transform:"translate3D(0, 0, 0)",opacity:1},{duration:.4,timing:"linear"}).resetStyle().queue(function(callback){done(),callback()}),animit(leavePage[0]).queue({transform:"translate3D(0, 0, 0)",opacity:1}).queue({transform:"translate3D(0, 0, 0)",opacity:0},{duration:.4,timing:"linear"}))}});return TabbarFadeAnimator}]),module.factory("TabbarView",["$onsen","$compile","TabbarAnimator","TabbarNoneAnimator","TabbarFadeAnimator",function($onsen,$compile,TabbarAnimator,TabbarNoneAnimator,TabbarFadeAnimator){var TabbarView=Class.extend({_tabbarId:void 0,_tabItems:void 0,init:function(scope,element,attrs){this._scope=scope,this._element=element,this._attrs=attrs,this._tabbarId=Date.now(),this._tabItems=[],this._contentElement=angular.element(element[0].querySelector(".ons-tab-bar__content")),this._tabbarElement=angular.element(element[0].querySelector(".ons-tab-bar__footer")),this._scope.$on("$destroy",this._destroy.bind(this)),this._hasTopTabbar()&&this._prepareForTopTabbar()},_prepareForTopTabbar:function(){this._contentElement.attr("no-status-bar-fill",""),setImmediate(function(){this._contentElement.addClass("tab-bar--top__content"),this._tabbarElement.addClass("tab-bar--top")}.bind(this));var page=ons.findParentComponentUntil("ons-page",this._element[0]);if(page&&this._element.css("top",window.getComputedStyle(page.getContentElement(),null).getPropertyValue("padding-top")),$onsen.shouldFillStatusBar(this._element[0])){var fill=angular.element(document.createElement("div"));fill.addClass("tab-bar__status-bar-fill"),fill.css({width:"0px",height:"0px"}),this._element.prepend(fill)}},_hasTopTabbar:function(){return"top"===this._attrs.position},setActiveTab:function(index,options){options=options||{};var previousTabItem=this._tabItems[this.getActiveTabIndex()],selectedTabItem=this._tabItems[index];if("undefined"!=typeof selectedTabItem.noReload&&index==this.getActiveTabIndex())return this.emit("reactive",{index:index,tabItem:selectedTabItem}),!1;var needLoad=selectedTabItem.page&&!options.keepPage;if(!selectedTabItem)return!1;var canceled=!1;if(this.emit("prechange",{index:index,tabItem:selectedTabItem,cancel:function(){canceled=!0}}),canceled)return selectedTabItem.setInactive(),previousTabItem&&previousTabItem.setActive(),!1;if(selectedTabItem.setActive(),needLoad){var removeElement=!0;previousTabItem&&previousTabItem.isPersistent()&&(removeElement=!1,previousTabItem._pageElement=this._currentPageElement);var params={callback:function(){this.emit("postchange",{index:index,tabItem:selectedTabItem})}.bind(this),_removeElement:removeElement};selectedTabItem.isPersistent()&&selectedTabItem._pageElement?this._loadPersistentPageDOM(selectedTabItem._pageElement,params):this._loadPage(selectedTabItem.page,params)}for(var i=0;i<this._tabItems.length;i++)this._tabItems[i]!=selectedTabItem?this._tabItems[i].setInactive():(this._triggerActiveTabChanged(i,selectedTabItem),needLoad||this.emit("postchange",{index:index,tabItem:selectedTabItem}));return!0},_triggerActiveTabChanged:function(index,tabItem){this._scope.onActiveTabChanged({$index:index,$tabItem:tabItem})},setTabbarVisibility:function(visible){this._scope.hideTabs=!visible,this._onTabbarVisibilityChanged()},_onTabbarVisibilityChanged:function(){this._hasTopTabbar()?this._scope.hideTabs?this._contentElement.css("top","0px"):this._contentElement.css("top",""):this._scope.hideTabs?this._contentElement.css("bottom","0px"):this._contentElement.css("bottom","")},addTabItem:function(tabItem){this._tabItems.push(tabItem)},getActiveTabIndex:function(){for(var tabItem,i=0;i<this._tabItems.length;i++)if(tabItem=this._tabItems[i],tabItem.isActive())return i;return-1},loadPage:function(page,options){return this._loadPage(page,options)},_loadPage:function(page,options){$onsen.getPageHTMLAsync(page).then(function(html){var pageElement=angular.element(html.trim());this._loadPageDOM(pageElement,options)}.bind(this),function(){throw new Error("Page is not found: "+page)})},_switchPage:function(element,scope,options){if(this._currentPageElement){var oldPageElement=this._currentPageElement,oldPageScope=this._currentPageScope;this._currentPageElement=element,this._currentPageScope=scope,this._getAnimatorOption(options).apply(element,oldPageElement,function(){options._removeElement?(oldPageElement.remove(),oldPageScope.$destroy()):oldPageElement.css("display","none"),options.callback instanceof Function&&options.callback()})}else this._currentPageElement=element,this._currentPageScope=scope,options.callback instanceof Function&&options.callback()},_loadPageDOM:function(element,options){options=options||{};var pageScope=this._scope.$parent.$new(),link=$compile(element);this._contentElement.append(element);var pageContent=link(pageScope);pageScope.$evalAsync(),this._switchPage(pageContent,pageScope,options)},_loadPersistentPageDOM:function(element,options){options=options||{},element.css("display","block"),this._switchPage(element,element.scope(),options)},_getAnimatorOption:function(options){var animationAttr=this._element.attr("animation")||"default";return TabbarView._animatorDict[options.animation||animationAttr]||TabbarView._animatorDict["default"]},_destroy:function(){this.emit("destroy",{tabbar:this}),this._element=this._scope=this._attrs=null}});return MicroEvent.mixin(TabbarView),TabbarView._animatorDict={"default":new TabbarNoneAnimator,none:new TabbarNoneAnimator,fade:new TabbarFadeAnimator},TabbarView.registerAnimator=function(name,animator){if(!(animator instanceof TabbarAnimator))throw new Error('"animator" param must be an instance of TabbarAnimator');this._transitionAnimatorDict[name]=animator},TabbarView}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsAlertDialog",["$onsen","AlertDialogView",function($onsen,AlertDialogView){return{restrict:"E",replace:!1,scope:!0,transclude:!1,compile:function(element,attrs){var modifierTemplater=$onsen.generateModifierTemplater(attrs);element.addClass("alert-dialog "+modifierTemplater("alert-dialog--*"));var titleElement=angular.element(element[0].querySelector(".alert-dialog-title")),contentElement=angular.element(element[0].querySelector(".alert-dialog-content"));return titleElement.length&&titleElement.addClass(modifierTemplater("alert-dialog-title--*")),contentElement.length&&contentElement.addClass(modifierTemplater("alert-dialog-content--*")),{pre:function(scope,element,attrs){var alertDialog=new AlertDialogView(scope,element,attrs);$onsen.declareVarAttribute(attrs,alertDialog),$onsen.addModifierMethods(alertDialog,"alert-dialog--*",element),titleElement.length&&$onsen.addModifierMethods(alertDialog,"alert-dialog-title--*",titleElement),contentElement.length&&$onsen.addModifierMethods(alertDialog,"alert-dialog-content--*",contentElement),$onsen.isAndroid()&&alertDialog.addModifier("android"),element.data("ons-alert-dialog",alertDialog),scope.$on("$destroy",function(){alertDialog._events=void 0,$onsen.removeModifierMethods(alertDialog),element.data("ons-alert-dialog",void 0),element=null})},post:function(scope,element){$onsen.fireComponentEvent(element[0],"init")}}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsBackButton",["$onsen","$compile","GenericView","ComponentCleaner",function($onsen,$compile,GenericView,ComponentCleaner){return{restrict:"E",replace:!1,templateUrl:$onsen.DIRECTIVE_TEMPLATE_URL+"/back_button.tpl",transclude:!0,scope:!0,link:{pre:function(scope,element,attrs,controller,transclude){var backButton=new GenericView(scope,element,attrs);$onsen.declareVarAttribute(attrs,backButton),element.data("ons-back-button",backButton),scope.$on("$destroy",function(){backButton._events=void 0,$onsen.removeModifierMethods(backButton),element.data("ons-back-button",void 0),element=null}),scope.modifierTemplater=$onsen.generateModifierTemplater(attrs);var navigator=ons.findParentComponentUntil("ons-navigator",element);scope.$watch(function(){return navigator.pages.length},function(nbrOfPages){scope.showBackButton=nbrOfPages>1}),$onsen.addModifierMethods(backButton,"toolbar-button--*",element.children()),transclude(scope,function(clonedElement){clonedElement[0]&&element[0].querySelector(".back-button__label").appendChild(clonedElement[0])}),ComponentCleaner.onDestroy(scope,function(){ComponentCleaner.destroyScope(scope),ComponentCleaner.destroyAttributes(attrs),element=null,scope=null,attrs=null})},post:function(scope,element){$onsen.fireComponentEvent(element[0],"init")}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsBottomToolbar",["$onsen","GenericView",function($onsen,GenericView){return{restrict:"E",replace:!1,transclude:!1,scope:!1,compile:function(element,attrs){var modifierTemplater=$onsen.generateModifierTemplater(attrs),inline="undefined"!=typeof attrs.inline;return element.addClass("bottom-bar"),element.addClass(modifierTemplater("bottom-bar--*")),element.css({"z-index":0}),inline&&element.css("position","static"),{pre:function(scope,element,attrs){var bottomToolbar=new GenericView(scope,element,attrs);$onsen.declareVarAttribute(attrs,bottomToolbar),element.data("ons-bottomToolbar",bottomToolbar),scope.$on("$destroy",function(){bottomToolbar._events=void 0,$onsen.removeModifierMethods(bottomToolbar),element.data("ons-bottomToolbar",void 0),element=null}),$onsen.addModifierMethods(bottomToolbar,"bottom-bar--*",element); var pageView=element.inheritedData("ons-page");pageView&&!inline&&pageView.registerBottomToolbar(element)},post:function(scope,element){$onsen.fireComponentEvent(element[0],"init")}}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsButton",["$onsen","ButtonView",function($onsen,ButtonView){return{restrict:"E",replace:!1,transclude:!0,scope:{animation:"@"},templateUrl:$onsen.DIRECTIVE_TEMPLATE_URL+"/button.tpl",link:function(scope,element,attrs,_,transclude){var button=new ButtonView(scope,element,attrs);$onsen.declareVarAttribute(attrs,button),element.data("ons-button",button),scope.$on("$destroy",function(){button._events=void 0,$onsen.removeModifierMethods(button),element.data("ons-button",void 0),element=null});var initialAnimation="slide-left";if(scope.modifierTemplater=$onsen.generateModifierTemplater(attrs),element.addClass("button effeckt-button"),element.addClass(scope.modifierTemplater("button--*")),element.addClass(initialAnimation),$onsen.addModifierMethods(button,"button--*",element),transclude(scope.$parent,function(cloned){angular.element(element[0].querySelector(".ons-button-inner")).append(cloned)}),attrs.ngController)throw new Error("This element can't accept ng-controller directive.");scope.item={},scope.item.animation=initialAnimation,scope.$watch("animation",function(newAnimation){newAnimation&&(scope.item.animation&&element.removeClass(scope.item.animation),scope.item.animation=newAnimation,element.addClass(scope.item.animation))}),attrs.$observe("shouldSpin",function(shouldSpin){"true"===shouldSpin?element.attr("data-loading",!0):element.removeAttr("data-loading")}),$onsen.cleaner.onDestroy(scope,function(){$onsen.clearComponent({scope:scope,attrs:attrs,element:element}),scope=element=attrs=null}),$onsen.fireComponentEvent(element[0],"init")}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsCarousel",["$onsen","CarouselView",function($onsen,CarouselView){return{restrict:"E",replace:!1,scope:!1,transclude:!1,compile:function(element,attrs){var templater=$onsen.generateModifierTemplater(attrs);return element.addClass(templater("carousel--*")),function(scope,element,attrs){var carousel=new CarouselView(scope,element,attrs);element.data("ons-carousel",carousel),$onsen.declareVarAttribute(attrs,carousel),scope.$on("$destroy",function(){carousel._events=void 0,element.data("ons-carousel",void 0),element=null}),element[0].hasAttribute("auto-refresh")&&scope.$watch(function(){return element[0].childNodes.length},function(){setImmediate(function(){carousel.refresh()})}),setImmediate(function(){carousel.refresh()}),$onsen.fireComponentEvent(element[0],"init")}}}}]),module.directive("onsCarouselItem",["$onsen",function($onsen){return{restrict:"E",replace:!1,scope:!1,transclude:!1,compile:function(element,attrs){var templater=$onsen.generateModifierTemplater(attrs);return element.addClass(templater("carousel-item--*")),element.css("width","100%"),function(){}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsCol",["$timeout","$onsen",function($timeout,$onsen){return{restrict:"E",replace:!1,transclude:!1,scope:!1,compile:function(element){return element.addClass("col ons-col-inner"),function(scope,element,attrs){function updateAlign(align){"top"===align||"center"===align||"bottom"===align?(element.removeClass("col-top col-center col-bottom"),element.addClass("col-"+align)):element.removeClass("col-top col-center col-bottom")}function updateWidth(width){"string"==typeof width?(width=(""+width).trim(),width=width.match(/^\d+$/)?width+"%":width,element.css({"-webkit-box-flex":"0","-webkit-flex":"0 0 "+width,"-moz-box-flex":"0","-moz-flex":"0 0 "+width,"-ms-flex":"0 0 "+width,flex:"0 0 "+width,"max-width":width})):element.removeAttr("style")}attrs.$observe("align",function(align){updateAlign(align)}),attrs.$observe("width",function(width){updateWidth(width)}),attrs.$observe("size",function(size){attrs.width||updateWidth(size)}),updateAlign(attrs.align),attrs.size&&!attrs.width?updateWidth(attrs.size):updateWidth(attrs.width),$onsen.cleaner.onDestroy(scope,function(){$onsen.clearComponent({scope:scope,element:element,attrs:attrs}),element=attrs=scope=null}),$onsen.fireComponentEvent(element[0],"init")}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsDialog",["$onsen","DialogView",function($onsen,DialogView){return{restrict:"E",replace:!1,scope:!0,transclude:!0,templateUrl:$onsen.DIRECTIVE_TEMPLATE_URL+"/dialog.tpl",compile:function(element,attrs,transclude){return element[0].setAttribute("no-status-bar-fill",""),{pre:function(scope,element,attrs){transclude(scope,function(clone){angular.element(element[0].querySelector(".dialog")).append(clone)});var dialog=new DialogView(scope,element,attrs);scope.modifierTemplater=$onsen.generateModifierTemplater(attrs),$onsen.addModifierMethods(dialog,"dialog--*",angular.element(element[0].querySelector(".dialog"))),$onsen.declareVarAttribute(attrs,dialog),element.data("ons-dialog",dialog),scope.$on("$destroy",function(){dialog._events=void 0,$onsen.removeModifierMethods(dialog),element.data("ons-dialog",void 0),element=null})},post:function(scope,element){$onsen.fireComponentEvent(element[0],"init")}}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsDummyForInit",["$rootScope",function($rootScope){var isReady=!1;return{restrict:"E",replace:!1,link:{post:function(scope,element){isReady||(isReady=!0,$rootScope.$broadcast("$ons-ready")),element.remove()}}}}])}(),function(){"use strict";var EVENTS="drag dragleft dragright dragup dragdown hold release swipe swipeleft swiperight swipeup swipedown tap doubletap touch transform pinch pinchin pinchout rotate".split(/ +/);angular.module("onsen").directive("onsGestureDetector",["$onsen",function($onsen){function titlize(str){return str.charAt(0).toUpperCase()+str.slice(1)}var scopeDef=EVENTS.reduce(function(dict,name){return dict["ng"+titlize(name)]="&",dict},{});return{restrict:"E",scope:scopeDef,replace:!1,transclude:!0,compile:function(){return function(scope,element,attrs,controller,transclude){function handleEvent(event){var attr="ng"+titlize(event.type);attr in scopeDef&&scope[attr]({$event:event})}transclude(scope.$parent,function(cloned){element.append(cloned)});var hammer=new Hammer(element[0]);hammer.on(EVENTS.join(" "),handleEvent),$onsen.cleaner.onDestroy(scope,function(){hammer.off(EVENTS.join(" "),handleEvent),$onsen.clearComponent({scope:scope,element:element,attrs:attrs}),hammer.element=scope=element=attrs=null}),$onsen.fireComponentEvent(element[0],"init")}}}}])}(),function(){"use strict";function cleanClassAttribute(element){var classList=(""+element.attr("class")).split(/ +/).filter(function(classString){return"fa"!==classString&&"fa-"!==classString.substring(0,3)&&"ion-"!==classString.substring(0,4)});element.attr("class",classList.join(" "))}function buildClassAndStyle(attrs){var classList=["ons-icon"],style={};0===attrs.icon.indexOf("ion-")?(classList.push(attrs.icon),classList.push("ons-icon--ion")):0===attrs.icon.indexOf("fa-")?(classList.push(attrs.icon),classList.push("fa")):(classList.push("fa"),classList.push("fa-"+attrs.icon));var size=""+attrs.size;return size.match(/^[1-5]x|lg$/)?classList.push("fa-"+size):"string"==typeof attrs.size?style["font-size"]=size:classList.push("fa-lg"),{"class":classList.join(" "),style:style}}var module=angular.module("onsen");module.directive("onsIcon",["$onsen",function($onsen){return{restrict:"E",replace:!1,transclude:!1,link:function(scope,element,attrs){if(attrs.ngController)throw new Error("This element can't accept ng-controller directive.");var update=function(){cleanClassAttribute(element);var builded=buildClassAndStyle(attrs);element.css(builded.style),element.addClass(builded["class"])},builded=buildClassAndStyle(attrs);element.css(builded.style),element.addClass(builded["class"]),attrs.$observe("icon",update),attrs.$observe("size",update),attrs.$observe("fixedWidth",update),attrs.$observe("rotate",update),attrs.$observe("flip",update),attrs.$observe("spin",update),$onsen.cleaner.onDestroy(scope,function(){$onsen.clearComponent({scope:scope,element:element,attrs:attrs}),element=scope=attrs=null}),$onsen.fireComponentEvent(element[0],"init")}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsIfOrientation",["$onsen","$onsGlobal",function($onsen,$onsGlobal){return{restrict:"A",replace:!1,transclude:!1,scope:!1,compile:function(element){return element.css("display","none"),function(scope,element,attrs){function update(){var userOrientation=(""+attrs.onsIfOrientation).toLowerCase(),orientation=getLandscapeOrPortrait();("portrait"===userOrientation||"landscape"===userOrientation)&&(userOrientation===orientation?element.css("display",""):element.css("display","none"))}function getLandscapeOrPortrait(){return $onsGlobal.orientation.isPortrait()?"portrait":"landscape"}element.addClass("ons-if-orientation-inner"),attrs.$observe("onsIfOrientation",update),$onsGlobal.orientation.on("change",update),update(),$onsen.cleaner.onDestroy(scope,function(){$onsGlobal.orientation.off("change",update),$onsen.clearComponent({element:element,scope:scope,attrs:attrs}),element=scope=attrs=null})}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsIfPlatform",["$onsen",function($onsen){return{restrict:"A",replace:!1,transclude:!1,scope:!1,compile:function(element){function getPlatformString(){if(navigator.userAgent.match(/Android/i))return"android";if(navigator.userAgent.match(/BlackBerry/i)||navigator.userAgent.match(/RIM Tablet OS/i)||navigator.userAgent.match(/BB10/i))return"blackberry";if(navigator.userAgent.match(/iPhone|iPad|iPod/i))return"ios";if(navigator.userAgent.match(/IEMobile/i))return"windows";var isOpera=!!window.opera||navigator.userAgent.indexOf(" OPR/")>=0;if(isOpera)return"opera";var isFirefox="undefined"!=typeof InstallTrigger;if(isFirefox)return"firefox";var isSafari=Object.prototype.toString.call(window.HTMLElement).indexOf("Constructor")>0;if(isSafari)return"safari";var isChrome=!!window.chrome&&!isOpera;if(isChrome)return"chrome";var isIE=!1||!!document.documentMode;return isIE?"ie":"unknown"}element.addClass("ons-if-platform-inner"),element.css("display","none");var platform=getPlatformString();return function(scope,element,attrs){function update(){attrs.onsIfPlatform.toLowerCase()===platform.toLowerCase()?element.css("display","block"):element.css("display","none")}attrs.$observe("onsIfPlatform",function(userPlatform){userPlatform&&update()}),update(),$onsen.cleaner.onDestroy(scope,function(){$onsen.clearComponent({element:element,scope:scope,attrs:attrs}),element=scope=attrs=null})}}}}])}(),function(){"use strict";var module=angular.module("onsen"),compileFunction=function(show,$onsen){return function(){return function(scope,element,attrs){var dispShow=show?"block":"none",dispHide=show?"none":"block",onShow=function(){element.css("display",dispShow)},onHide=function(){element.css("display",dispHide)},onInit=function(e){e.visible?onShow():onHide()};ons.softwareKeyboard.on("show",onShow),ons.softwareKeyboard.on("hide",onHide),ons.softwareKeyboard.on("init",onInit),ons.softwareKeyboard._visible?onShow():onHide(),$onsen.cleaner.onDestroy(scope,function(){ons.softwareKeyboard.off("show",onShow),ons.softwareKeyboard.off("hide",onHide),ons.softwareKeyboard.off("init",onInit),$onsen.clearComponent({element:element,scope:scope,attrs:attrs}),element=scope=attrs=null})}}};module.directive("onsKeyboardActive",["$onsen",function($onsen){return{restrict:"A",replace:!1,transclude:!1,scope:!1,compile:compileFunction(!0,$onsen)}}]),module.directive("onsKeyboardInactive",["$onsen",function($onsen){return{restrict:"A",replace:!1,transclude:!1,scope:!1,compile:compileFunction(!1,$onsen)}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsLazyRepeat",["$onsen","LazyRepeatView",function($onsen,LazyRepeatView){return{restrict:"A",replace:!1,transclude:"element",compile:function(element,attrs,linker){return function(scope,element,attrs){new LazyRepeatView(scope,element,attrs,linker);scope.$on("$destroy",function(){scope=element=attrs=linker=null})}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsList",["$onsen","GenericView",function($onsen,GenericView){return{restrict:"E",scope:!1,replace:!1,transclude:!1,compile:function(){return function(scope,element,attrs){var list=new GenericView(scope,element,attrs);$onsen.declareVarAttribute(attrs,list),element.data("ons-list",list),scope.$on("$destroy",function(){list._events=void 0,$onsen.removeModifierMethods(list),element.data("ons-list",void 0),element=null});var templater=$onsen.generateModifierTemplater(attrs);element.addClass("list ons-list-inner"),element.addClass(templater("list--*")),$onsen.addModifierMethods(list,"list--*",element),$onsen.fireComponentEvent(element[0],"init")}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsListHeader",["$onsen","GenericView",function($onsen,GenericView){return{restrict:"E",replace:!1,transclude:!1,compile:function(){return function(scope,element,attrs){var listHeader=new GenericView(scope,element,attrs);$onsen.declareVarAttribute(attrs,listHeader),element.data("ons-listHeader",listHeader),scope.$on("$destroy",function(){listHeader._events=void 0,$onsen.removeModifierMethods(listHeader),element.data("ons-listHeader",void 0),element=null});var templater=$onsen.generateModifierTemplater(attrs);element.addClass("list__header ons-list-header-inner"),element.addClass(templater("list__header--*")),$onsen.addModifierMethods(listHeader,"list__header--*",element),$onsen.fireComponentEvent(element[0],"init")}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsListItem",["$onsen","GenericView",function($onsen,GenericView){return{restrict:"E",replace:!1,transclude:!1,compile:function(){return function(scope,element,attrs){var listItem=new GenericView(scope,element,attrs);$onsen.declareVarAttribute(attrs,listItem),element.data("ons-list-item",listItem),scope.$on("$destroy",function(){listItem._events=void 0,$onsen.removeModifierMethods(listItem),element.data("ons-list-item",void 0),element=null});var templater=$onsen.generateModifierTemplater(attrs);element.addClass("list__item ons-list-item-inner"),element.addClass(templater("list__item--*")),$onsen.addModifierMethods(listItem,"list__item--*",element),$onsen.fireComponentEvent(element[0],"init")}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsLoadingPlaceholder",["$onsen","$compile",function($onsen){return{restrict:"A",replace:!1,transclude:!1,scope:!1,compile:function(element,attrs){if(!attrs.onsLoadingPlaceholder.length)throw Error("Must define page to load.");$onsen.getPageHTMLAsync(attrs.onsLoadingPlaceholder).then(function(html){setImmediate(function(){var div=document.createElement("div");div.innerHTML=html.trim();var newElement=angular.element(div);newElement.css("display","none"),element.append(newElement),ons.compile(newElement[0]),angular.element(element.children()[0]).remove(),newElement.css("display","block")})})}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsModal",["$onsen","ModalView",function($onsen,ModalView){function compile(element,attrs){var modifierTemplater=$onsen.generateModifierTemplater(attrs),html=element[0].innerHTML;element[0].innerHTML="";var wrapper=angular.element("<div></div>");wrapper.addClass("modal__content"),wrapper.addClass(modifierTemplater("modal--*__content")),element.css("display","none"),element.addClass("modal"),element.addClass(modifierTemplater("modal--*")),wrapper[0].innerHTML=html,element.append(wrapper)}return{restrict:"E",replace:!1,scope:!1,transclude:!1,compile:function(element,attrs){return compile(element,attrs),{pre:function(scope,element,attrs){var page=element.inheritedData("ons-page");page&&page.registerExtraElement(element);var modal=new ModalView(scope,element);$onsen.addModifierMethods(modal,"modal--*",element),$onsen.addModifierMethods(modal,"modal--*__content",element.children()),$onsen.declareVarAttribute(attrs,modal),element.data("ons-modal",modal),scope.$on("$destroy",function(){modal._events=void 0,$onsen.removeModifierMethods(modal),element.data("ons-modal",void 0)})},post:function(scope,element){$onsen.fireComponentEvent(element[0],"init")}}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsNavigator",["$compile","NavigatorView","$onsen",function($compile,NavigatorView,$onsen){return{restrict:"E",transclude:!1,scope:!0,compile:function(element){var html=$onsen.normalizePageHTML(element.html());return element.contents().remove(),{pre:function(scope,element,attrs){var navigator=new NavigatorView({scope:scope,element:element});if($onsen.declareVarAttribute(attrs,navigator),attrs.page)navigator.pushPage(attrs.page,{});else{var pageScope=navigator._createPageScope(),pageElement=angular.element(html),linkScope=$compile(pageElement),link=function(){linkScope(pageScope)};navigator._pushPageDOM("",pageElement,link,pageScope,{}),pageElement=null}element.data("ons-navigator",navigator),scope.$on("$destroy",function(){navigator._events=void 0,element.data("ons-navigator",void 0),element=null})},post:function(scope,element){$onsen.fireComponentEvent(element[0],"init")}}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsPage",["$onsen","PageView",function($onsen,PageView){function firePageInitEvent(element){var i=0,f=function(){if(!(i++<5))throw new Error('Fail to fire "pageinit" event. Attach "ons-page" element to the document after initialization.');isAttached(element)?(fillStatusBar(element),$onsen.fireComponentEvent(element,"init"),fireActualPageInitEvent(element)):setImmediate(f)};f()}function fireActualPageInitEvent(element){var event=document.createEvent("HTMLEvents");event.initEvent("pageinit",!0,!0),element.dispatchEvent(event)}function fillStatusBar(element){if($onsen.shouldFillStatusBar(element)){var fill=angular.element(document.createElement("div"));fill.addClass("page__status-bar-fill"),fill.css({width:"0px",height:"0px"}),angular.element(element).prepend(fill)}}function isAttached(element){return document.documentElement===element?!0:element.parentNode?isAttached(element.parentNode):!1}function preLink(scope,element,attrs){var page=new PageView(scope,element,attrs);$onsen.declareVarAttribute(attrs,page),element.data("ons-page",page);var modifierTemplater=$onsen.generateModifierTemplater(attrs),template="page--*";element.addClass("page "+modifierTemplater(template)),$onsen.addModifierMethods(page,template,element);var pageContent=angular.element(element[0].querySelector(".page__content"));pageContent.addClass(modifierTemplater("page--*__content")),pageContent=null;var pageBackground=angular.element(element[0].querySelector(".page__background"));pageBackground.addClass(modifierTemplater("page--*__background")),pageBackground=null,$onsen.cleaner.onDestroy(scope,function(){page._events=void 0,$onsen.removeModifierMethods(page),element.data("ons-page",void 0),$onsen.clearComponent({element:element,scope:scope,attrs:attrs}),scope=element=attrs=null})}function postLink(scope,element){firePageInitEvent(element[0])}return{restrict:"E",transclude:!1,scope:!1,compile:function(element){var children=element.children().remove(),content=angular.element('<div class="page__content ons-page-inner"></div>').append(children),background=angular.element('<div class="page__background"></div>');if(element.attr("style")&&(background.attr("style",element.attr("style")),element.attr("style","")),element.append(background),Modernizr.csstransforms3d)element.append(content);else{content.css("overflow","visible");var wrapper=angular.element("<div></div>");wrapper.append(children),content.append(wrapper),element.append(content),wrapper=null;var scroller=new IScroll(content[0],{momentum:!0,bounce:!0,hScrollbar:!1,vScrollbar:!1,preventDefault:!1}),offset=10;scroller.on("scrollStart",function(){var scrolled=scroller.y-offset;scrolled<scroller.maxScrollY+40&&scroller.refresh()})}return content=null,background=null,children=null,{pre:preLink,post:postLink}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsPopover",["$onsen","PopoverView",function($onsen,PopoverView){return{restrict:"E",replace:!1,transclude:!0,scope:!0,templateUrl:$onsen.DIRECTIVE_TEMPLATE_URL+"/popover.tpl",compile:function(element,attrs,transclude){return{pre:function(scope,element,attrs){transclude(scope,function(clone){angular.element(element[0].querySelector(".popover__content")).append(clone)});var popover=new PopoverView(scope,element,attrs);$onsen.declareVarAttribute(attrs,popover),element.data("ons-popover",popover),scope.$on("$destroy",function(){popover._events=void 0,$onsen.removeModifierMethods(popover),element.data("ons-popover",void 0),element=null}),scope.modifierTemplater=$onsen.generateModifierTemplater(attrs),$onsen.addModifierMethods(popover,"popover--*",angular.element(element[0].querySelector(".popover"))),$onsen.addModifierMethods(popover,"popover__content--*",angular.element(element[0].querySelector(".popover__content"))),$onsen.isAndroid()&&setImmediate(function(){popover.addModifier("android")}),scope.direction="up",scope.arrowPosition="bottom"},post:function(scope,element){$onsen.fireComponentEvent(element[0],"init")}}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsPullHook",["$onsen","PullHookView",function($onsen,PullHookView){return{restrict:"E",replace:!1,scope:!0,compile:function(){return{pre:function(scope,element,attrs){var pullHook=new PullHookView(scope,element,attrs);$onsen.declareVarAttribute(attrs,pullHook),element.data("ons-pull-hook",pullHook),scope.$on("$destroy",function(){pullHook._events=void 0,element.data("ons-pull-hook",void 0),scope=element=attrs=null})},post:function(scope,element){$onsen.fireComponentEvent(element[0],"init")}}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsRow",["$onsen","$timeout",function($onsen){return{restrict:"E",replace:!1,transclude:!1,scope:!1,compile:function(element){return element.addClass("row ons-row-inner"),function(scope,element,attrs){function update(){var align=(""+attrs.align).trim();("top"===align||"center"===align||"bottom"===align)&&(element.removeClass("row-bottom row-center row-top"),element.addClass("row-"+align))}attrs.$observe("align",function(){update()}),update(),$onsen.fireComponentEvent(element[0],"init")}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsScroller",["$onsen","$timeout",function($onsen,$timeout){return{restrict:"E",replace:!1,transclude:!0,scope:{onScrolled:"&",infinitScrollEnable:"="},compile:function(element){element.addClass("ons-scroller").children().remove();return function(scope,element,attrs,controller,transclude){if(attrs.ngController)throw new Error('"ons-scroller" can\'t accept "ng-controller" directive.');var wrapper=angular.element("<div></div>");wrapper.addClass("ons-scroller__content ons-scroller-inner"),element.append(wrapper),transclude(scope.$parent,function(cloned){wrapper.append(cloned),wrapper=null});var scrollWrapper;scrollWrapper=element[0];var offset=parseInt(attrs.threshold)||10;scope.onScrolled&&scrollWrapper.addEventListener("scroll",function(){if(scope.infinitScrollEnable){var scrollTopAndOffsetHeight=scrollWrapper.scrollTop+scrollWrapper.offsetHeight,scrollHeightMinusOffset=scrollWrapper.scrollHeight-offset;scrollTopAndOffsetHeight>=scrollHeightMinusOffset&&scope.onScrolled()}}),Modernizr.csstransforms3d||$timeout(function(){var iScroll=new IScroll(scrollWrapper,{momentum:!0,bounce:!0,hScrollbar:!1,vScrollbar:!1,preventDefault:!1});iScroll.on("scrollStart",function(){var scrolled=iScroll.y-offset;scrolled<iScroll.maxScrollY+40&&iScroll.refresh()}),scope.onScrolled&&iScroll.on("scrollEnd",function(){var scrolled=iScroll.y-offset;scrolled<iScroll.maxScrollY&&scope.onScrolled()})},500),$onsen.fireComponentEvent(element[0],"init")}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsSlidingMenu",["$compile","SlidingMenuView","$onsen",function($compile,SlidingMenuView,$onsen){return{restrict:"E",replace:!1,transclude:!1,scope:!0,compile:function(element){var main=element[0].querySelector(".main"),menu=element[0].querySelector(".menu");if(main)var mainHtml=angular.element(main).remove().html().trim();if(menu)var menuHtml=angular.element(menu).remove().html().trim();return function(scope,element,attrs){if(attrs.ngController)throw new Error("This element can't accept ng-controller directive.");element.append(angular.element("<div></div>").addClass("onsen-sliding-menu__menu ons-sliding-menu-inner")),element.append(angular.element("<div></div>").addClass("onsen-sliding-menu__main ons-sliding-menu-inner"));var slidingMenu=new SlidingMenuView(scope,element,attrs);mainHtml&&!attrs.mainPage&&slidingMenu._appendMainPage(null,mainHtml),menuHtml&&!attrs.menuPage&&slidingMenu._appendMenuPage(menuHtml),$onsen.declareVarAttribute(attrs,slidingMenu),element.data("ons-sliding-menu",slidingMenu),scope.$on("$destroy",function(){slidingMenu._events=void 0,element.data("ons-sliding-menu",void 0)}),$onsen.fireComponentEvent(element[0],"init")}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsSplitView",["$compile","SplitView","$onsen",function($compile,SplitView,$onsen){return{restrict:"E",replace:!1,transclude:!1,scope:{secondaryPage:"@",mainPage:"@",collapse:"@",mainPageWidth:"@"},compile:function(element){var mainPage=element[0].querySelector(".main-page"),secondaryPage=element[0].querySelector(".secondary-page");if(mainPage)var mainHtml=angular.element(mainPage).remove().html().trim();if(secondaryPage)var secondaryHtml=angular.element(secondaryPage).remove().html().trim();return function(scope,element,attrs){if(attrs.ngController)throw new Error("This element can't accept ng-controller directive.");element.append(angular.element("<div></div>").addClass("onsen-split-view__secondary full-screen ons-split-view-inner")),element.append(angular.element("<div></div>").addClass("onsen-split-view__main full-screen ons-split-view-inner"));var splitView=new SplitView(scope,element,attrs);mainHtml&&!attrs.mainPage&&splitView._appendMainPage(mainHtml),secondaryHtml&&!attrs.secondaryPage&&splitView._appendSecondPage(secondaryHtml),$onsen.declareVarAttribute(attrs,splitView),element.data("ons-split-view",splitView),scope.$on("$destroy",function(){splitView._events=void 0,element.data("ons-split-view",void 0)}),$onsen.fireComponentEvent(element[0],"init")}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsSwitch",["$onsen","$parse","SwitchView",function($onsen,$parse,SwitchView){return{restrict:"E",replace:!1,transclude:!1,scope:!0,templateUrl:$onsen.DIRECTIVE_TEMPLATE_URL+"/switch.tpl",compile:function(){return function(scope,element,attrs){if(attrs.ngController)throw new Error("This element can't accept ng-controller directive.");var switchView=new SwitchView(element,scope,attrs),checkbox=angular.element(element[0].querySelector("input[type=checkbox]"));scope.modifierTemplater=$onsen.generateModifierTemplater(attrs);var label=element.children(),input=angular.element(label.children()[0]),toggle=angular.element(label.children()[1]);if($onsen.addModifierMethods(switchView,"switch--*",label),$onsen.addModifierMethods(switchView,"switch--*__input",input),$onsen.addModifierMethods(switchView,"switch--*__toggle",toggle),attrs.$observe("checked",function(){scope.model=!!element.attr("checked")}),attrs.$observe("name",function(name){element.attr("name")&&checkbox.attr("name",name)}),attrs.ngModel){var set=$parse(attrs.ngModel).assign;scope.$parent.$watch(attrs.ngModel,function(value){scope.model=value}),scope.$watch("model",function(to,from){set(scope.$parent,to),to!==from&&scope.$eval(attrs.ngChange)})}$onsen.declareVarAttribute(attrs,switchView),element.data("ons-switch",switchView),$onsen.cleaner.onDestroy(scope,function(){switchView._events=void 0,$onsen.removeModifierMethods(switchView),element.data("ons-switch",void 0),$onsen.clearComponent({element:element,scope:scope,attrs:attrs}),checkbox=element=attrs=scope=null}),$onsen.fireComponentEvent(element[0],"init")}}}}])}(),function(){"use strict";function tab($onsen,$compile){return{restrict:"E",transclude:!0,scope:{page:"@",active:"@",icon:"@",activeIcon:"@",label:"@",noReload:"@",persistent:"@"},templateUrl:$onsen.DIRECTIVE_TEMPLATE_URL+"/tab.tpl",compile:function(element){return element.addClass("tab-bar__item"),function(scope,element,attrs,controller,transclude){var tabbarView=element.inheritedData("ons-tabbar");if(!tabbarView)throw new Error("This ons-tab element is must be child of ons-tabbar element.");element.addClass(tabbarView._scope.modifierTemplater("tab-bar--*__item")),element.addClass(tabbarView._scope.modifierTemplater("tab-bar__item--*")),transclude(scope.$parent,function(cloned){var wrapper=angular.element(element[0].querySelector(".tab-bar-inner"));if(attrs.icon||attrs.label||!cloned[0]){var innerElement=angular.element("<div>"+defaultInnerTemplate+"</div>").children();wrapper.append(innerElement),$compile(innerElement)(scope)}else wrapper.append(cloned)});var radioButton=element[0].querySelector("input");scope.tabbarModifierTemplater=tabbarView._scope.modifierTemplater,scope.modifierTemplater=$onsen.generateModifierTemplater(attrs),scope.tabbarId=tabbarView._tabbarId,scope.tabIcon=scope.icon,tabbarView.addTabItem(scope),scope.setActive=function(){element.addClass("active"),radioButton.checked=!0,scope.activeIcon&&(scope.tabIcon=scope.activeIcon),angular.element(element[0].querySelectorAll("[ons-tab-inactive]")).css("display","none"),angular.element(element[0].querySelectorAll("[ons-tab-active]")).css("display","inherit")},scope.setInactive=function(){element.removeClass("active"),radioButton.checked=!1,scope.tabIcon=scope.icon,angular.element(element[0].querySelectorAll("[ons-tab-inactive]")).css("display","inherit"),angular.element(element[0].querySelectorAll("[ons-tab-active]")).css("display","none")},scope.isPersistent=function(){return"undefined"!=typeof scope.persistent},scope.isActive=function(){return element.hasClass("active")},scope.tryToChange=function(){tabbarView.setActiveTab(tabbarView._tabItems.indexOf(scope))},scope.active&&tabbarView.setActiveTab(tabbarView._tabItems.indexOf(scope)),$onsen.fireComponentEvent(element[0],"init")}}}}var module=angular.module("onsen");module.directive("onsTab",tab),module.directive("onsTabbarItem",tab);var defaultInnerTemplate='<div ng-if="icon != undefined" class="tab-bar__icon"><ons-icon icon="{{tabIcon}}" style="font-size: 28px; line-height: 34px; vertical-align: top;"></ons-icon></div><div ng-if="label" class="tab-bar__label">{{label}}</div>';tab.$inject=["$onsen","$compile"]}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsTabbar",["$onsen","$compile","TabbarView",function($onsen,$compile,TabbarView){return{restrict:"E",replace:!1,transclude:!0,scope:{onActiveTabChanged:"&"},templateUrl:$onsen.DIRECTIVE_TEMPLATE_URL+"/tab_bar.tpl",link:function(scope,element,attrs,controller,transclude){if(attrs.ngController)throw new Error("This element can't accept ng-controller directive.");scope.modifierTemplater=$onsen.generateModifierTemplater(attrs),scope.selectedTabItem={source:""},attrs.$observe("hideTabs",function(hide){var visible="true"!==hide;tabbarView.setTabbarVisibility(visible)});var tabbarView=new TabbarView(scope,element,attrs);$onsen.addModifierMethods(tabbarView,"tab-bar--*",angular.element(element.children()[1])),scope.tabbarId=tabbarView._tabbarId,element.data("ons-tabbar",tabbarView),$onsen.declareVarAttribute(attrs,tabbarView),transclude(function(cloned){angular.element(element[0].querySelector(".ons-tabbar-inner")).append(cloned) }),scope.$on("$destroy",function(){tabbarView._events=void 0,$onsen.removeModifierMethods(tabbarView),element.data("ons-tabbar",void 0)}),$onsen.fireComponentEvent(element[0],"init")}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsTemplate",["$onsen","$templateCache",function($onsen,$templateCache){return{restrict:"E",transclude:!1,priority:1e3,terminal:!0,compile:function(element){$templateCache.put(element.attr("id"),element.remove().html()),$onsen.fireComponentEvent(element[0],"init")}}}])}(),function(){"use strict";function ensureLeftContainer(element,modifierTemplater){var container=element[0].querySelector(".left");return container||(container=document.createElement("div"),container.setAttribute("class","left"),container.innerHTML="&nbsp;"),""===container.innerHTML.trim()&&(container.innerHTML="&nbsp;"),angular.element(container).addClass("navigation-bar__left").addClass(modifierTemplater("navigation-bar--*__left")),container}function ensureCenterContainer(element,modifierTemplater){var container=element[0].querySelector(".center");return container||(container=document.createElement("div"),container.setAttribute("class","center")),""===container.innerHTML.trim()&&(container.innerHTML="&nbsp;"),angular.element(container).addClass("navigation-bar__title navigation-bar__center").addClass(modifierTemplater("navigation-bar--*__center")),container}function ensureRightContainer(element,modifierTemplater){var container=element[0].querySelector(".right");return container||(container=document.createElement("div"),container.setAttribute("class","right"),container.innerHTML="&nbsp;"),""===container.innerHTML.trim()&&(container.innerHTML="&nbsp;"),angular.element(container).addClass("navigation-bar__right").addClass(modifierTemplater("navigation-bar--*__right")),container}function hasCenterClassElementOnly(element){for(var child,hasCenter=!1,hasOther=!1,children=element.contents(),i=0;i<children.length;i++)child=angular.element(children[i]),child.hasClass("center")?hasCenter=!0:(child.hasClass("left")||child.hasClass("right"))&&(hasOther=!0);return hasCenter&&!hasOther}function ensureToolbarItemElements(element,modifierTemplater){var center;if(hasCenterClassElementOnly(element))center=ensureCenterContainer(element,modifierTemplater),element.contents().remove(),element.append(center);else{center=ensureCenterContainer(element,modifierTemplater);var left=ensureLeftContainer(element,modifierTemplater),right=ensureRightContainer(element,modifierTemplater);element.contents().remove(),element.append(angular.element([left,center,right]))}}var module=angular.module("onsen");module.directive("onsToolbar",["$onsen","GenericView",function($onsen,GenericView){return{restrict:"E",replace:!1,scope:!1,transclude:!1,compile:function(element,attrs){var shouldAppendAndroidModifier=ons.platform.isAndroid()&&!element[0].hasAttribute("fixed-style"),modifierTemplater=$onsen.generateModifierTemplater(attrs,shouldAppendAndroidModifier?["android"]:[]),inline="undefined"!=typeof attrs.inline;return element.addClass("navigation-bar"),element.addClass(modifierTemplater("navigation-bar--*")),inline||element.css({position:"absolute","z-index":"10000",left:"0px",right:"0px",top:"0px"}),ensureToolbarItemElements(element,modifierTemplater),{pre:function(scope,element,attrs){var toolbar=new GenericView(scope,element,attrs);$onsen.declareVarAttribute(attrs,toolbar),scope.$on("$destroy",function(){toolbar._events=void 0,$onsen.removeModifierMethods(toolbar),element.data("ons-toolbar",void 0),element=null}),$onsen.addModifierMethods(toolbar,"navigation-bar--*",element),angular.forEach(["left","center","right"],function(position){var el=element[0].querySelector(".navigation-bar__"+position);el&&$onsen.addModifierMethods(toolbar,"navigation-bar--*__"+position,angular.element(el))});var pageView=element.inheritedData("ons-page");pageView&&!inline&&pageView.registerToolbar(element),element.data("ons-toolbar",toolbar)},post:function(scope,element){$onsen.fireComponentEvent(element[0],"init")}}}}}])}(),function(){"use strict";var module=angular.module("onsen");module.directive("onsToolbarButton",["$onsen","GenericView",function($onsen,GenericView){return{restrict:"E",transclude:!0,scope:{},templateUrl:$onsen.DIRECTIVE_TEMPLATE_URL+"/toolbar_button.tpl",link:{pre:function(scope,element,attrs){var toolbarButton=new GenericView(scope,element,attrs),innerElement=element[0].querySelector(".toolbar-button");$onsen.declareVarAttribute(attrs,toolbarButton),element.data("ons-toolbar-button",toolbarButton),scope.$on("$destroy",function(){toolbarButton._events=void 0,$onsen.removeModifierMethods(toolbarButton),element.data("ons-toolbar-button",void 0),element=null});var modifierTemplater=$onsen.generateModifierTemplater(attrs);if(attrs.ngController)throw new Error("This element can't accept ng-controller directive.");attrs.$observe("disabled",function(value){value===!1||"undefined"==typeof value?innerElement.removeAttribute("disabled"):innerElement.setAttribute("disabled","disabled")}),scope.modifierTemplater=$onsen.generateModifierTemplater(attrs),$onsen.addModifierMethods(toolbarButton,"toolbar-button--*",element.children()),element.children("span").addClass(modifierTemplater("toolbar-button--*")),$onsen.cleaner.onDestroy(scope,function(){$onsen.clearComponent({scope:scope,attrs:attrs,element:element}),scope=element=attrs=null})},post:function(scope,element){$onsen.fireComponentEvent(element[0],"init")}}}}])}(),function(){"use strict";var module=angular.module("onsen"),ComponentCleaner={decomposeNode:function(element){for(var children=element.remove().children(),i=0;i<children.length;i++)ComponentCleaner.decomposeNode(angular.element(children[i]))},destroyAttributes:function(attrs){attrs.$$element=null,attrs.$$observers=null},destroyElement:function(element){element.remove()},destroyScope:function(scope){scope.$$listeners={},scope.$$watchers=null,scope=null},onDestroy:function(scope,fn){var clear=scope.$on("$destroy",function(){clear(),fn.apply(null,arguments)})}};module.factory("ComponentCleaner",function(){return ComponentCleaner}),function(){var ngEventDirectives={};"click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste".split(" ").forEach(function(name){function directiveNormalize(name){return name.replace(/-([a-z])/g,function(matches){return matches[1].toUpperCase()})}var directiveName=directiveNormalize("ng-"+name);ngEventDirectives[directiveName]=["$parse",function($parse){return{compile:function($element,attr){var fn=$parse(attr[directiveName]);return function(scope,element,attr){var listener=function(event){scope.$apply(function(){fn(scope,{$event:event})})};element.on(name,listener),ComponentCleaner.onDestroy(scope,function(){element.off(name,listener),element=null,ComponentCleaner.destroyScope(scope),scope=null,ComponentCleaner.destroyAttributes(attr),attr=null})}}}}]}),module.config(["$provide",function($provide){var shift=function($delegate){return $delegate.shift(),$delegate};Object.keys(ngEventDirectives).forEach(function(directiveName){$provide.decorator(directiveName+"Directive",["$delegate",shift])})}]),Object.keys(ngEventDirectives).forEach(function(directiveName){module.directive(directiveName,ngEventDirectives[directiveName])})}()}(),function(){"use strict";var util={init:function(){this.ready=!1},addBackButtonListener:function(fn){this._ready?window.document.addEventListener("backbutton",fn,!1):window.document.addEventListener("deviceready",function(){window.document.addEventListener("backbutton",fn,!1)})},removeBackButtonListener:function(fn){this._ready?window.document.removeEventListener("backbutton",fn,!1):window.document.addEventListener("deviceready",function(){window.document.removeEventListener("backbutton",fn,!1)})}};util.init(),angular.module("onsen").service("DeviceBackButtonHandler",function(){this._init=function(){window.ons.isWebView()?window.document.addEventListener("deviceready",function(){util._ready=!0},!1):util._ready=!0,this._bindedCallback=this._callback.bind(this),this.enable()},this._isEnabled=!1,this.enable=function(){this._isEnabled||(util.addBackButtonListener(this._bindedCallback),this._isEnabled=!0)},this.disable=function(){this._isEnabled&&(util.removeBackButtonListener(this._bindedCallback),this._isEnabled=!1)},this.fireDeviceBackButtonEvent=function(){var event=document.createEvent("Event");event.initEvent("backbutton",!0,!0),document.dispatchEvent(event)},this._callback=function(){this._dispatchDeviceBackButtonEvent()},this.create=function(element,callback){if(!(element instanceof angular.element().constructor))throw new Error("element must be an instance of jqLite");if(!(callback instanceof Function))throw new Error("callback must be an instance of Function");var handler={_callback:callback,_element:element,disable:function(){this._element.data("device-backbutton-handler",null)},setListener:function(callback){this._callback=callback},enable:function(){this._element.data("device-backbutton-handler",this)},isEnabled:function(){return this._element.data("device-backbutton-handler")===this},destroy:function(){this._element.data("device-backbutton-handler",null),this._callback=this._element=null}};return handler.enable(),handler},this._dispatchDeviceBackButtonEvent=function(){function createEvent(element){return{_element:element,callParentHandler:function(){for(var parent=this._element.parent();parent[0];){if(handler=parent.data("device-backbutton-handler"))return handler._callback(createEvent(parent));parent=parent.parent()}}}}var tree=this._captureTree(),element=this._findHandlerLeafElement(tree),handler=element.data("device-backbutton-handler");handler._callback(createEvent(element))},this._dumpParents=function(element){for(;element[0];)console.log(element[0].nodeName.toLowerCase()+"."+element.attr("class")),element=element.parent()},this._captureTree=function(){function createTree(element){return{element:element,children:Array.prototype.concat.apply([],Array.prototype.map.call(element.children(),function(child){if(child=angular.element(child),"none"===child[0].style.display)return[];if(0===child.children().length&&!child.data("device-backbutton-handler"))return[];var result=createTree(child);return 0!==result.children.length||child.data("device-backbutton-handler")?[result]:[]}))}}return createTree(angular.element(document.body))},this._dumpTree=function(node){function _dump(node,level){var pad=new Array(level+1).join(" ");console.log(pad+node.element[0].nodeName.toLowerCase()),node.children.forEach(function(node){_dump(node,level+1)})}_dump(node,0)},this._findHandlerLeafElement=function(tree){function find(node){return 0===node.children.length?node.element:1===node.children.length?find(node.children[0]):node.children.map(function(childNode){return childNode.element}).reduce(function(left,right){if(null===left)return right;var leftZ=parseInt(window.getComputedStyle(left[0],"").zIndex,10),rightZ=parseInt(window.getComputedStyle(right[0],"").zIndex,10);if(!isNaN(leftZ)&&!isNaN(rightZ))return leftZ>rightZ?left:right;throw new Error("Capturing backbutton-handler is failure.")},null)}return find(tree)},this._init()})}(),function(){"use strict";var module=angular.module("onsen");module.factory("$onsen",["$rootScope","$window","$cacheFactory","$document","$templateCache","$http","$q","$onsGlobal","ComponentCleaner","DeviceBackButtonHandler",function($rootScope,$window,$cacheFactory,$document,$templateCache,$http,$q,$onsGlobal,ComponentCleaner,DeviceBackButtonHandler){function createOnsenService(){return{DIRECTIVE_TEMPLATE_URL:"templates",cleaner:ComponentCleaner,DeviceBackButtonHandler:DeviceBackButtonHandler,_defaultDeviceBackButtonHandler:DeviceBackButtonHandler.create(angular.element(document.body),function(){navigator.app.exitApp()}),getDefaultDeviceBackButtonHandler:function(){return this._defaultDeviceBackButtonHandler},isEnabledAutoStatusBarFill:function(){return!!$onsGlobal._config.autoStatusBarFill},shouldFillStatusBar:function(element){if(this.isEnabledAutoStatusBarFill()&&this.isWebView()&&this.isIOS7Above()){if(!(element instanceof HTMLElement))throw new Error("element must be an instance of HTMLElement");for(var debug="ONS-TABBAR"===element.tagName?console.log.bind(console):angular.noop;;){if(element.hasAttribute("no-status-bar-fill"))return!1;if(element=element.parentNode,debug(element),!element||!element.hasAttribute)return!0}}return!1},clearComponent:function(params){params.scope&&ComponentCleaner.destroyScope(params.scope),params.attrs&&ComponentCleaner.destroyAttributes(params.attrs),params.element&&ComponentCleaner.destroyElement(params.element),params.elements&&params.elements.forEach(function(element){ComponentCleaner.destroyElement(element)})},upTo:function(el,tagName){tagName=tagName.toLowerCase();do{if(!el)return null;if(el=el.parentNode,el.tagName.toLowerCase()==tagName)return el}while(el.parentNode);return null},waitForVariables:function(dependencies,callback){unlockerDict.addCallback(dependencies,callback)},findElementeObject:function(element,name){return element.inheritedData(name)},getPageHTMLAsync:function(page){var cache=$templateCache.get(page);if(cache){var deferred=$q.defer(),html="string"==typeof cache?cache:cache[1];return deferred.resolve(this.normalizePageHTML(html)),deferred.promise}return $http({url:page,method:"GET"}).then(function(response){var html=response.data;return this.normalizePageHTML(html)}.bind(this))},normalizePageHTML:function(html){return html=(""+html).trim(),html.match(/^<(ons-page|ons-navigator|ons-tabbar|ons-sliding-menu|ons-split-view)/)||(html="<ons-page>"+html+"</ons-page>"),html},generateModifierTemplater:function(attrs,modifiers){var attrModifiers=attrs&&"string"==typeof attrs.modifier?attrs.modifier.trim().split(/ +/):[];return modifiers=angular.isArray(modifiers)?attrModifiers.concat(modifiers):attrModifiers,function(template){return modifiers.map(function(modifier){return template.replace("*",modifier)}).join(" ")}},addModifierMethods:function(view,template,element){var _tr=function(modifier){return template.replace("*",modifier)},fns={hasModifier:function(modifier){return element.hasClass(_tr(modifier))},removeModifier:function(modifier){element.removeClass(_tr(modifier))},addModifier:function(modifier){element.addClass(_tr(modifier))},setModifier:function(modifier){for(var classes=element.attr("class").split(/\s+/),patt=template.replace("*","."),i=0;i<classes.length;i++){var cls=classes[i];cls.match(patt)&&element.removeClass(cls)}element.addClass(_tr(modifier))},toggleModifier:function(modifier){var cls=_tr(modifier);element.hasClass(cls)?element.removeClass(cls):element.addClass(cls)}},append=function(oldFn,newFn){return"undefined"!=typeof oldFn?function(){return oldFn.apply(null,arguments)||newFn.apply(null,arguments)}:newFn};view.hasModifier=append(view.hasModifier,fns.hasModifier),view.removeModifier=append(view.removeModifier,fns.removeModifier),view.addModifier=append(view.addModifier,fns.addModifier),view.setModifier=append(view.setModifier,fns.setModifier),view.toggleModifier=append(view.toggleModifier,fns.toggleModifier)},removeModifierMethods:function(view){view.hasModifier=view.removeModifier=view.addModifier=view.setModifier=view.toggleModifier=void 0},declareVarAttribute:function(attrs,object){if("string"==typeof attrs["var"]){var varName=attrs["var"];this._defineVar(varName,object),unlockerDict.unlockVarName(varName)}},isAndroid:function(){return!!window.navigator.userAgent.match(/android/i)},isIOS:function(){return!!window.navigator.userAgent.match(/(ipad|iphone|ipod touch)/i)},isWebView:function(){return window.ons.isWebView()},isIOS7Above:function(){var ua=window.navigator.userAgent,match=ua.match(/(iPad|iPhone|iPod touch);.*CPU.*OS (\d+)_(\d+)/i),result=match?parseFloat(match[2]+"."+match[3])>=7:!1;return function(){return result}}(),fireComponentEvent:function(dom,eventName){var event=document.createEvent("HTMLEvents");event.component=dom?angular.element(dom).data(dom.nodeName.toLowerCase())||null:null,event.initEvent(dom.nodeName.toLowerCase()+":"+eventName,!0,!0),dom.dispatchEvent(event)},_defineVar:function(name,object){function set(container,names,object){for(var name,i=0;i<names.length-1;i++)name=names[i],(void 0===container[name]||null===container[name])&&(container[name]={}),container=container[name];container[names[names.length-1]]=object}var names=name.split(/\./);ons.componentBase&&set(ons.componentBase,names,object),set($rootScope,names,object)}}}function createUnlockerDict(){return{_unlockersDict:{},_unlockedVarDict:{},_addVarLock:function(name,unlocker){if(!(unlocker instanceof Function))throw new Error("unlocker argument must be an instance of Function.");this._unlockersDict[name]?this._unlockersDict[name].push(unlocker):this._unlockersDict[name]=[unlocker]},unlockVarName:function(varName){var unlockers=this._unlockersDict[varName];unlockers&&unlockers.forEach(function(unlock){unlock()}),this._unlockedVarDict[varName]=!0},addCallback:function(dependencies,callback){if(!(callback instanceof Function))throw new Error("callback argument must be an instance of Function.");var doorLock=new DoorLock,self=this;dependencies.forEach(function(varName){if(!self._unlockedVarDict[varName]){var unlock=doorLock.lock();self._addVarLock(varName,unlock)}}),doorLock.isLocked()?doorLock.waitUnlock(callback):callback()}}}var unlockerDict=createUnlockerDict(),$onsen=createOnsenService();return $onsen}])}(),window.animit=function(){"use strict";var Animit=function(element){if(!(this instanceof Animit))return new Animit(element);if(element instanceof HTMLElement)this.elements=[element];else{if("[object Array]"!==Object.prototype.toString.call(element))throw new Error("First argument must be an array or an instance of HTMLElement.");this.elements=element}this.transitionQueue=[],this.lastStyleAttributeDict=[];var self=this;this.elements.forEach(function(element,index){element.hasAttribute("data-animit-orig-style")?self.lastStyleAttributeDict[index]=element.getAttribute("data-animit-orig-style"):(self.lastStyleAttributeDict[index]=element.getAttribute("style"),element.setAttribute("data-animit-orig-style",self.lastStyleAttributeDict[index]||""))})};Animit.prototype={transitionQueue:void 0,element:void 0,play:function(callback){return"function"==typeof callback&&this.transitionQueue.push(function(done){callback(),done()}),this.startAnimation(),this},queue:function(transition,options){var queue=this.transitionQueue;if(transition&&options&&(options.css=transition,transition=new Animit.Transition(options)),transition instanceof Function||transition instanceof Animit.Transition||(transition=transition.css?new Animit.Transition(transition):new Animit.Transition({css:transition})),transition instanceof Function)queue.push(transition);else{if(!(transition instanceof Animit.Transition))throw new Error("Invalid arguments");queue.push(transition.build())}return this},wait:function(seconds){return this.transitionQueue.push(function(done){setTimeout(done,1e3*seconds)}),this},resetStyle:function(options){function reset(){self.elements.forEach(function(element,index){element.style[Animit.prefix+"Transition"]="none",element.style.transition="none",self.lastStyleAttributeDict[index]?element.setAttribute("style",self.lastStyleAttributeDict[index]):(element.setAttribute("style",""),element.removeAttribute("style"))})}options=options||{};var self=this;if(options.transition&&!options.duration)throw new Error('"options.duration" is required when "options.transition" is enabled.');if(options.transition||options.duration&&options.duration>0){var transitionValue=options.transition||"all "+options.duration+"s "+(options.timing||"linear"),transitionStyle="transition: "+transitionValue+"; -"+Animit.prefix+"-transition: "+transitionValue+";";this.transitionQueue.push(function(done){var elements=this.elements;elements.forEach(function(element,index){element.style[Animit.prefix+"Transition"]=transitionValue,element.style.transition=transitionValue;var styleValue=(self.lastStyleAttributeDict[index]?self.lastStyleAttributeDict[index]+"; ":"")+transitionStyle;element.setAttribute("style",styleValue)});var removeListeners=util.addOnTransitionEnd(elements[0],function(){clearTimeout(timeoutId),reset(),done()}),timeoutId=setTimeout(function(){removeListeners(),reset(),done()},1e3*options.duration*1.4)})}else this.transitionQueue.push(function(done){reset(),done()});return this},startAnimation:function(){return this._dequeueTransition(),this},_dequeueTransition:function(){var transition=this.transitionQueue.shift();if(this._currentTransition)throw new Error("Current transition exists.");this._currentTransition=transition;var self=this,called=!1,done=function(){if(called)throw new Error("Invalid state: This callback is called twice.");called=!0,self._currentTransition=void 0,self._dequeueTransition()};transition&&transition.call(this,done)}},Animit.cssPropertyDict=function(){var styles=window.getComputedStyle(document.documentElement,""),dict={},a="A".charCodeAt(0),z="z".charCodeAt(0);for(var key in styles)if(styles.hasOwnProperty(key)){{key.charCodeAt(0)}a<=key.charCodeAt(0)&&z>=key.charCodeAt(0)&&"cssText"!==key&&"parentText"!==key&&"length"!==key&&(dict[key]=!0)}return dict}(),Animit.hasCssProperty=function(name){return!!Animit.cssPropertyDict[name]},Animit.prefix=function(){var styles=window.getComputedStyle(document.documentElement,""),pre=(Array.prototype.slice.call(styles).join("").match(/-(moz|webkit|ms)-/)||""===styles.OLink&&["","o"])[1];return pre}(),Animit.runAll=function(){for(var i=0;i<arguments.length;i++)arguments[i].play()},Animit.Transition=function(options){this.options=options||{},this.options.duration=this.options.duration||0,this.options.timing=this.options.timing||"linear",this.options.css=this.options.css||{},this.options.property=this.options.property||"all"},Animit.Transition.prototype={build:function(){function createActualCssProps(css){var result={};return Object.keys(css).forEach(function(name){var value=css[name];name=util.normalizeStyleName(name);var prefixed=Animit.prefix+util.capitalize(name);Animit.cssPropertyDict[name]?result[name]=value:Animit.cssPropertyDict[prefixed]?result[prefixed]=value:(result[prefixed]=value,result[name]=value)}),result}if(0===Object.keys(this.options.css).length)throw new Error("options.css is required.");var css=createActualCssProps(this.options.css);if(this.options.duration>0){var transitionValue=util.buildTransitionValue(this.options),self=this;return function(callback){var elements=this.elements,timeout=1e3*self.options.duration*1.4,removeListeners=util.addOnTransitionEnd(elements[0],function(){clearTimeout(timeoutId),callback()}),timeoutId=setTimeout(function(){removeListeners(),callback()},timeout);elements.forEach(function(element){element.style[Animit.prefix+"Transition"]=transitionValue,element.style.transition=transitionValue,Object.keys(css).forEach(function(name){element.style[name]=css[name]})})}}return this.options.duration<=0?function(callback){var elements=this.elements;elements.forEach(function(element){element.style[Animit.prefix+"Transition"]="none",element.transition="none",Object.keys(css).forEach(function(name){element.style[name]=css[name]})}),elements.forEach(function(element){element.getBoundingClientRect()}),window.requestAnimationFrame?requestAnimationFrame(callback):setTimeout(callback,1e3/30)}:void 0}};var util={normalizeStyleName:function(name){return name=name.replace(/-[a-zA-Z]/g,function(all){return all.slice(1).toUpperCase()}),name.charAt(0).toLowerCase()+name.slice(1)},capitalize:function(str){return str.charAt(0).toUpperCase()+str.slice(1)},buildTransitionValue:function(params){params.property=params.property||"all",params.duration=params.duration||.4,params.timing=params.timing||"linear";var props=params.property.split(/ +/);return props.map(function(prop){return prop+" "+params.duration+"s "+params.timing}).join(", ")},addOnTransitionEnd:function(element,callback){if(!element)return function(){};var fn=function(event){element==event.target&&(event.stopPropagation(),removeListeners(),callback())},removeListeners=function(){util._transitionEndEvents.forEach(function(eventName){element.removeEventListener(eventName,fn)})};return util._transitionEndEvents.forEach(function(eventName){element.addEventListener(eventName,fn,!1)}),removeListeners},_transitionEndEvents:function(){return"webkit"===Animit.prefix||"o"===Animit.prefix||"moz"===Animit.prefix||"ms"===Animit.prefix?[Animit.prefix+"TransitionEnd","transitionend"]:["transitionend"]}()};return Animit}(),window.ons.notification=function(){var createAlertDialog=function(title,message,buttonLabels,primaryButtonIndex,modifier,animation,callback,messageIsHTML,cancelable,promptDialog,autofocus,placeholder){var inputEl,dialogEl=angular.element("<ons-alert-dialog>"),titleEl=angular.element("<div>").addClass("alert-dialog-title").text(title),messageEl=angular.element("<div>").addClass("alert-dialog-content"),footerEl=angular.element("<div>").addClass("alert-dialog-footer");modifier&&dialogEl.attr("modifier",modifier),dialogEl.attr("animation",animation),messageIsHTML?messageEl.html(message):messageEl.text(message),dialogEl.append(titleEl).append(messageEl),promptDialog&&(inputEl=angular.element("<input>").addClass("text-input").attr("placeholder",placeholder).css({width:"100%",marginTop:"10px"}),messageEl.append(inputEl)),dialogEl.append(footerEl),angular.element(document.body).append(dialogEl),ons.compile(dialogEl[0]);var alertDialog=dialogEl.data("ons-alert-dialog");buttonLabels.length<=2&&footerEl.addClass("alert-dialog-footer--one");for(var createButton=function(i){var buttonEl=angular.element("<button>").addClass("alert-dialog-button").text(buttonLabels[i]);i==primaryButtonIndex&&buttonEl.addClass("alert-dialog-button--primal"),buttonLabels.length<=2&&buttonEl.addClass("alert-dialog-button--one"),buttonEl.on("click",function(){alertDialog.hide({callback:function(){promptDialog?callback(inputEl.val()):callback(i),alertDialog.destroy(),alertDialog=null,inputEl=null}})}),footerEl.append(buttonEl),buttonEl=null},i=0;i<buttonLabels.length;i++)createButton(i);cancelable&&(alertDialog.setCancelable(cancelable),alertDialog.on("cancel",function(){promptDialog?callback(null):callback(-1),setTimeout(function(){alertDialog.destroy(),alertDialog=null,inputEl=null})})),alertDialog.show({callback:function(){promptDialog&&autofocus&&inputEl[0].focus()}}),dialogEl=titleEl=messageEl=footerEl=null};return{alert:function(options){var defaults={buttonLabel:"OK",animation:"default",title:"Alert",callback:function(){}};if(options=angular.extend({},defaults,options),!options.message&&!options.messageHTML)throw new Error("Alert dialog must contain a message.");createAlertDialog(options.title,options.message||options.messageHTML,[options.buttonLabel],0,options.modifier,options.animation,options.callback,options.message?!1:!0,!1,!1,!1)},confirm:function(options){var defaults={buttonLabels:["Cancel","OK"],primaryButtonIndex:1,animation:"default",title:"Confirm",callback:function(){},cancelable:!1};if(options=angular.extend({},defaults,options),!options.message&&!options.messageHTML)throw new Error("Confirm dialog must contain a message.");createAlertDialog(options.title,options.message||options.messageHTML,options.buttonLabels,options.primaryButtonIndex,options.modifier,options.animation,options.callback,options.message?!1:!0,options.cancelable,!1,!1)},prompt:function(options){var defaults={buttonLabel:"OK",animation:"default",title:"Alert",placeholder:"",callback:function(){},cancelable:!1,autofocus:!0};if(options=angular.extend({},defaults,options),!options.message&&!options.messageHTML)throw new Error("Prompt dialog must contain a message.");createAlertDialog(options.title,options.message||options.messageHTML,[options.buttonLabel],0,options.modifier,options.animation,options.callback,options.message?!1:!0,options.cancelable,!0,options.autofocus,options.placeholder)}}}(),window.ons.orientation=function(){function create(){var obj={_isPortrait:!1,isPortrait:function(){return this._isPortrait()},isLandscape:function(){return!this.isPortrait()},_init:function(){return document.addEventListener("DOMContentLoaded",this._onDOMContentLoaded.bind(this),!1),"orientation"in window?window.addEventListener("orientationchange",this._onOrientationChange.bind(this),!1):window.addEventListener("resize",this._onResize.bind(this),!1),this._isPortrait=function(){return window.innerHeight>window.innerWidth},this},_onDOMContentLoaded:function(){this._installIsPortraitImplementation(),this.emit("change",{isPortrait:this.isPortrait()})},_installIsPortraitImplementation:function(){var isPortrait=window.innerWidth<window.innerHeight;this._isPortrait="orientation"in window?window.orientation%180===0?function(){return 0===Math.abs(window.orientation%180)?isPortrait:!isPortrait}:function(){return 90===Math.abs(window.orientation%180)?isPortrait:!isPortrait}:function(){return window.innerHeight>window.innerWidth}},_onOrientationChange:function(){setImmediate(function(){this.emit("change",{isPortrait:this.isPortrait()})}.bind(this))},_onResize:function(){this.emit("change",{isPortrait:this.isPortrait()})}};return MicroEvent.mixin(obj),obj}return create()._init()}(),function(){"use strict";window.ons.platform={isWebView:function(){return ons.isWebView()},isIOS:function(){return/iPhone|iPad|iPod/i.test(navigator.userAgent)},isAndroid:function(){return/Android/i.test(navigator.userAgent)},isIPhone:function(){return/iPhone/i.test(navigator.userAgent)},isIPad:function(){return/iPad/i.test(navigator.userAgent)},isBlackBerry:function(){return/BlackBerry|RIM Tablet OS|BB10/i.test(navigator.userAgent)},isOpera:function(){return!!window.opera||navigator.userAgent.indexOf(" OPR/")>=0},isFirefox:function(){return"undefined"!=typeof InstallTrigger},isSafari:function(){return Object.prototype.toString.call(window.HTMLElement).indexOf("Constructor")>0},isChrome:function(){return!!window.chrome&&!(window.opera||navigator.userAgent.indexOf(" OPR/")>=0)},isIE:function(){return!1||!!document.documentMode},isIOS7above:function(){if(/iPhone|iPad|iPod/i.test(navigator.userAgent)){var ver=(navigator.userAgent.match(/\b[0-9]+_[0-9]+(?:_[0-9]+)?\b/)||[""])[0].replace(/_/g,".");return parseInt(ver.split(".")[0])>=7}return!1}}}(),function(){"use strict";window.addEventListener("load",function(){FastClick.attach(document.body)},!1),(new Viewport).setup(),Modernizr.testStyles("#modernizr { -webkit-overflow-scrolling:touch }",function(elem){Modernizr.addTest("overflowtouch",window.getComputedStyle&&"touch"==window.getComputedStyle(elem).getPropertyValue("-webkit-overflow-scrolling"))}),window.jQuery&&angular.element===window.jQuery&&console.warn("Onsen UI require jqLite. Load jQuery after loading AngularJS to fix this error. jQuery may break Onsen UI behavior.")}(),function(){"use strict";angular.module("onsen").run(["$templateCache",function($templateCache){for(var templates=window.document.querySelectorAll('script[type="text/ons-template"]'),i=0;i<templates.length;i++){var template=angular.element(templates[i]),id=template.attr("id");"string"==typeof id&&$templateCache.put(id,template.text())}}])}();
ki1st-xtqb/src/main/webapp/front/app/components/App.js
chosenki/chosenki-2016
import React from 'react' import Footer from './Footer' import AddTodo from '../containers/AddTodo' import VisibleTodoList from '../containers/VisibleTodoList' const App = () => ( <div> <AddTodo /> <VisibleTodoList /> <Footer /> </div> ) export default App
node_modules/bs-recipes/recipes/webpack.react-transform-hmr/app/js/main.js
vvlladimir/mbd
import React from 'react'; import { render } from 'react-dom'; // 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'; render(<HelloWorld />, document.getElementById('react-root'));
src/components/Boulder.js
kyledavid/rock-genius
import PropTypes from 'prop-types' import React from 'react' import BoulderRoute from './BoulderRoute' import boulderImg from '../img/boulders/the-pearl/pearl.jpg' const Boulder = props => { return props.routeInfo.routeName ? ( <div id="boulder-container"> <img src={boulderImg} alt="the-pearl" /> <BoulderRoute activeHold={props.routeInfo.activeHold} highlightedHolds={props.routeInfo.highlightedHolds} routeName={props.routeInfo.routeName} setActive={props.routeInfo.setActive} boulderData={props.boulderData} /> </div> ) : <div id="boulder-container"><img src={boulderImg} alt="the-pearl" /></div> } Boulder.propTypes = { routeInfo: PropTypes.shape({ activeHold: PropTypes.number, highlightedHolds: PropTypes.arrayOf(PropTypes.number), routeName: PropTypes.string, setActive: PropTypes.func.isRequired, }).isRequired, boulderData: PropTypes.object.isRequired, } Boulder.defaultProps = { routeInfo: { active: null, highlighted: null, } } export default Boulder
features/apimgt/org.wso2.carbon.apimgt.publisher.feature/src/main/resources/publisher/node_modules/material-ui/svg-icons/action/important-devices.js
bhathiya/test
'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 ActionImportantDevices = function ActionImportantDevices(props) { return _react2.default.createElement( _SvgIcon2.default, props, _react2.default.createElement('path', { d: 'M23 11.01L18 11c-.55 0-1 .45-1 1v9c0 .55.45 1 1 1h5c.55 0 1-.45 1-1v-9c0-.55-.45-.99-1-.99zM23 20h-5v-7h5v7zM20 2H2C.89 2 0 2.89 0 4v12c0 1.1.89 2 2 2h7v2H7v2h8v-2h-2v-2h2v-2H2V4h18v5h2V4c0-1.11-.9-2-2-2zm-8.03 7L11 6l-.97 3H7l2.47 1.76-.94 2.91 2.47-1.8 2.47 1.8-.94-2.91L15 9h-3.03z' }) ); }; ActionImportantDevices = (0, _pure2.default)(ActionImportantDevices); ActionImportantDevices.displayName = 'ActionImportantDevices'; ActionImportantDevices.muiName = 'SvgIcon'; exports.default = ActionImportantDevices;
examples/with-react-intl/components/Nav.js
giacomorebonato/next.js
import React from 'react' import {FormattedMessage} from 'react-intl' import Link from 'next/link' export default () => ( <nav> <li> <Link href='/'> <a><FormattedMessage id='nav.home' defaultMessage='Home' /></a> </Link> </li> <li> <Link href='/about'> <a><FormattedMessage id='nav.about' defaultMessage='About' /></a> </Link> </li> <style jsx>{` nav { display: flex; } li { list-style: none; margin-right: 1rem; } `}</style> </nav> )
admin/client/components/CreateForm.js
efernandesng/keystone
import React from 'react'; import Fields from '../fields'; import InvalidFieldType from './InvalidFieldType'; import { Alert, Button, Form, Modal } from 'elemental'; var CreateForm = React.createClass({ displayName: 'CreateForm', propTypes: { err: React.PropTypes.object, isOpen: React.PropTypes.bool, list: React.PropTypes.object, onCancel: React.PropTypes.func, values: React.PropTypes.object, }, getDefaultProps () { return { err: null, values: {}, isOpen: false }; }, getInitialState () { var values = Object.assign({}, this.props.values); Object.keys(this.props.list.fields).forEach(key => { var field = this.props.list.fields[key]; if (!values[field.path]) { values[field.path] = field.defaultValue; } }); return { values: values }; }, handleChange (event) { var values = Object.assign({}, this.state.values); values[event.path] = event.value; this.setState({ values: values }); }, componentDidUpdate (prevProps) { if (this.props.isOpen !== prevProps.isOpen) { // focus the focusTarget after the "open modal" CSS animation has started setTimeout(() => this.refs.focusTarget && this.refs.focusTarget.focus(), 0); } }, componentDidMount () { if (this.refs.focusTarget) { this.refs.focusTarget.focus(); } }, getFieldProps (field) { var props = Object.assign({}, field); props.value = this.state.values[field.path]; props.values = this.state.values; props.onChange = this.handleChange; props.mode = 'create'; props.key = field.path; return props; }, renderAlerts () { if (!this.props.err || !this.props.err.errors) return; var alertContent; var errorCount = Object.keys(this.props.err.errors).length; var messages = Object.keys(this.props.err.errors).map((path) => { return errorCount > 1 ? <li key={path}>{this.props.err.errors[path].message}</li> : <div key={path}>{this.props.err.errors[path].message}</div>; }); if (errorCount > 1) { alertContent = ( <div> <h4>There were {errorCount} errors creating the new {this.props.list.singular}:</h4> <ul>{messages}</ul> </div> ); } else { alertContent = messages; } return <Alert type="danger">{alertContent}</Alert>; }, renderForm () { if (!this.props.isOpen) return; var form = []; var list = this.props.list; var formAction = `${Keystone.adminPath}/${list.path}`; var nameField = this.props.list.nameField; var focusRef; if (list.nameIsInitial) { var nameFieldProps = this.getFieldProps(nameField); nameFieldProps.ref = focusRef = 'focusTarget'; if (nameField.type === 'text') { nameFieldProps.className = 'item-name-field'; nameFieldProps.placeholder = nameField.label; nameFieldProps.label = false; } form.push(React.createElement(Fields[nameField.type], nameFieldProps)); } Object.keys(list.initialFields).forEach(key => { var field = list.fields[list.initialFields[key]]; if ('function' !== typeof Fields[field.type]) { form.push(React.createElement(InvalidFieldType, { type: field.type, path: field.path, key: field.path })); return; } var fieldProps = this.getFieldProps(field); if (!focusRef) { fieldProps.ref = focusRef = 'focusTarget'; } form.push(React.createElement(Fields[field.type], fieldProps)); }); return ( <Form type="horizontal" encType="multipart/form-data" method="post" action={formAction} className="create-form"> <input type="hidden" name="action" value="create" /> <input type="hidden" name={Keystone.csrf.key} value={Keystone.csrf.value} /> <Modal.Header text={'Create a new ' + list.singular} onClose={this.props.onCancel} showCloseButton /> <Modal.Body> {this.renderAlerts()} {form} </Modal.Body> <Modal.Footer> <Button type="success" submit>Create</Button> <Button type="link-cancel" onClick={this.props.onCancel}>Cancel</Button> </Modal.Footer> </Form> ); }, render () { return ( <Modal isOpen={this.props.isOpen} onCancel={this.props.onCancel} backdropClosesModal> {this.renderForm()} </Modal> ); } }); module.exports = CreateForm;
client/index.js
VaRt-io/V-aRt
import './stylesheets/index.scss'; import React from 'react'; import ReactDOM from 'react-dom'; import {Provider} from 'react-redux'; import store from './store'; import {BrowserRouter as Router} from 'react-router-dom'; import Main from './components/main'; ReactDOM.render( <Provider store={store} > <Router> <Main /> </Router> </Provider>, document.getElementById('mainView') );
3-namespace/button.js
aruberto/styling-react-components
import React from 'react'; import cx from 'classnames'; const Button = ({ error, ...restProps }) => ( <button {...restProps} className={cx( 'my-namespace-button', { 'my-namespace-button-error': error } )} /> ); Button.propTypes = { error: React.PropTypes.bool, }; export default Button;
ajax/libs/js-data/1.4.1/js-data.js
iamso/cdnjs
/** * @author Jason Dobry <[email protected]> * @file dist/js-data.js * @version 1.4.1 - Homepage <http://www.js-data.io/> * @copyright (c) 2014 Jason Dobry * @license MIT <https://github.com/js-data/js-data/blob/master/LICENSE> * * @overview Data store. */ !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.JSData=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);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){ // Copyright 2012 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Modifications // Copyright 2014-2015 Jason Dobry // // Summary of modifications: // Fixed use of "delete" keyword for IE8 compatibility // Exposed diffObjectFromOldObject on the exported object // Added the "equals" argument to diffObjectFromOldObject to be used to check equality // Added a way to to define a default equality operator for diffObjectFromOldObject // Added a way in diffObjectFromOldObject to ignore changes to certain properties // Removed all code related to: // - ArrayObserver // - ArraySplice // - PathObserver // - CompoundObserver // - Path // - ObserverTransform (function(global) { 'use strict'; var equalityFn = function (a, b) { return a === b; }; var blacklist = []; // Detect and do basic sanity checking on Object/Array.observe. function detectObjectObserve() { if (typeof Object.observe !== 'function' || typeof Array.observe !== 'function') { return false; } var records = []; function callback(recs) { records = recs; } var test = {}; var arr = []; Object.observe(test, callback); Array.observe(arr, callback); test.id = 1; test.id = 2; delete test.id; arr.push(1, 2); arr.length = 0; Object.deliverChangeRecords(callback); if (records.length !== 5) return false; if (records[0].type != 'add' || records[1].type != 'update' || records[2].type != 'delete' || records[3].type != 'splice' || records[4].type != 'splice') { return false; } Object.unobserve(test, callback); Array.unobserve(arr, callback); return true; } var hasObserve = detectObjectObserve(); function detectEval() { // Don't test for eval if we're running in a Chrome App environment. // We check for APIs set that only exist in a Chrome App context. if (typeof chrome !== 'undefined' && chrome.app && chrome.app.runtime) { return false; } try { var f = new Function('', 'return true;'); return f(); } catch (ex) { return false; } } var hasEval = detectEval(); var createObject = ('__proto__' in {}) ? function(obj) { return obj; } : function(obj) { var proto = obj.__proto__; if (!proto) return obj; var newObject = Object.create(proto); Object.getOwnPropertyNames(obj).forEach(function(name) { Object.defineProperty(newObject, name, Object.getOwnPropertyDescriptor(obj, name)); }); return newObject; }; var MAX_DIRTY_CHECK_CYCLES = 1000; function dirtyCheck(observer) { var cycles = 0; while (cycles < MAX_DIRTY_CHECK_CYCLES && observer.check_()) { cycles++; } if (global.testingExposeCycleCount) global.dirtyCheckCycleCount = cycles; return cycles > 0; } function objectIsEmpty(object) { for (var prop in object) return false; return true; } function diffIsEmpty(diff) { return objectIsEmpty(diff.added) && objectIsEmpty(diff.removed) && objectIsEmpty(diff.changed); } function isBlacklisted(prop, bl) { if (!bl || !bl.length) { return false; } var matches; for (var i = 0; i < bl.length; i++) { if ((Object.prototype.toString.call(bl[i]) === '[object RegExp]' && bl[i].test(prop)) || bl[i] === prop) { return matches = prop; } } return !!matches; } function diffObjectFromOldObject(object, oldObject, equals, bl) { var added = {}; var removed = {}; var changed = {}; for (var prop in oldObject) { var newValue = object[prop]; if (isBlacklisted(prop, bl)) continue; if (newValue !== undefined && (equals ? equals(newValue, oldObject[prop]) : newValue === oldObject[prop])) continue; if (!(prop in object)) { removed[prop] = undefined; continue; } if (equals ? !equals(newValue, oldObject[prop]) : newValue !== oldObject[prop]) changed[prop] = newValue; } for (var prop in object) { if (prop in oldObject) continue; if (isBlacklisted(prop, bl)) continue; added[prop] = object[prop]; } if (Array.isArray(object) && object.length !== oldObject.length) changed.length = object.length; return { added: added, removed: removed, changed: changed }; } var eomTasks = []; function runEOMTasks() { if (!eomTasks.length) return false; for (var i = 0; i < eomTasks.length; i++) { eomTasks[i](); } eomTasks.length = 0; return true; } var runEOM = hasObserve ? (function(){ var eomObj = { pingPong: true }; var eomRunScheduled = false; Object.observe(eomObj, function() { runEOMTasks(); eomRunScheduled = false; }); return function(fn) { eomTasks.push(fn); if (!eomRunScheduled) { eomRunScheduled = true; eomObj.pingPong = !eomObj.pingPong; } }; })() : (function() { return function(fn) { eomTasks.push(fn); }; })(); var observedObjectCache = []; function newObservedObject() { var observer; var object; var discardRecords = false; var first = true; function callback(records) { if (observer && observer.state_ === OPENED && !discardRecords) observer.check_(records); } return { open: function(obs) { if (observer) throw Error('ObservedObject in use'); if (!first) Object.deliverChangeRecords(callback); observer = obs; first = false; }, observe: function(obj, arrayObserve) { object = obj; if (arrayObserve) Array.observe(object, callback); else Object.observe(object, callback); }, deliver: function(discard) { discardRecords = discard; Object.deliverChangeRecords(callback); discardRecords = false; }, close: function() { observer = undefined; Object.unobserve(object, callback); observedObjectCache.push(this); } }; } /* * The observedSet abstraction is a perf optimization which reduces the total * number of Object.observe observations of a set of objects. The idea is that * groups of Observers will have some object dependencies in common and this * observed set ensures that each object in the transitive closure of * dependencies is only observed once. The observedSet acts as a write barrier * such that whenever any change comes through, all Observers are checked for * changed values. * * Note that this optimization is explicitly moving work from setup-time to * change-time. * * TODO(rafaelw): Implement "garbage collection". In order to move work off * the critical path, when Observers are closed, their observed objects are * not Object.unobserve(d). As a result, it's possible that if the observedSet * is kept open, but some Observers have been closed, it could cause "leaks" * (prevent otherwise collectable objects from being collected). At some * point, we should implement incremental "gc" which keeps a list of * observedSets which may need clean-up and does small amounts of cleanup on a * timeout until all is clean. */ function getObservedObject(observer, object, arrayObserve) { var dir = observedObjectCache.pop() || newObservedObject(); dir.open(observer); dir.observe(object, arrayObserve); return dir; } var UNOPENED = 0; var OPENED = 1; var CLOSED = 2; var nextObserverId = 1; function Observer() { this.state_ = UNOPENED; this.callback_ = undefined; this.target_ = undefined; // TODO(rafaelw): Should be WeakRef this.directObserver_ = undefined; this.value_ = undefined; this.id_ = nextObserverId++; } Observer.prototype = { open: function(callback, target) { if (this.state_ != UNOPENED) throw Error('Observer has already been opened.'); addToAll(this); this.callback_ = callback; this.target_ = target; this.connect_(); this.state_ = OPENED; return this.value_; }, close: function() { if (this.state_ != OPENED) return; removeFromAll(this); this.disconnect_(); this.value_ = undefined; this.callback_ = undefined; this.target_ = undefined; this.state_ = CLOSED; }, deliver: function() { if (this.state_ != OPENED) return; dirtyCheck(this); }, report_: function(changes) { try { this.callback_.apply(this.target_, changes); } catch (ex) { Observer._errorThrownDuringCallback = true; console.error('Exception caught during observer callback: ' + (ex.stack || ex)); } }, discardChanges: function() { this.check_(undefined, true); return this.value_; } } var collectObservers = !hasObserve; var allObservers; Observer._allObserversCount = 0; if (collectObservers) { allObservers = []; } function addToAll(observer) { Observer._allObserversCount++; if (!collectObservers) return; allObservers.push(observer); } function removeFromAll(observer) { Observer._allObserversCount--; } var runningMicrotaskCheckpoint = false; var hasDebugForceFullDelivery = hasObserve && hasEval && (function() { try { eval('%RunMicrotasks()'); return true; } catch (ex) { return false; } })(); global.Platform = global.Platform || {}; global.Platform.performMicrotaskCheckpoint = function() { if (runningMicrotaskCheckpoint) return; if (hasDebugForceFullDelivery) { eval('%RunMicrotasks()'); return; } if (!collectObservers) return; runningMicrotaskCheckpoint = true; var cycles = 0; var anyChanged, toCheck; do { cycles++; toCheck = allObservers; allObservers = []; anyChanged = false; for (var i = 0; i < toCheck.length; i++) { var observer = toCheck[i]; if (observer.state_ != OPENED) continue; if (observer.check_()) anyChanged = true; allObservers.push(observer); } if (runEOMTasks()) anyChanged = true; } while (cycles < MAX_DIRTY_CHECK_CYCLES && anyChanged); if (global.testingExposeCycleCount) global.dirtyCheckCycleCount = cycles; runningMicrotaskCheckpoint = false; }; if (collectObservers) { global.Platform.clearObservers = function() { allObservers = []; }; } function ObjectObserver(object) { Observer.call(this); this.value_ = object; this.oldObject_ = undefined; } ObjectObserver.prototype = createObject({ __proto__: Observer.prototype, arrayObserve: false, connect_: function(callback, target) { if (hasObserve) { this.directObserver_ = getObservedObject(this, this.value_, this.arrayObserve); } else { this.oldObject_ = this.copyObject(this.value_); } }, copyObject: function(object) { var copy = Array.isArray(object) ? [] : {}; for (var prop in object) { copy[prop] = object[prop]; }; if (Array.isArray(object)) copy.length = object.length; return copy; }, check_: function(changeRecords, skipChanges) { var diff; var oldValues; if (hasObserve) { if (!changeRecords) return false; oldValues = {}; diff = diffObjectFromChangeRecords(this.value_, changeRecords, oldValues); } else { oldValues = this.oldObject_; diff = diffObjectFromOldObject(this.value_, this.oldObject_); } if (diffIsEmpty(diff)) return false; if (!hasObserve) this.oldObject_ = this.copyObject(this.value_); this.report_([ diff.added || {}, diff.removed || {}, diff.changed || {}, function(property) { return oldValues[property]; } ]); return true; }, disconnect_: function() { if (hasObserve) { this.directObserver_.close(); this.directObserver_ = undefined; } else { this.oldObject_ = undefined; } }, deliver: function() { if (this.state_ != OPENED) return; if (hasObserve) this.directObserver_.deliver(false); else dirtyCheck(this); }, discardChanges: function() { if (this.directObserver_) this.directObserver_.deliver(true); else this.oldObject_ = this.copyObject(this.value_); return this.value_; } }); var observerSentinel = {}; var expectedRecordTypes = { add: true, update: true, delete: true }; function diffObjectFromChangeRecords(object, changeRecords, oldValues) { var added = {}; var removed = {}; for (var i = 0; i < changeRecords.length; i++) { var record = changeRecords[i]; if (!expectedRecordTypes[record.type]) { console.error('Unknown changeRecord type: ' + record.type); console.error(record); continue; } if (!(record.name in oldValues)) oldValues[record.name] = record.oldValue; if (record.type == 'update') continue; if (record.type == 'add') { if (record.name in removed) delete removed[record.name]; else added[record.name] = true; continue; } // type = 'delete' if (record.name in added) { delete added[record.name]; delete oldValues[record.name]; } else { removed[record.name] = true; } } for (var prop in added) added[prop] = object[prop]; for (var prop in removed) removed[prop] = undefined; var changed = {}; for (var prop in oldValues) { if (prop in added || prop in removed) continue; var newValue = object[prop]; if (oldValues[prop] !== newValue) changed[prop] = newValue; } return { added: added, removed: removed, changed: changed }; } global.Observer = Observer; global.diffObjectFromOldObject = diffObjectFromOldObject; global.setEqualityFn = function (fn) { equalityFn = fn; }; global.setBlacklist = function (bl) { blacklist = bl; }; global.Observer.runEOM_ = runEOM; global.Observer.observerSentinel_ = observerSentinel; // for testing. global.Observer.hasObjectObserve = hasObserve; global.ObjectObserver = ObjectObserver; })(exports); },{}],2:[function(require,module,exports){ (function (process,global){ /*! * @overview es6-promise - a tiny implementation of Promises/A+. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) * @license Licensed under MIT license * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE * @version 2.0.1 */ (function() { "use strict"; function $$utils$$objectOrFunction(x) { return typeof x === 'function' || (typeof x === 'object' && x !== null); } function $$utils$$isFunction(x) { return typeof x === 'function'; } function $$utils$$isMaybeThenable(x) { return typeof x === 'object' && x !== null; } var $$utils$$_isArray; if (!Array.isArray) { $$utils$$_isArray = function (x) { return Object.prototype.toString.call(x) === '[object Array]'; }; } else { $$utils$$_isArray = Array.isArray; } var $$utils$$isArray = $$utils$$_isArray; var $$utils$$now = Date.now || function() { return new Date().getTime(); }; function $$utils$$F() { } var $$utils$$o_create = (Object.create || function (o) { if (arguments.length > 1) { throw new Error('Second argument not supported'); } if (typeof o !== 'object') { throw new TypeError('Argument must be an object'); } $$utils$$F.prototype = o; return new $$utils$$F(); }); var $$asap$$len = 0; var $$asap$$default = function asap(callback, arg) { $$asap$$queue[$$asap$$len] = callback; $$asap$$queue[$$asap$$len + 1] = arg; $$asap$$len += 2; if ($$asap$$len === 2) { // If len 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. $$asap$$scheduleFlush(); } }; var $$asap$$browserGlobal = (typeof window !== 'undefined') ? window : {}; var $$asap$$BrowserMutationObserver = $$asap$$browserGlobal.MutationObserver || $$asap$$browserGlobal.WebKitMutationObserver; // test for web worker but not in IE10 var $$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined'; // node function $$asap$$useNextTick() { return function() { process.nextTick($$asap$$flush); }; } function $$asap$$useMutationObserver() { var iterations = 0; var observer = new $$asap$$BrowserMutationObserver($$asap$$flush); var node = document.createTextNode(''); observer.observe(node, { characterData: true }); return function() { node.data = (iterations = ++iterations % 2); }; } // web worker function $$asap$$useMessageChannel() { var channel = new MessageChannel(); channel.port1.onmessage = $$asap$$flush; return function () { channel.port2.postMessage(0); }; } function $$asap$$useSetTimeout() { return function() { setTimeout($$asap$$flush, 1); }; } var $$asap$$queue = new Array(1000); function $$asap$$flush() { for (var i = 0; i < $$asap$$len; i+=2) { var callback = $$asap$$queue[i]; var arg = $$asap$$queue[i+1]; callback(arg); $$asap$$queue[i] = undefined; $$asap$$queue[i+1] = undefined; } $$asap$$len = 0; } var $$asap$$scheduleFlush; // Decide what async method to use to triggering processing of queued callbacks: if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { $$asap$$scheduleFlush = $$asap$$useNextTick(); } else if ($$asap$$BrowserMutationObserver) { $$asap$$scheduleFlush = $$asap$$useMutationObserver(); } else if ($$asap$$isWorker) { $$asap$$scheduleFlush = $$asap$$useMessageChannel(); } else { $$asap$$scheduleFlush = $$asap$$useSetTimeout(); } function $$$internal$$noop() {} var $$$internal$$PENDING = void 0; var $$$internal$$FULFILLED = 1; var $$$internal$$REJECTED = 2; var $$$internal$$GET_THEN_ERROR = new $$$internal$$ErrorObject(); function $$$internal$$selfFullfillment() { return new TypeError("You cannot resolve a promise with itself"); } function $$$internal$$cannotReturnOwn() { return new TypeError('A promises callback cannot return that same promise.') } function $$$internal$$getThen(promise) { try { return promise.then; } catch(error) { $$$internal$$GET_THEN_ERROR.error = error; return $$$internal$$GET_THEN_ERROR; } } function $$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) { try { then.call(value, fulfillmentHandler, rejectionHandler); } catch(e) { return e; } } function $$$internal$$handleForeignThenable(promise, thenable, then) { $$asap$$default(function(promise) { var sealed = false; var error = $$$internal$$tryThen(then, thenable, function(value) { if (sealed) { return; } sealed = true; if (thenable !== value) { $$$internal$$resolve(promise, value); } else { $$$internal$$fulfill(promise, value); } }, function(reason) { if (sealed) { return; } sealed = true; $$$internal$$reject(promise, reason); }, 'Settle: ' + (promise._label || ' unknown promise')); if (!sealed && error) { sealed = true; $$$internal$$reject(promise, error); } }, promise); } function $$$internal$$handleOwnThenable(promise, thenable) { if (thenable._state === $$$internal$$FULFILLED) { $$$internal$$fulfill(promise, thenable._result); } else if (promise._state === $$$internal$$REJECTED) { $$$internal$$reject(promise, thenable._result); } else { $$$internal$$subscribe(thenable, undefined, function(value) { $$$internal$$resolve(promise, value); }, function(reason) { $$$internal$$reject(promise, reason); }); } } function $$$internal$$handleMaybeThenable(promise, maybeThenable) { if (maybeThenable.constructor === promise.constructor) { $$$internal$$handleOwnThenable(promise, maybeThenable); } else { var then = $$$internal$$getThen(maybeThenable); if (then === $$$internal$$GET_THEN_ERROR) { $$$internal$$reject(promise, $$$internal$$GET_THEN_ERROR.error); } else if (then === undefined) { $$$internal$$fulfill(promise, maybeThenable); } else if ($$utils$$isFunction(then)) { $$$internal$$handleForeignThenable(promise, maybeThenable, then); } else { $$$internal$$fulfill(promise, maybeThenable); } } } function $$$internal$$resolve(promise, value) { if (promise === value) { $$$internal$$reject(promise, $$$internal$$selfFullfillment()); } else if ($$utils$$objectOrFunction(value)) { $$$internal$$handleMaybeThenable(promise, value); } else { $$$internal$$fulfill(promise, value); } } function $$$internal$$publishRejection(promise) { if (promise._onerror) { promise._onerror(promise._result); } $$$internal$$publish(promise); } function $$$internal$$fulfill(promise, value) { if (promise._state !== $$$internal$$PENDING) { return; } promise._result = value; promise._state = $$$internal$$FULFILLED; if (promise._subscribers.length === 0) { } else { $$asap$$default($$$internal$$publish, promise); } } function $$$internal$$reject(promise, reason) { if (promise._state !== $$$internal$$PENDING) { return; } promise._state = $$$internal$$REJECTED; promise._result = reason; $$asap$$default($$$internal$$publishRejection, promise); } function $$$internal$$subscribe(parent, child, onFulfillment, onRejection) { var subscribers = parent._subscribers; var length = subscribers.length; parent._onerror = null; subscribers[length] = child; subscribers[length + $$$internal$$FULFILLED] = onFulfillment; subscribers[length + $$$internal$$REJECTED] = onRejection; if (length === 0 && parent._state) { $$asap$$default($$$internal$$publish, parent); } } function $$$internal$$publish(promise) { var subscribers = promise._subscribers; var settled = promise._state; if (subscribers.length === 0) { return; } var child, callback, detail = promise._result; for (var i = 0; i < subscribers.length; i += 3) { child = subscribers[i]; callback = subscribers[i + settled]; if (child) { $$$internal$$invokeCallback(settled, child, callback, detail); } else { callback(detail); } } promise._subscribers.length = 0; } function $$$internal$$ErrorObject() { this.error = null; } var $$$internal$$TRY_CATCH_ERROR = new $$$internal$$ErrorObject(); function $$$internal$$tryCatch(callback, detail) { try { return callback(detail); } catch(e) { $$$internal$$TRY_CATCH_ERROR.error = e; return $$$internal$$TRY_CATCH_ERROR; } } function $$$internal$$invokeCallback(settled, promise, callback, detail) { var hasCallback = $$utils$$isFunction(callback), value, error, succeeded, failed; if (hasCallback) { value = $$$internal$$tryCatch(callback, detail); if (value === $$$internal$$TRY_CATCH_ERROR) { failed = true; error = value.error; value = null; } else { succeeded = true; } if (promise === value) { $$$internal$$reject(promise, $$$internal$$cannotReturnOwn()); return; } } else { value = detail; succeeded = true; } if (promise._state !== $$$internal$$PENDING) { // noop } else if (hasCallback && succeeded) { $$$internal$$resolve(promise, value); } else if (failed) { $$$internal$$reject(promise, error); } else if (settled === $$$internal$$FULFILLED) { $$$internal$$fulfill(promise, value); } else if (settled === $$$internal$$REJECTED) { $$$internal$$reject(promise, value); } } function $$$internal$$initializePromise(promise, resolver) { try { resolver(function resolvePromise(value){ $$$internal$$resolve(promise, value); }, function rejectPromise(reason) { $$$internal$$reject(promise, reason); }); } catch(e) { $$$internal$$reject(promise, e); } } function $$$enumerator$$makeSettledResult(state, position, value) { if (state === $$$internal$$FULFILLED) { return { state: 'fulfilled', value: value }; } else { return { state: 'rejected', reason: value }; } } function $$$enumerator$$Enumerator(Constructor, input, abortOnReject, label) { this._instanceConstructor = Constructor; this.promise = new Constructor($$$internal$$noop, label); this._abortOnReject = abortOnReject; if (this._validateInput(input)) { this._input = input; this.length = input.length; this._remaining = input.length; this._init(); if (this.length === 0) { $$$internal$$fulfill(this.promise, this._result); } else { this.length = this.length || 0; this._enumerate(); if (this._remaining === 0) { $$$internal$$fulfill(this.promise, this._result); } } } else { $$$internal$$reject(this.promise, this._validationError()); } } $$$enumerator$$Enumerator.prototype._validateInput = function(input) { return $$utils$$isArray(input); }; $$$enumerator$$Enumerator.prototype._validationError = function() { return new Error('Array Methods must be provided an Array'); }; $$$enumerator$$Enumerator.prototype._init = function() { this._result = new Array(this.length); }; var $$$enumerator$$default = $$$enumerator$$Enumerator; $$$enumerator$$Enumerator.prototype._enumerate = function() { var length = this.length; var promise = this.promise; var input = this._input; for (var i = 0; promise._state === $$$internal$$PENDING && i < length; i++) { this._eachEntry(input[i], i); } }; $$$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) { var c = this._instanceConstructor; if ($$utils$$isMaybeThenable(entry)) { if (entry.constructor === c && entry._state !== $$$internal$$PENDING) { entry._onerror = null; this._settledAt(entry._state, i, entry._result); } else { this._willSettleAt(c.resolve(entry), i); } } else { this._remaining--; this._result[i] = this._makeResult($$$internal$$FULFILLED, i, entry); } }; $$$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) { var promise = this.promise; if (promise._state === $$$internal$$PENDING) { this._remaining--; if (this._abortOnReject && state === $$$internal$$REJECTED) { $$$internal$$reject(promise, value); } else { this._result[i] = this._makeResult(state, i, value); } } if (this._remaining === 0) { $$$internal$$fulfill(promise, this._result); } }; $$$enumerator$$Enumerator.prototype._makeResult = function(state, i, value) { return value; }; $$$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) { var enumerator = this; $$$internal$$subscribe(promise, undefined, function(value) { enumerator._settledAt($$$internal$$FULFILLED, i, value); }, function(reason) { enumerator._settledAt($$$internal$$REJECTED, i, reason); }); }; var $$promise$all$$default = function all(entries, label) { return new $$$enumerator$$default(this, entries, true /* abort on reject */, label).promise; }; var $$promise$race$$default = function race(entries, label) { /*jshint validthis:true */ var Constructor = this; var promise = new Constructor($$$internal$$noop, label); if (!$$utils$$isArray(entries)) { $$$internal$$reject(promise, new TypeError('You must pass an array to race.')); return promise; } var length = entries.length; function onFulfillment(value) { $$$internal$$resolve(promise, value); } function onRejection(reason) { $$$internal$$reject(promise, reason); } for (var i = 0; promise._state === $$$internal$$PENDING && i < length; i++) { $$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection); } return promise; }; var $$promise$resolve$$default = function resolve(object, label) { /*jshint validthis:true */ var Constructor = this; if (object && typeof object === 'object' && object.constructor === Constructor) { return object; } var promise = new Constructor($$$internal$$noop, label); $$$internal$$resolve(promise, object); return promise; }; var $$promise$reject$$default = function reject(reason, label) { /*jshint validthis:true */ var Constructor = this; var promise = new Constructor($$$internal$$noop, label); $$$internal$$reject(promise, reason); return promise; }; var $$es6$promise$promise$$counter = 0; function $$es6$promise$promise$$needsResolver() { throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); } function $$es6$promise$promise$$needsNew() { throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); } var $$es6$promise$promise$$default = $$es6$promise$promise$$Promise; /** Promise objects represent the eventual result of an asynchronous operation. The primary way of interacting with a promise is through its `then` method, which registers callbacks to receive either a promise’s eventual value or the reason why the promise cannot be fulfilled. Terminology ----------- - `promise` is an object or function with a `then` method whose behavior conforms to this specification. - `thenable` is an object or function that defines a `then` method. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). - `exception` is a value that is thrown using the throw statement. - `reason` is a value that indicates why a promise was rejected. - `settled` the final resting state of a promise, fulfilled or rejected. A promise can be in one of three states: pending, fulfilled, or rejected. Promises that are fulfilled have a fulfillment value and are in the fulfilled state. Promises that are rejected have a rejection reason and are in the rejected state. A fulfillment value is never a thenable. Promises can also be said to *resolve* a value. If this value is also a promise, then the original promise's settled state will match the value's settled state. So a promise that *resolves* a promise that rejects will itself reject, and a promise that *resolves* a promise that fulfills will itself fulfill. Basic Usage: ------------ ```js var promise = new Promise(function(resolve, reject) { // on success resolve(value); // on failure reject(reason); }); promise.then(function(value) { // on fulfillment }, function(reason) { // on rejection }); ``` Advanced Usage: --------------- Promises shine when abstracting away asynchronous interactions such as `XMLHttpRequest`s. ```js function getJSON(url) { return new Promise(function(resolve, reject){ var xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.onreadystatechange = handler; xhr.responseType = 'json'; xhr.setRequestHeader('Accept', 'application/json'); xhr.send(); function handler() { if (this.readyState === this.DONE) { if (this.status === 200) { resolve(this.response); } else { reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); } } }; }); } getJSON('/posts.json').then(function(json) { // on fulfillment }, function(reason) { // on rejection }); ``` Unlike callbacks, promises are great composable primitives. ```js Promise.all([ getJSON('/posts'), getJSON('/comments') ]).then(function(values){ values[0] // => postsJSON values[1] // => commentsJSON return values; }); ``` @class Promise @param {function} resolver Useful for tooling. @constructor */ function $$es6$promise$promise$$Promise(resolver) { this._id = $$es6$promise$promise$$counter++; this._state = undefined; this._result = undefined; this._subscribers = []; if ($$$internal$$noop !== resolver) { if (!$$utils$$isFunction(resolver)) { $$es6$promise$promise$$needsResolver(); } if (!(this instanceof $$es6$promise$promise$$Promise)) { $$es6$promise$promise$$needsNew(); } $$$internal$$initializePromise(this, resolver); } } $$es6$promise$promise$$Promise.all = $$promise$all$$default; $$es6$promise$promise$$Promise.race = $$promise$race$$default; $$es6$promise$promise$$Promise.resolve = $$promise$resolve$$default; $$es6$promise$promise$$Promise.reject = $$promise$reject$$default; $$es6$promise$promise$$Promise.prototype = { constructor: $$es6$promise$promise$$Promise, /** The primary way of interacting with a promise is through its `then` method, which registers callbacks to receive either a promise's eventual value or the reason why the promise cannot be fulfilled. ```js findUser().then(function(user){ // user is available }, function(reason){ // user is unavailable, and you are given the reason why }); ``` Chaining -------- The return value of `then` is itself a promise. This second, 'downstream' promise is resolved with the return value of the first promise's fulfillment or rejection handler, or rejected if the handler throws an exception. ```js findUser().then(function (user) { return user.name; }, function (reason) { return 'default name'; }).then(function (userName) { // If `findUser` fulfilled, `userName` will be the user's name, otherwise it // will be `'default name'` }); findUser().then(function (user) { throw new Error('Found user, but still unhappy'); }, function (reason) { throw new Error('`findUser` rejected and we're unhappy'); }).then(function (value) { // never reached }, function (reason) { // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. }); ``` If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. ```js findUser().then(function (user) { throw new PedagogicalException('Upstream error'); }).then(function (value) { // never reached }).then(function (value) { // never reached }, function (reason) { // The `PedgagocialException` is propagated all the way down to here }); ``` Assimilation ------------ Sometimes the value you want to propagate to a downstream promise can only be retrieved asynchronously. This can be achieved by returning a promise in the fulfillment or rejection handler. The downstream promise will then be pending until the returned promise is settled. This is called *assimilation*. ```js findUser().then(function (user) { return findCommentsByAuthor(user); }).then(function (comments) { // The user's comments are now available }); ``` If the assimliated promise rejects, then the downstream promise will also reject. ```js findUser().then(function (user) { return findCommentsByAuthor(user); }).then(function (comments) { // If `findCommentsByAuthor` fulfills, we'll have the value here }, function (reason) { // If `findCommentsByAuthor` rejects, we'll have the reason here }); ``` Simple Example -------------- Synchronous Example ```javascript var result; try { result = findResult(); // success } catch(reason) { // failure } ``` Errback Example ```js findResult(function(result, err){ if (err) { // failure } else { // success } }); ``` Promise Example; ```javascript findResult().then(function(result){ // success }, function(reason){ // failure }); ``` Advanced Example -------------- Synchronous Example ```javascript var author, books; try { author = findAuthor(); books = findBooksByAuthor(author); // success } catch(reason) { // failure } ``` Errback Example ```js function foundBooks(books) { } function failure(reason) { } findAuthor(function(author, err){ if (err) { failure(err); // failure } else { try { findBoooksByAuthor(author, function(books, err) { if (err) { failure(err); } else { try { foundBooks(books); } catch(reason) { failure(reason); } } }); } catch(error) { failure(err); } // success } }); ``` Promise Example; ```javascript findAuthor(). then(findBooksByAuthor). then(function(books){ // found books }).catch(function(reason){ // something went wrong }); ``` @method then @param {Function} onFulfilled @param {Function} onRejected Useful for tooling. @return {Promise} */ then: function(onFulfillment, onRejection) { var parent = this; var state = parent._state; if (state === $$$internal$$FULFILLED && !onFulfillment || state === $$$internal$$REJECTED && !onRejection) { return this; } var child = new this.constructor($$$internal$$noop); var result = parent._result; if (state) { var callback = arguments[state - 1]; $$asap$$default(function(){ $$$internal$$invokeCallback(state, child, callback, result); }); } else { $$$internal$$subscribe(parent, child, onFulfillment, onRejection); } return child; }, /** `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same as the catch block of a try/catch statement. ```js function findAuthor(){ throw new Error('couldn't find that author'); } // synchronous try { findAuthor(); } catch(reason) { // something went wrong } // async with promises findAuthor().catch(function(reason){ // something went wrong }); ``` @method catch @param {Function} onRejection Useful for tooling. @return {Promise} */ 'catch': function(onRejection) { return this.then(null, onRejection); } }; var $$es6$promise$polyfill$$default = 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 $$utils$$isFunction(resolve); }()); if (!es6PromiseSupport) { local.Promise = $$es6$promise$promise$$default; } }; var es6$promise$umd$$ES6Promise = { 'Promise': $$es6$promise$promise$$default, 'polyfill': $$es6$promise$polyfill$$default }; /* global define:true module:true window: true */ if (typeof define === 'function' && define['amd']) { define(function() { return es6$promise$umd$$ES6Promise; }); } else if (typeof module !== 'undefined' && module['exports']) { module['exports'] = es6$promise$umd$$ES6Promise; } else if (typeof this !== 'undefined') { this['ES6Promise'] = es6$promise$umd$$ES6Promise; } }).call(this); }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"_process":3}],3:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; var queue = []; var draining = false; function drainQueue() { if (draining) { return; } draining = true; var currentQueue; var len = queue.length; while(len) { currentQueue = queue; queue = []; var i = -1; while (++i < len) { currentQueue[i](); } len = queue.length; } draining = false; } process.nextTick = function (fun) { queue.push(fun); if (!draining) { setTimeout(drainQueue, 0); } }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues 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'); }; process.umask = function() { return 0; }; },{}],4:[function(require,module,exports){ var indexOf = require('./indexOf'); /** * If array contains values. */ function contains(arr, val) { return indexOf(arr, val) !== -1; } module.exports = contains; },{"./indexOf":6}],5:[function(require,module,exports){ /** * Array forEach */ function forEach(arr, callback, thisObj) { if (arr == null) { return; } var i = -1, len = arr.length; while (++i < len) { // we iterate over sparse items since there is no way to make it // work properly on IE 7-8. see #64 if ( callback.call(thisObj, arr[i], i, arr) === false ) { break; } } } module.exports = forEach; },{}],6:[function(require,module,exports){ /** * Array.indexOf */ function indexOf(arr, item, fromIndex) { fromIndex = fromIndex || 0; if (arr == null) { return -1; } var len = arr.length, i = fromIndex < 0 ? len + fromIndex : fromIndex; while (i < len) { // we iterate over sparse items since there is no way to make it // work properly on IE 7-8. see #64 if (arr[i] === item) { return i; } i++; } return -1; } module.exports = indexOf; },{}],7:[function(require,module,exports){ var indexOf = require('./indexOf'); /** * Remove a single item from the array. * (it won't remove duplicates, just a single item) */ function remove(arr, item){ var idx = indexOf(arr, item); if (idx !== -1) arr.splice(idx, 1); } module.exports = remove; },{"./indexOf":6}],8:[function(require,module,exports){ /** * Create slice of source array or array-like object */ function slice(arr, start, end){ var len = arr.length; if (start == null) { start = 0; } else if (start < 0) { start = Math.max(len + start, 0); } else { start = Math.min(start, len); } if (end == null) { end = len; } else if (end < 0) { end = Math.max(len + end, 0); } else { end = Math.min(end, len); } var result = []; while (start < end) { result.push(arr[start++]); } return result; } module.exports = slice; },{}],9:[function(require,module,exports){ /** * Merge sort (http://en.wikipedia.org/wiki/Merge_sort) */ function mergeSort(arr, compareFn) { if (arr == null) { return []; } else if (arr.length < 2) { return arr; } if (compareFn == null) { compareFn = defaultCompare; } var mid, left, right; mid = ~~(arr.length / 2); left = mergeSort( arr.slice(0, mid), compareFn ); right = mergeSort( arr.slice(mid, arr.length), compareFn ); return merge(left, right, compareFn); } function defaultCompare(a, b) { return a < b ? -1 : (a > b? 1 : 0); } function merge(left, right, compareFn) { var result = []; while (left.length && right.length) { if (compareFn(left[0], right[0]) <= 0) { // if 0 it should preserve same order (stable) result.push(left.shift()); } else { result.push(right.shift()); } } if (left.length) { result.push.apply(result, left); } if (right.length) { result.push.apply(result, right); } return result; } module.exports = mergeSort; },{}],10:[function(require,module,exports){ /** * Checks if the value is created by the `Object` constructor. */ function isPlainObject(value) { return (!!value && typeof value === 'object' && value.constructor === Object); } module.exports = isPlainObject; },{}],11:[function(require,module,exports){ /** * Checks if the object is a primitive */ function isPrimitive(value) { // Using switch fallthrough because it's simple to read and is // generally fast: http://jsperf.com/testing-value-is-primitive/5 switch (typeof value) { case "string": case "number": case "boolean": return true; } return value == null; } module.exports = isPrimitive; },{}],12:[function(require,module,exports){ /** * Typecast a value to a String, using an empty string value for null or * undefined. */ function toString(val){ return val == null ? '' : val.toString(); } module.exports = toString; },{}],13:[function(require,module,exports){ var forOwn = require('./forOwn'); var isPlainObject = require('../lang/isPlainObject'); /** * Mixes objects into the target object, recursively mixing existing child * objects. */ function deepMixIn(target, objects) { var i = 0, n = arguments.length, obj; while(++i < n){ obj = arguments[i]; if (obj) { forOwn(obj, copyProp, target); } } return target; } function copyProp(val, key) { var existing = this[key]; if (isPlainObject(val) && isPlainObject(existing)) { deepMixIn(existing, val); } else { this[key] = val; } } module.exports = deepMixIn; },{"../lang/isPlainObject":10,"./forOwn":15}],14:[function(require,module,exports){ var hasOwn = require('./hasOwn'); var _hasDontEnumBug, _dontEnums; function checkDontEnum(){ _dontEnums = [ 'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor' ]; _hasDontEnumBug = true; for (var key in {'toString': null}) { _hasDontEnumBug = false; } } /** * Similar to Array/forEach but works over object properties and fixes Don't * Enum bug on IE. * based on: http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation */ function forIn(obj, fn, thisObj){ var key, i = 0; // no need to check if argument is a real object that way we can use // it for arrays, functions, date, etc. //post-pone check till needed if (_hasDontEnumBug == null) checkDontEnum(); for (key in obj) { if (exec(fn, obj, key, thisObj) === false) { break; } } if (_hasDontEnumBug) { var ctor = obj.constructor, isProto = !!ctor && obj === ctor.prototype; while (key = _dontEnums[i++]) { // For constructor, if it is a prototype object the constructor // is always non-enumerable unless defined otherwise (and // enumerated above). For non-prototype objects, it will have // to be defined on this object, since it cannot be defined on // any prototype objects. // // For other [[DontEnum]] properties, check if the value is // different than Object prototype value. if ( (key !== 'constructor' || (!isProto && hasOwn(obj, key))) && obj[key] !== Object.prototype[key] ) { if (exec(fn, obj, key, thisObj) === false) { break; } } } } } function exec(fn, obj, key, thisObj){ return fn.call(thisObj, obj[key], key, obj); } module.exports = forIn; },{"./hasOwn":17}],15:[function(require,module,exports){ var hasOwn = require('./hasOwn'); var forIn = require('./forIn'); /** * Similar to Array/forEach but works over object properties and fixes Don't * Enum bug on IE. * based on: http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation */ function forOwn(obj, fn, thisObj){ forIn(obj, function(val, key){ if (hasOwn(obj, key)) { return fn.call(thisObj, obj[key], key, obj); } }); } module.exports = forOwn; },{"./forIn":14,"./hasOwn":17}],16:[function(require,module,exports){ var isPrimitive = require('../lang/isPrimitive'); /** * get "nested" object property */ function get(obj, prop){ var parts = prop.split('.'), last = parts.pop(); while (prop = parts.shift()) { obj = obj[prop]; if (obj == null) return; } return obj[last]; } module.exports = get; },{"../lang/isPrimitive":11}],17:[function(require,module,exports){ /** * Safer Object.hasOwnProperty */ function hasOwn(obj, prop){ return Object.prototype.hasOwnProperty.call(obj, prop); } module.exports = hasOwn; },{}],18:[function(require,module,exports){ var forEach = require('../array/forEach'); /** * Create nested object if non-existent */ function namespace(obj, path){ if (!path) return obj; forEach(path.split('.'), function(key){ if (!obj[key]) { obj[key] = {}; } obj = obj[key]; }); return obj; } module.exports = namespace; },{"../array/forEach":5}],19:[function(require,module,exports){ var slice = require('../array/slice'); /** * Return a copy of the object, filtered to only have values for the whitelisted keys. */ function pick(obj, var_keys){ var keys = typeof arguments[1] !== 'string'? arguments[1] : slice(arguments, 1), out = {}, i = 0, key; while (key = keys[i++]) { out[key] = obj[key]; } return out; } module.exports = pick; },{"../array/slice":8}],20:[function(require,module,exports){ var namespace = require('./namespace'); /** * set "nested" object property */ function set(obj, prop, val){ var parts = (/^(.+)\.(.+)$/).exec(prop); if (parts){ namespace(obj, parts[1])[parts[2]] = val; } else { obj[prop] = val; } } module.exports = set; },{"./namespace":18}],21:[function(require,module,exports){ var toString = require('../lang/toString'); var replaceAccents = require('./replaceAccents'); var removeNonWord = require('./removeNonWord'); var upperCase = require('./upperCase'); var lowerCase = require('./lowerCase'); /** * Convert string to camelCase text. */ function camelCase(str){ str = toString(str); str = replaceAccents(str); str = removeNonWord(str) .replace(/[\-_]/g, ' ') //convert all hyphens and underscores to spaces .replace(/\s[a-z]/g, upperCase) //convert first char of each word to UPPERCASE .replace(/\s+/g, '') //remove spaces .replace(/^[A-Z]/g, lowerCase); //convert first char to lowercase return str; } module.exports = camelCase; },{"../lang/toString":12,"./lowerCase":22,"./removeNonWord":24,"./replaceAccents":25,"./upperCase":26}],22:[function(require,module,exports){ var toString = require('../lang/toString'); /** * "Safer" String.toLowerCase() */ function lowerCase(str){ str = toString(str); return str.toLowerCase(); } module.exports = lowerCase; },{"../lang/toString":12}],23:[function(require,module,exports){ var toString = require('../lang/toString'); var camelCase = require('./camelCase'); var upperCase = require('./upperCase'); /** * camelCase + UPPERCASE first char */ function pascalCase(str){ str = toString(str); return camelCase(str).replace(/^[a-z]/, upperCase); } module.exports = pascalCase; },{"../lang/toString":12,"./camelCase":21,"./upperCase":26}],24:[function(require,module,exports){ var toString = require('../lang/toString'); // This pattern is generated by the _build/pattern-removeNonWord.js script var PATTERN = /[^\x20\x2D0-9A-Z\x5Fa-z\xC0-\xD6\xD8-\xF6\xF8-\xFF]/g; /** * Remove non-word chars. */ function removeNonWord(str){ str = toString(str); return str.replace(PATTERN, ''); } module.exports = removeNonWord; },{"../lang/toString":12}],25:[function(require,module,exports){ var toString = require('../lang/toString'); /** * Replaces all accented chars with regular ones */ function replaceAccents(str){ str = toString(str); // verifies if the String has accents and replace them if (str.search(/[\xC0-\xFF]/g) > -1) { str = str .replace(/[\xC0-\xC5]/g, "A") .replace(/[\xC6]/g, "AE") .replace(/[\xC7]/g, "C") .replace(/[\xC8-\xCB]/g, "E") .replace(/[\xCC-\xCF]/g, "I") .replace(/[\xD0]/g, "D") .replace(/[\xD1]/g, "N") .replace(/[\xD2-\xD6\xD8]/g, "O") .replace(/[\xD9-\xDC]/g, "U") .replace(/[\xDD]/g, "Y") .replace(/[\xDE]/g, "P") .replace(/[\xE0-\xE5]/g, "a") .replace(/[\xE6]/g, "ae") .replace(/[\xE7]/g, "c") .replace(/[\xE8-\xEB]/g, "e") .replace(/[\xEC-\xEF]/g, "i") .replace(/[\xF1]/g, "n") .replace(/[\xF2-\xF6\xF8]/g, "o") .replace(/[\xF9-\xFC]/g, "u") .replace(/[\xFE]/g, "p") .replace(/[\xFD\xFF]/g, "y"); } return str; } module.exports = replaceAccents; },{"../lang/toString":12}],26:[function(require,module,exports){ var toString = require('../lang/toString'); /** * "Safer" String.toUpperCase() */ function upperCase(str){ str = toString(str); return str.toUpperCase(); } module.exports = upperCase; },{"../lang/toString":12}],27:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function create(resourceName, attrs, options) { var _this = this; var definition = _this.definitions[resourceName]; options = options || {}; attrs = attrs || {}; var rejectionError; if (!definition) { rejectionError = new DSErrors.NER(resourceName); } else if (!DSUtils.isObject(attrs)) { rejectionError = new DSErrors.IA('"attrs" must be an object!'); } else { options = DSUtils._(definition, options); if (options.upsert && (DSUtils.isString(attrs[definition.idAttribute]) || DSUtils.isNumber(attrs[definition.idAttribute]))) { return _this.update(resourceName, attrs[definition.idAttribute], attrs, options); } } return new DSUtils.Promise(function (resolve, reject) { if (rejectionError) { reject(rejectionError); } else { resolve(attrs); } }) .then(function (attrs) { return options.beforeValidate.call(attrs, options, attrs); }) .then(function (attrs) { return options.validate.call(attrs, options, attrs); }) .then(function (attrs) { return options.afterValidate.call(attrs, options, attrs); }) .then(function (attrs) { return options.beforeCreate.call(attrs, options, attrs); }) .then(function (attrs) { if (options.notify) { _this.emit(options, 'beforeCreate', DSUtils.copy(attrs)); } return _this.getAdapter(options).create(definition, attrs, options); }) .then(function (attrs) { return options.afterCreate.call(attrs, options, attrs); }) .then(function (attrs) { if (options.notify) { _this.emit(options, 'afterCreate', DSUtils.copy(attrs)); } if (options.cacheResponse) { var created = _this.inject(definition.name, attrs, options); var id = created[definition.idAttribute]; _this.store[resourceName].completedQueries[id] = new Date().getTime(); return created; } else { return _this.createInstance(resourceName, attrs, options); } }); } module.exports = create; },{"../../errors":48,"../../utils":50}],28:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function destroy(resourceName, id, options) { var _this = this; var definition = _this.definitions[resourceName]; var item; return new DSUtils.Promise(function (resolve, reject) { id = DSUtils.resolveId(definition, id); if (!definition) { reject(new DSErrors.NER(resourceName)); } else if (!DSUtils.isString(id) && !DSUtils.isNumber(id)) { reject(new DSErrors.IA('"id" must be a string or a number!')); } else { item = _this.get(resourceName, id) || { id: id }; options = DSUtils._(definition, options); resolve(item); } }) .then(function (attrs) { return options.beforeDestroy.call(attrs, options, attrs); }) .then(function (attrs) { if (options.notify) { _this.emit(options, 'beforeDestroy', DSUtils.copy(attrs)); } if (options.eagerEject) { _this.eject(resourceName, id); } return _this.getAdapter(options).destroy(definition, id, options); }) .then(function () { return options.afterDestroy.call(item, options, item); }) .then(function (item) { if (options.notify) { _this.emit(options, 'afterDestroy', DSUtils.copy(item)); } _this.eject(resourceName, id); return id; })['catch'](function (err) { if (options && options.eagerEject && item) { _this.inject(resourceName, item, { notify: false }); } throw err; }); } module.exports = destroy; },{"../../errors":48,"../../utils":50}],29:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function destroyAll(resourceName, params, options) { var _this = this; var definition = _this.definitions[resourceName]; var ejected, toEject; params = params || {}; return new DSUtils.Promise(function (resolve, reject) { if (!definition) { reject(new DSErrors.NER(resourceName)); } else if (!DSUtils.isObject(params)) { reject(new DSErrors.IA('"params" must be an object!')); } else { options = DSUtils._(definition, options); resolve(); } }).then(function () { toEject = _this.defaults.defaultFilter.call(_this, resourceName, params); return options.beforeDestroy(options, toEject); }).then(function () { if (options.notify) { _this.emit(options, 'beforeDestroy', DSUtils.copy(toEject)); } if (options.eagerEject) { ejected = _this.ejectAll(resourceName, params); } return _this.getAdapter(options).destroyAll(definition, params, options); }).then(function () { return options.afterDestroy(options, toEject); }).then(function () { if (options.notify) { _this.emit(options, 'afterDestroy', DSUtils.copy(toEject)); } return ejected || _this.ejectAll(resourceName, params); })['catch'](function (err) { if (options && options.eagerEject && ejected) { _this.inject(resourceName, ejected, { notify: false }); } throw err; }); } module.exports = destroyAll; },{"../../errors":48,"../../utils":50}],30:[function(require,module,exports){ /* jshint -W082 */ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function find(resourceName, id, options) { var _this = this; var definition = _this.definitions[resourceName]; var resource = _this.store[resourceName]; return new DSUtils.Promise(function (resolve, reject) { if (!definition) { reject(new DSErrors.NER(resourceName)); } else if (!DSUtils.isString(id) && !DSUtils.isNumber(id)) { reject(new DSErrors.IA('"id" must be a string or a number!')); } else { options = DSUtils._(definition, options); if (options.params) { options.params = DSUtils.copy(options.params); } if (options.bypassCache || !options.cacheResponse) { delete resource.completedQueries[id]; } if (id in resource.completedQueries && _this.get(resourceName, id)) { resolve(_this.get(resourceName, id)); } else { delete resource.completedQueries[id]; resolve(); } } }).then(function (item) { if (!item) { if (!(id in resource.pendingQueries)) { var promise; var strategy = options.findStrategy || options.strategy; if (strategy === 'fallback') { function makeFallbackCall(index) { return _this.getAdapter((options.findFallbackAdapters || options.fallbackAdapters)[index]).find(definition, id, options)['catch'](function (err) { index++; if (index < options.fallbackAdapters.length) { return makeFallbackCall(index); } else { return Promise.reject(err); } }); } promise = makeFallbackCall(0); } else { promise = _this.getAdapter(options).find(definition, id, options); } resource.pendingQueries[id] = promise.then(function (data) { // Query is no longer pending delete resource.pendingQueries[id]; if (options.cacheResponse) { var injected = _this.inject(resourceName, data, options); resource.completedQueries[id] = new Date().getTime(); return injected; } else { return _this.createInstance(resourceName, data, options); } }); } return resource.pendingQueries[id]; } else { return item; } })['catch'](function (err) { if (resource) { delete resource.pendingQueries[id]; } throw err; }); } module.exports = find; },{"../../errors":48,"../../utils":50}],31:[function(require,module,exports){ /* jshint -W082 */ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function processResults(data, resourceName, queryHash, options) { var _this = this; var resource = _this.store[resourceName]; var idAttribute = _this.definitions[resourceName].idAttribute; var date = new Date().getTime(); data = data || []; // Query is no longer pending delete resource.pendingQueries[queryHash]; resource.completedQueries[queryHash] = date; // Update modified timestamp of collection resource.collectionModified = DSUtils.updateTimestamp(resource.collectionModified); // Merge the new values into the cache var injected = _this.inject(resourceName, data, options); // Make sure each object is added to completedQueries if (DSUtils.isArray(injected)) { DSUtils.forEach(injected, function (item) { if (item && item[idAttribute]) { resource.completedQueries[item[idAttribute]] = date; } }); } else { options.errorFn('response is expected to be an array!'); resource.completedQueries[injected[idAttribute]] = date; } return injected; } function findAll(resourceName, params, options) { var _this = this; var definition = _this.definitions[resourceName]; var resource = _this.store[resourceName]; var queryHash; return new DSUtils.Promise(function (resolve, reject) { params = params || {}; if (!_this.definitions[resourceName]) { reject(new DSErrors.NER(resourceName)); } else if (!DSUtils.isObject(params)) { reject(new DSErrors.IA('"params" must be an object!')); } else { options = DSUtils._(definition, options); queryHash = DSUtils.toJson(params); if (options.params) { options.params = DSUtils.copy(options.params); } if (options.bypassCache || !options.cacheResponse) { delete resource.completedQueries[queryHash]; delete resource.queryData[queryHash]; } if (queryHash in resource.completedQueries) { if (options.useFilter) { resolve(_this.filter(resourceName, params, options)); } else { resolve(resource.queryData[queryHash]); } } else { resolve(); } } }).then(function (items) { if (!(queryHash in resource.completedQueries)) { if (!(queryHash in resource.pendingQueries)) { var promise; var strategy = options.findAllStrategy || options.strategy; if (strategy === 'fallback') { function makeFallbackCall(index) { return _this.getAdapter((options.findAllFallbackAdapters || options.fallbackAdapters)[index]).findAll(definition, params, options)['catch'](function (err) { index++; if (index < options.fallbackAdapters.length) { return makeFallbackCall(index); } else { return Promise.reject(err); } }); } promise = makeFallbackCall(0); } else { promise = _this.getAdapter(options).findAll(definition, params, options); } resource.pendingQueries[queryHash] = promise.then(function (data) { delete resource.pendingQueries[queryHash]; if (options.cacheResponse) { resource.queryData[queryHash] = processResults.call(_this, data, resourceName, queryHash, options); resource.queryData[queryHash].$$injected = true; return resource.queryData[queryHash]; } else { DSUtils.forEach(data, function (item, i) { data[i] = _this.createInstance(resourceName, item, options); }); return data; } }); } return resource.pendingQueries[queryHash]; } else { return items; } })['catch'](function (err) { if (resource) { delete resource.pendingQueries[queryHash]; } throw err; }); } module.exports = findAll; },{"../../errors":48,"../../utils":50}],32:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function reap(resourceName, options) { var _this = this; var definition = _this.definitions[resourceName]; var resource = _this.store[resourceName]; return new DSUtils.Promise(function (resolve, reject) { if (!definition) { reject(new _this.errors.NER(resourceName)); } else { options = DSUtils._(definition, options); if (!options.hasOwnProperty('notify')) { options.notify = false; } var items = []; var now = new Date().getTime(); var expiredItem; while ((expiredItem = resource.expiresHeap.peek()) && expiredItem.expires < now) { items.push(expiredItem.item); delete expiredItem.item; resource.expiresHeap.pop(); } resolve(items); } }).then(function (items) { if (options.isInterval || options.notify) { definition.beforeReap(options, items); _this.emit(options, 'beforeReap', DSUtils.copy(items)); } if (options.reapAction === 'inject') { DSUtils.forEach(items, function (item) { var id = item[definition.idAttribute]; resource.expiresHeap.push({ item: item, timestamp: resource.saved[id], expires: definition.maxAge ? resource.saved[id] + definition.maxAge : Number.MAX_VALUE }); }); } else if (options.reapAction === 'eject') { DSUtils.forEach(items, function (item) { _this.eject(resourceName, item[definition.idAttribute]); }); } else if (options.reapAction === 'refresh') { var tasks = []; DSUtils.forEach(items, function (item) { tasks.push(_this.refresh(resourceName, item[definition.idAttribute])); }); return DSUtils.Promise.all(tasks); } return items; }).then(function (items) { if (options.isInterval || options.notify) { definition.afterReap(options, items); _this.emit(options, 'afterReap', DSUtils.copy(items)); } return items; }); } function refresh(resourceName, id, options) { var _this = this; return new DSUtils.Promise(function (resolve, reject) { var definition = _this.definitions[resourceName]; id = DSUtils.resolveId(_this.definitions[resourceName], id); if (!definition) { reject(new _this.errors.NER(resourceName)); } else if (!DSUtils.isString(id) && !DSUtils.isNumber(id)) { reject(new DSErrors.IA('"id" must be a string or a number!')); } else { options = DSUtils._(definition, options); options.bypassCache = true; resolve(_this.get(resourceName, id)); } }).then(function (item) { if (item) { return _this.find(resourceName, id, options); } else { return item; } }); } module.exports = { create: require('./create'), destroy: require('./destroy'), destroyAll: require('./destroyAll'), find: require('./find'), findAll: require('./findAll'), loadRelations: require('./loadRelations'), reap: reap, refresh: refresh, save: require('./save'), update: require('./update'), updateAll: require('./updateAll') }; },{"../../errors":48,"../../utils":50,"./create":27,"./destroy":28,"./destroyAll":29,"./find":30,"./findAll":31,"./loadRelations":33,"./save":34,"./update":35,"./updateAll":36}],33:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function loadRelations(resourceName, instance, relations, options) { var _this = this; var definition = _this.definitions[resourceName]; var fields = []; return new DSUtils.Promise(function (resolve, reject) { if (DSUtils.isString(instance) || DSUtils.isNumber(instance)) { instance = _this.get(resourceName, instance); } if (DSUtils.isString(relations)) { relations = [relations]; } if (!definition) { reject(new DSErrors.NER(resourceName)); } else if (!DSUtils.isObject(instance)) { reject(new DSErrors.IA('"instance(id)" must be a string, number or object!')); } else if (!DSUtils.isArray(relations)) { reject(new DSErrors.IA('"relations" must be a string or an array!')); } else { var _options = DSUtils._(definition, options); if (!_options.hasOwnProperty('findBelongsTo')) { _options.findBelongsTo = true; } if (!_options.hasOwnProperty('findHasMany')) { _options.findHasMany = true; } var tasks = []; DSUtils.forEach(definition.relationList, function (def) { var relationName = def.relation; var relationDef = definition.getResource(relationName); var __options = DSUtils._(relationDef, options); if (DSUtils.contains(relations, relationName)) { var task; var params = {}; if (__options.allowSimpleWhere) { params[def.foreignKey] = instance[definition.idAttribute]; } else { params.where = {}; params.where[def.foreignKey] = { '==': instance[definition.idAttribute] }; } if (def.type === 'hasMany' && params[def.foreignKey]) { task = _this.findAll(relationName, params, __options); } else if (def.type === 'hasOne') { if (def.localKey && instance[def.localKey]) { task = _this.find(relationName, instance[def.localKey], __options); } else if (def.foreignKey && params[def.foreignKey]) { task = _this.findAll(relationName, params, __options).then(function (hasOnes) { return hasOnes.length ? hasOnes[0] : null; }); } } else if (instance[def.localKey]) { task = _this.find(relationName, instance[def.localKey], options); } if (task) { tasks.push(task); fields.push(def.localField); } } }); resolve(tasks); } }) .then(function (tasks) { return DSUtils.Promise.all(tasks); }) .then(function (loadedRelations) { DSUtils.forEach(fields, function (field, index) { instance[field] = loadedRelations[index]; }); return instance; }); } module.exports = loadRelations; },{"../../errors":48,"../../utils":50}],34:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function save(resourceName, id, options) { var _this = this; var definition = _this.definitions[resourceName]; var item; return new DSUtils.Promise(function (resolve, reject) { id = DSUtils.resolveId(definition, id); if (!definition) { reject(new DSErrors.NER(resourceName)); } else if (!DSUtils.isString(id) && !DSUtils.isNumber(id)) { reject(new DSErrors.IA('"id" must be a string or a number!')); } else if (!_this.get(resourceName, id)) { reject(new DSErrors.R('id "' + id + '" not found in cache!')); } else { item = _this.get(resourceName, id); options = DSUtils._(definition, options); resolve(item); } }).then(function (attrs) { return options.beforeValidate.call(attrs, options, attrs); }) .then(function (attrs) { return options.validate.call(attrs, options, attrs); }) .then(function (attrs) { return options.afterValidate.call(attrs, options, attrs); }) .then(function (attrs) { return options.beforeUpdate.call(attrs, options, attrs); }) .then(function (attrs) { if (options.notify) { _this.emit(options, 'beforeUpdate', DSUtils.copy(attrs)); } if (options.changesOnly) { var resource = _this.store[resourceName]; if (DSUtils.w) { resource.observers[id].deliver(); } var toKeep = []; var changes = _this.changes(resourceName, id); for (var key in changes.added) { toKeep.push(key); } for (key in changes.changed) { toKeep.push(key); } changes = DSUtils.pick(attrs, toKeep); if (DSUtils.isEmpty(changes)) { // no changes, return return attrs; } else { attrs = changes; } } return _this.getAdapter(options).update(definition, id, attrs, options); }) .then(function (data) { return options.afterUpdate.call(data, options, data); }) .then(function (attrs) { if (options.notify) { _this.emit(options, 'afterUpdate', DSUtils.copy(attrs)); } if (options.cacheResponse) { return _this.inject(definition.name, attrs, options); } else { return _this.createInstance(resourceName, attrs, options); } }); } module.exports = save; },{"../../errors":48,"../../utils":50}],35:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function update(resourceName, id, attrs, options) { var _this = this; var definition = _this.definitions[resourceName]; return new DSUtils.Promise(function (resolve, reject) { id = DSUtils.resolveId(definition, id); if (!definition) { reject(new DSErrors.NER(resourceName)); } else if (!DSUtils.isString(id) && !DSUtils.isNumber(id)) { reject(new DSErrors.IA('"id" must be a string or a number!')); } else { options = DSUtils._(definition, options); resolve(attrs); } }).then(function (attrs) { return options.beforeValidate.call(attrs, options, attrs); }) .then(function (attrs) { return options.validate.call(attrs, options, attrs); }) .then(function (attrs) { return options.afterValidate.call(attrs, options, attrs); }) .then(function (attrs) { return options.beforeUpdate.call(attrs, options, attrs); }) .then(function (attrs) { if (options.notify) { _this.emit(options, 'beforeUpdate', DSUtils.copy(attrs)); } return _this.getAdapter(options).update(definition, id, attrs, options); }) .then(function (data) { return options.afterUpdate.call(data, options, data); }) .then(function (attrs) { if (options.notify) { _this.emit(options, 'afterUpdate', DSUtils.copy(attrs)); } if (options.cacheResponse) { return _this.inject(definition.name, attrs, options); } else { return _this.createInstance(resourceName, attrs, options); } }); } module.exports = update; },{"../../errors":48,"../../utils":50}],36:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function updateAll(resourceName, attrs, params, options) { var _this = this; var definition = _this.definitions[resourceName]; return new DSUtils.Promise(function (resolve, reject) { if (!definition) { reject(new DSErrors.NER(resourceName)); } else { options = DSUtils._(definition, options); resolve(attrs); } }).then(function (attrs) { return options.beforeValidate.call(attrs, options, attrs); }) .then(function (attrs) { return options.validate.call(attrs, options, attrs); }) .then(function (attrs) { return options.afterValidate.call(attrs, options, attrs); }) .then(function (attrs) { return options.beforeUpdate.call(attrs, options, attrs); }) .then(function (attrs) { if (options.notify) { _this.emit(options, 'beforeUpdate', DSUtils.copy(attrs)); } return _this.getAdapter(options).updateAll(definition, attrs, params, options); }) .then(function (data) { return options.afterUpdate.call(data, options, data); }) .then(function (data) { if (options.notify) { _this.emit(options, 'afterUpdate', DSUtils.copy(attrs)); } if (options.cacheResponse) { return _this.inject(definition.name, data, options); } else { var instances = []; DSUtils.forEach(data, function (item) { instances.push(_this.createInstance(resourceName, item, options)); }); return instances; } }); } module.exports = updateAll; },{"../../errors":48,"../../utils":50}],37:[function(require,module,exports){ var DSUtils = require('../utils'); var DSErrors = require('../errors'); var syncMethods = require('./sync_methods'); var asyncMethods = require('./async_methods'); var Schemator; function lifecycleNoopCb(resource, attrs, cb) { cb(null, attrs); } function lifecycleNoop(resource, attrs) { return attrs; } function compare(orderBy, index, a, b) { var def = orderBy[index]; var cA = DSUtils.get(a, def[0]), cB = DSUtils.get(b, def[0]); if (DSUtils.isString(cA)) { cA = DSUtils.upperCase(cA); } if (DSUtils.isString(cB)) { cB = DSUtils.upperCase(cB); } if (def[1] === 'DESC') { if (cB < cA) { return -1; } else if (cB > cA) { return 1; } else { if (index < orderBy.length - 1) { return compare(orderBy, index + 1, a, b); } else { return 0; } } } else { if (cA < cB) { return -1; } else if (cA > cB) { return 1; } else { if (index < orderBy.length - 1) { return compare(orderBy, index + 1, a, b); } else { return 0; } } } } function Defaults() { } var defaultsPrototype = Defaults.prototype; defaultsPrototype.actions = {}; defaultsPrototype.afterCreate = lifecycleNoopCb; defaultsPrototype.afterCreateInstance = lifecycleNoop; defaultsPrototype.afterDestroy = lifecycleNoopCb; defaultsPrototype.afterEject = lifecycleNoop; defaultsPrototype.afterInject = lifecycleNoop; defaultsPrototype.afterReap = lifecycleNoop; defaultsPrototype.afterUpdate = lifecycleNoopCb; defaultsPrototype.afterValidate = lifecycleNoopCb; defaultsPrototype.allowSimpleWhere = true; defaultsPrototype.basePath = ''; defaultsPrototype.beforeCreate = lifecycleNoopCb; defaultsPrototype.beforeCreateInstance = lifecycleNoop; defaultsPrototype.beforeDestroy = lifecycleNoopCb; defaultsPrototype.beforeEject = lifecycleNoop; defaultsPrototype.beforeInject = lifecycleNoop; defaultsPrototype.beforeReap = lifecycleNoop; defaultsPrototype.beforeUpdate = lifecycleNoopCb; defaultsPrototype.beforeValidate = lifecycleNoopCb; defaultsPrototype.bypassCache = false; defaultsPrototype.cacheResponse = !!DSUtils.w; defaultsPrototype.defaultAdapter = 'http'; defaultsPrototype.debug = true; defaultsPrototype.eagerEject = false; // TODO: Implement eagerInject in DS#create defaultsPrototype.eagerInject = false; defaultsPrototype.endpoint = ''; defaultsPrototype.error = console ? function (a, b, c) { console[typeof console.error === 'function' ? 'error' : 'log'](a, b, c); } : false; defaultsPrototype.errorFn = function (a, b) { if (this.error && typeof this.error === 'function') { try { if (typeof a === 'string') { throw new Error(a); } else { throw a; } } catch (err) { a = err; } this.error(this.name || null, a || null, b || null); } }; defaultsPrototype.fallbackAdapters = ['http']; defaultsPrototype.findBelongsTo = true; defaultsPrototype.findHasOne = true; defaultsPrototype.findHasMany = true; defaultsPrototype.findInverseLinks = true; defaultsPrototype.idAttribute = 'id'; defaultsPrototype.ignoredChanges = [/\$/]; defaultsPrototype.ignoreMissing = false; defaultsPrototype.keepChangeHistory = false; defaultsPrototype.loadFromServer = false; defaultsPrototype.log = console ? function (a, b, c, d, e) { console[typeof console.info === 'function' ? 'info' : 'log'](a, b, c, d, e); } : false; defaultsPrototype.logFn = function (a, b, c, d) { if (this.debug && this.log && typeof this.log === 'function') { this.log(this.name || null, a || null, b || null, c || null, d || null); } }; defaultsPrototype.maxAge = false; defaultsPrototype.notify = !!DSUtils.w; defaultsPrototype.reapAction = !!DSUtils.w ? 'inject' : 'none'; defaultsPrototype.reapInterval = !!DSUtils.w ? 30000 : false; defaultsPrototype.resetHistoryOnInject = true; defaultsPrototype.strategy = 'single'; defaultsPrototype.upsert = !!DSUtils.w; defaultsPrototype.useClass = true; defaultsPrototype.useFilter = false; defaultsPrototype.validate = lifecycleNoopCb; defaultsPrototype.defaultFilter = function (collection, resourceName, params, options) { var _this = this; var filtered = collection; var where = null; var reserved = { skip: '', offset: '', where: '', limit: '', orderBy: '', sort: '' }; params = params || {}; options = options || {}; if (DSUtils.isObject(params.where)) { where = params.where; } else { where = {}; } if (options.allowSimpleWhere) { DSUtils.forOwn(params, function (value, key) { if (!(key in reserved) && !(key in where)) { where[key] = { '==': value }; } }); } if (DSUtils.isEmpty(where)) { where = null; } if (where) { filtered = DSUtils.filter(filtered, function (attrs) { var first = true; var keep = true; DSUtils.forOwn(where, function (clause, field) { if (DSUtils.isString(clause)) { clause = { '===': clause }; } else if (DSUtils.isNumber(clause) || DSUtils.isBoolean(clause)) { clause = { '==': clause }; } if (DSUtils.isObject(clause)) { DSUtils.forOwn(clause, function (term, op) { var expr; var isOr = op[0] === '|'; var val = attrs[field]; op = isOr ? op.substr(1) : op; if (op === '==') { expr = val == term; } else if (op === '===') { expr = val === term; } else if (op === '!=') { expr = val != term; } else if (op === '!==') { expr = val !== term; } else if (op === '>') { expr = val > term; } else if (op === '>=') { expr = val >= term; } else if (op === '<') { expr = val < term; } else if (op === '<=') { expr = val <= term; } else if (op === 'isectEmpty') { expr = !DSUtils.intersection((val || []), (term || [])).length; } else if (op === 'isectNotEmpty') { expr = DSUtils.intersection((val || []), (term || [])).length; } else if (op === 'in') { if (DSUtils.isString(term)) { expr = term.indexOf(val) !== -1; } else { expr = DSUtils.contains(term, val); } } else if (op === 'notIn') { if (DSUtils.isString(term)) { expr = term.indexOf(val) === -1; } else { expr = !DSUtils.contains(term, val); } } else if (op === 'contains') { if (DSUtils.isString(val)) { expr = val.indexOf(term) !== -1; } else { expr = DSUtils.contains(val, term); } } else if (op === 'notContains') { if (DSUtils.isString(val)) { expr = val.indexOf(term) === -1; } else { expr = !DSUtils.contains(val, term); } } if (expr !== undefined) { keep = first ? expr : (isOr ? keep || expr : keep && expr); } first = false; }); } }); return keep; }); } var orderBy = null; if (DSUtils.isString(params.orderBy)) { orderBy = [ [params.orderBy, 'ASC'] ]; } else if (DSUtils.isArray(params.orderBy)) { orderBy = params.orderBy; } if (!orderBy && DSUtils.isString(params.sort)) { orderBy = [ [params.sort, 'ASC'] ]; } else if (!orderBy && DSUtils.isArray(params.sort)) { orderBy = params.sort; } // Apply 'orderBy' if (orderBy) { var index = 0; DSUtils.forEach(orderBy, function (def, i) { if (DSUtils.isString(def)) { orderBy[i] = [def, 'ASC']; } else if (!DSUtils.isArray(def)) { throw new _this.errors.IllegalArgumentError('DS.filter(resourceName[, params][, options]): ' + DSUtils.toJson(def) + ': Must be a string or an array!', { params: { 'orderBy[i]': { actual: typeof def, expected: 'string|array' } } }); } }); filtered = DSUtils.sort(filtered, function (a, b) { return compare(orderBy, index, a, b); }); } var limit = DSUtils.isNumber(params.limit) ? params.limit : null; var skip = null; if (DSUtils.isNumber(params.skip)) { skip = params.skip; } else if (DSUtils.isNumber(params.offset)) { skip = params.offset; } // Apply 'limit' and 'skip' if (limit && skip) { filtered = DSUtils.slice(filtered, skip, Math.min(filtered.length, skip + limit)); } else if (DSUtils.isNumber(limit)) { filtered = DSUtils.slice(filtered, 0, Math.min(filtered.length, limit)); } else if (DSUtils.isNumber(skip)) { if (skip < filtered.length) { filtered = DSUtils.slice(filtered, skip); } else { filtered = []; } } return filtered; }; function DS(options) { var _this = this; options = options || {}; try { Schemator = require('js-data-schema'); } catch (e) { } if (!Schemator || DSUtils.isEmpty(Schemator)) { try { Schemator = window.Schemator; } catch (e) { } } if (Schemator || options.schemator) { _this.schemator = options.schemator || new Schemator(); } _this.store = {}; _this.definitions = {}; _this.adapters = {}; _this.defaults = new Defaults(); _this.observe = DSUtils.observe; DSUtils.forOwn(options, function (v, k) { _this.defaults[k] = v; }); } var dsPrototype = DS.prototype; dsPrototype.getAdapter = function (options) { var errorIfNotExist = false; options = options || {}; if (DSUtils.isString(options)) { errorIfNotExist = true; options = { adapter: options }; } var adapter = this.adapters[options.adapter]; if (adapter) { return adapter; } else if (errorIfNotExist) { throw new Error(options.adapter + ' is not a registered adapter!'); } else { return this.adapters[options.defaultAdapter]; } }; dsPrototype.registerAdapter = function (name, Adapter, options) { var _this = this; options = options || {}; if (DSUtils.isFunction(Adapter)) { _this.adapters[name] = new Adapter(options); } else { _this.adapters[name] = Adapter; } if (options.default) { _this.defaults.defaultAdapter = name; } }; dsPrototype.emit = function (definition, event) { var args = Array.prototype.slice.call(arguments, 2); args.unshift(definition.name); args.unshift('DS.' + event); definition.emit.apply(definition, args); }; dsPrototype.is = function is(resourceName, instance) { var definition = this.definitions[resourceName]; if (!definition) { throw new DSErrors.NER(resourceName); } return instance instanceof definition[definition.class]; }; dsPrototype.errors = require('../errors'); dsPrototype.utils = DSUtils; DSUtils.deepMixIn(dsPrototype, syncMethods); DSUtils.deepMixIn(dsPrototype, asyncMethods); module.exports = DS; },{"../errors":48,"../utils":50,"./async_methods":32,"./sync_methods":42,"js-data-schema":"js-data-schema"}],38:[function(require,module,exports){ /*jshint evil:true, loopfunc:true*/ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function Resource(options) { DSUtils.deepMixIn(this, options); if ('endpoint' in options) { this.endpoint = options.endpoint; } else { this.endpoint = this.name; } } var instanceMethods = [ 'compute', 'refresh', 'save', 'update', 'destroy', 'loadRelations', 'changeHistory', 'changes', 'hasChanges', 'lastModified', 'lastSaved', 'link', 'linkInverse', 'previous', 'unlinkInverse' ]; function defineResource(definition) { var _this = this; var definitions = _this.definitions; if (DSUtils.isString(definition)) { definition = { name: definition.replace(/\s/gi, '') }; } if (!DSUtils.isObject(definition)) { throw new DSErrors.IA('"definition" must be an object!'); } else if (!DSUtils.isString(definition.name)) { throw new DSErrors.IA('"name" must be a string!'); } else if (_this.store[definition.name]) { throw new DSErrors.R(definition.name + ' is already registered!'); } try { // Inherit from global defaults Resource.prototype = _this.defaults; definitions[definition.name] = new Resource(definition); var def = definitions[definition.name]; if (!DSUtils.isString(def.idAttribute)) { throw new DSErrors.IA('"idAttribute" must be a string!'); } // Setup nested parent configuration if (def.relations) { def.relationList = []; def.relationFields = []; DSUtils.forOwn(def.relations, function (relatedModels, type) { DSUtils.forOwn(relatedModels, function (defs, relationName) { if (!DSUtils.isArray(defs)) { relatedModels[relationName] = [defs]; } DSUtils.forEach(relatedModels[relationName], function (d) { d.type = type; d.relation = relationName; d.name = def.name; def.relationList.push(d); def.relationFields.push(d.localField); }); }); }); if (def.relations.belongsTo) { DSUtils.forOwn(def.relations.belongsTo, function (relatedModel, modelName) { DSUtils.forEach(relatedModel, function (relation) { if (relation.parent) { def.parent = modelName; def.parentKey = relation.localKey; def.parentField = relation.localField; } }); }); } if (typeof Object.freeze === 'function') { Object.freeze(def.relations); Object.freeze(def.relationList); } } def.getResource = function (resourceName) { return _this.definitions[resourceName]; }; def.getEndpoint = function (id, options) { options.params = options.params || {}; var item; var parentKey = def.parentKey; var endpoint = options.hasOwnProperty('endpoint') ? options.endpoint : def.endpoint; var parentField = def.parentField; var parentDef = definitions[def.parent]; var parentId = options.params[parentKey]; if (parentId === false || !parentKey || !parentDef) { if (parentId === false) { delete options.params[parentKey]; } return endpoint; } else { delete options.params[parentKey]; if (DSUtils.isNumber(id) || DSUtils.isString(id)) { item = def.get(id); } else if (DSUtils.isObject(id)) { item = id; } if (item) { parentId = parentId || item[parentKey] || (item[parentField] ? item[parentField][parentDef.idAttribute] : null); } if (parentId) { delete options.endpoint; var _options = {}; DSUtils.forOwn(options, function (value, key) { _options[key] = value; }); return DSUtils.makePath(parentDef.getEndpoint(parentId, DSUtils._(parentDef, _options)), parentId, endpoint); } else { return endpoint; } } }; // Remove this in v0.11.0 and make a breaking change notice // the the `filter` option has been renamed to `defaultFilter` if (def.filter) { def.defaultFilter = def.filter; delete def.filter; } // Create the wrapper class for the new resource def['class'] = DSUtils.pascalCase(definition.name); try { if (typeof def.useClass === 'function') { eval('function ' + def['class'] + '() { def.useClass.call(this); }'); def[def['class']] = eval(def['class']); def[def['class']].prototype = (function (proto) { function Ctor() { } Ctor.prototype = proto; return new Ctor(); })(def.useClass.prototype); } else { eval('function ' + def['class'] + '() {}'); def[def['class']] = eval(def['class']); } } catch (e) { def[def['class']] = function () { }; } // Apply developer-defined methods if (def.methods) { DSUtils.deepMixIn(def[def['class']].prototype, def.methods); } def[def['class']].prototype.set = function (key, value) { DSUtils.set(this, key, value); var observer = _this.store[def.name].observers[this[def.idAttribute]]; if (observer && !DSUtils.observe.hasObjectObserve) { observer.deliver(); } else { _this.compute(def.name, this); } return this; }; def[def['class']].prototype.get = function (key) { return DSUtils.get(this, key); }; // Prepare for computed properties if (def.computed) { DSUtils.forOwn(def.computed, function (fn, field) { if (DSUtils.isFunction(fn)) { def.computed[field] = [fn]; fn = def.computed[field]; } if (def.methods && field in def.methods) { def.errorFn('Computed property "' + field + '" conflicts with previously defined prototype method!'); } var deps; if (fn.length === 1) { var match = fn[0].toString().match(/function.*?\(([\s\S]*?)\)/); deps = match[1].split(','); def.computed[field] = deps.concat(fn); fn = def.computed[field]; if (deps.length) { def.errorFn('Use the computed property array syntax for compatibility with minified code!'); } } deps = fn.slice(0, fn.length - 1); DSUtils.forEach(deps, function (val, index) { deps[index] = val.trim(); }); fn.deps = DSUtils.filter(deps, function (dep) { return !!dep; }); }); } if (definition.schema && _this.schemator) { def.schema = _this.schemator.defineSchema(def.name, definition.schema); if (!definition.hasOwnProperty('validate')) { def.validate = function (resourceName, attrs, cb) { def.schema.validate(attrs, { ignoreMissing: def.ignoreMissing }, function (err) { if (err) { return cb(err); } else { return cb(null, attrs); } }); }; } } DSUtils.forEach(instanceMethods, function (name) { def[def['class']].prototype['DS' + DSUtils.pascalCase(name)] = function () { var args = Array.prototype.slice.call(arguments); args.unshift(this[def.idAttribute] || this); args.unshift(def.name); return _this[name].apply(_this, args); }; }); def[def['class']].prototype.DSCreate = function () { var args = Array.prototype.slice.call(arguments); args.unshift(this); args.unshift(def.name); return _this.create.apply(_this, args); }; // Initialize store data for the new resource _this.store[def.name] = { collection: [], expiresHeap: new DSUtils.DSBinaryHeap(function (x) { return x.expires; }, function (x, y) { return x.item === y; }), completedQueries: {}, queryData: {}, pendingQueries: {}, index: {}, modified: {}, saved: {}, previousAttributes: {}, observers: {}, changeHistories: {}, changeHistory: [], collectionModified: 0 }; if (def.reapInterval) { setInterval(function () { _this.reap(def.name, { isInterval: true }); }, def.reapInterval); } // Proxy DS methods with shorthand ones for (var key in _this) { if (typeof _this[key] === 'function' && key !== 'defineResource') { (function (k) { def[k] = function () { var args = Array.prototype.slice.call(arguments); args.unshift(def.name); return _this[k].apply(_this, args); }; })(key); } } def.beforeValidate = DSUtils.promisify(def.beforeValidate); def.validate = DSUtils.promisify(def.validate); def.afterValidate = DSUtils.promisify(def.afterValidate); def.beforeCreate = DSUtils.promisify(def.beforeCreate); def.afterCreate = DSUtils.promisify(def.afterCreate); def.beforeUpdate = DSUtils.promisify(def.beforeUpdate); def.afterUpdate = DSUtils.promisify(def.afterUpdate); def.beforeDestroy = DSUtils.promisify(def.beforeDestroy); def.afterDestroy = DSUtils.promisify(def.afterDestroy); DSUtils.forOwn(def.actions, function addAction(action, name) { if (def[name]) { throw new Error('Cannot override existing method "' + name + '"!'); } def[name] = function (options) { options = options || {}; var adapter = _this.getAdapter(action.adapter || 'http'); var config = DSUtils.deepMixIn({}, action); if (!options.hasOwnProperty('endpoint') && config.endpoint) { options.endpoint = config.endpoint; } if (typeof options.getEndpoint === 'function') { config.url = options.getEndpoint(def, options); } else { config.url = DSUtils.makePath(options.basePath || adapter.defaults.basePath || def.basePath, def.getEndpoint(null, options), name); } config.method = config.method || 'GET'; DSUtils.deepMixIn(config, options); return adapter.HTTP(config); }; }); // Mix-in events DSUtils.Events(def); return def; } catch (err) { delete definitions[definition.name]; delete _this.store[definition.name]; throw err; } } module.exports = defineResource; },{"../../errors":48,"../../utils":50}],39:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function eject(resourceName, id, options) { var _this = this; var definition = _this.definitions[resourceName]; var resource = _this.store[resourceName]; var item; var found = false; id = DSUtils.resolveId(definition, id); if (!definition) { throw new DSErrors.NER(resourceName); } else if (!DSUtils.isString(id) && !DSUtils.isNumber(id)) { throw new DSErrors.IA('"id" must be a string or a number!'); } options = DSUtils._(definition, options); for (var i = 0; i < resource.collection.length; i++) { if (resource.collection[i][definition.idAttribute] == id) { item = resource.collection[i]; resource.expiresHeap.remove(item); found = true; break; } } if (found) { if (options.notify) { definition.beforeEject(options, item); _this.emit(options, 'beforeEject', DSUtils.copy(item)); } _this.unlinkInverse(definition.name, id); resource.collection.splice(i, 1); if (DSUtils.w) { resource.observers[id].close(); } delete resource.observers[id]; delete resource.index[id]; delete resource.previousAttributes[id]; delete resource.completedQueries[id]; delete resource.pendingQueries[id]; DSUtils.forEach(resource.changeHistories[id], function (changeRecord) { DSUtils.remove(resource.changeHistory, changeRecord); }); var toRemove = []; DSUtils.forOwn(resource.queryData, function (items, queryHash) { if (items.$$injected) { DSUtils.remove(items, item); } if (!items.length) { toRemove.push(queryHash); } }); DSUtils.forEach(toRemove, function (queryHash) { delete resource.completedQueries[queryHash]; delete resource.queryData[queryHash]; }); delete resource.changeHistories[id]; delete resource.modified[id]; delete resource.saved[id]; resource.collectionModified = DSUtils.updateTimestamp(resource.collectionModified); if (options.notify) { definition.afterEject(options, item); _this.emit(options, 'afterEject', DSUtils.copy(item)); } return item; } } module.exports = eject; },{"../../errors":48,"../../utils":50}],40:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function ejectAll(resourceName, params, options) { var _this = this; var definition = _this.definitions[resourceName]; params = params || {}; if (!definition) { throw new DSErrors.NER(resourceName); } else if (!DSUtils.isObject(params)) { throw new DSErrors.IA('"params" must be an object!'); } var resource = _this.store[resourceName]; if (DSUtils.isEmpty(params)) { resource.completedQueries = {}; } var queryHash = DSUtils.toJson(params); var items = _this.filter(definition.name, params); var ids = []; DSUtils.forEach(items, function (item) { if (item && item[definition.idAttribute]) { ids.push(item[definition.idAttribute]); } }); DSUtils.forEach(ids, function (id) { _this.eject(definition.name, id, options); }); delete resource.completedQueries[queryHash]; resource.collectionModified = DSUtils.updateTimestamp(resource.collectionModified); return items; } module.exports = ejectAll; },{"../../errors":48,"../../utils":50}],41:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function filter(resourceName, params, options) { var _this = this; var definition = _this.definitions[resourceName]; var resource = _this.store[resourceName]; if (!definition) { throw new DSErrors.NER(resourceName); } else if (params && !DSUtils.isObject(params)) { throw new DSErrors.IA('"params" must be an object!'); } options = DSUtils._(definition, options); // Protect against null params = params || {}; var queryHash = DSUtils.toJson(params); if (!(queryHash in resource.completedQueries) && options.loadFromServer) { // This particular query has never been completed if (!resource.pendingQueries[queryHash]) { // This particular query has never even been started _this.findAll(resourceName, params, options); } } return definition.defaultFilter.call(_this, resource.collection, resourceName, params, options); } module.exports = filter; },{"../../errors":48,"../../utils":50}],42:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); var NER = DSErrors.NER; var IA = DSErrors.IA; var R = DSErrors.R; function changes(resourceName, id, options) { var _this = this; var definition = _this.definitions[resourceName]; options = options || {}; id = DSUtils.resolveId(definition, id); if (!definition) { throw new NER(resourceName); } else if (!DSUtils.isString(id) && !DSUtils.isNumber(id)) { throw new IA('"id" must be a string or a number!'); } options = DSUtils._(definition, options); var item = _this.get(resourceName, id); if (item) { if (DSUtils.w) { _this.store[resourceName].observers[id].deliver(); } var diff = DSUtils.diffObjectFromOldObject(item, _this.store[resourceName].previousAttributes[id], DSUtils.equals, options.ignoredChanges); DSUtils.forOwn(diff, function (changeset, name) { var toKeep = []; DSUtils.forOwn(changeset, function (value, field) { if (!DSUtils.isFunction(value)) { toKeep.push(field); } }); diff[name] = DSUtils.pick(diff[name], toKeep); }); DSUtils.forEach(definition.relationFields, function (field) { delete diff.added[field]; delete diff.removed[field]; delete diff.changed[field]; }); return diff; } } function changeHistory(resourceName, id) { var _this = this; var definition = _this.definitions[resourceName]; var resource = _this.store[resourceName]; id = DSUtils.resolveId(definition, id); if (resourceName && !_this.definitions[resourceName]) { throw new NER(resourceName); } else if (id && !DSUtils.isString(id) && !DSUtils.isNumber(id)) { throw new IA('"id" must be a string or a number!'); } if (!definition.keepChangeHistory) { definition.errorFn('changeHistory is disabled for this resource!'); } else { if (resourceName) { var item = _this.get(resourceName, id); if (item) { return resource.changeHistories[id]; } } else { return resource.changeHistory; } } } function compute(resourceName, instance) { var _this = this; var definition = _this.definitions[resourceName]; instance = DSUtils.resolveItem(_this.store[resourceName], instance); if (!definition) { throw new NER(resourceName); } else if (!instance) { throw new R('Item not in the store!'); } else if (!DSUtils.isObject(instance) && !DSUtils.isString(instance) && !DSUtils.isNumber(instance)) { throw new IA('"instance" must be an object, string or number!'); } DSUtils.forOwn(definition.computed, function (fn, field) { DSUtils.compute.call(instance, fn, field); }); return instance; } function createInstance(resourceName, attrs, options) { var definition = this.definitions[resourceName]; var item; attrs = attrs || {}; if (!definition) { throw new NER(resourceName); } else if (attrs && !DSUtils.isObject(attrs)) { throw new IA('"attrs" must be an object!'); } options = DSUtils._(definition, options); if (options.notify) { options.beforeCreateInstance(options, attrs); } if (options.useClass) { var Constructor = definition[definition.class]; item = new Constructor(); } else { item = {}; } DSUtils.deepMixIn(item, attrs); if (options.notify) { options.afterCreateInstance(options, attrs); } return item; } function diffIsEmpty(diff) { return !(DSUtils.isEmpty(diff.added) && DSUtils.isEmpty(diff.removed) && DSUtils.isEmpty(diff.changed)); } function digest() { this.observe.Platform.performMicrotaskCheckpoint(); } function get(resourceName, id, options) { var _this = this; var definition = _this.definitions[resourceName]; if (!definition) { throw new NER(resourceName); } else if (!DSUtils.isString(id) && !DSUtils.isNumber(id)) { throw new IA('"id" must be a string or a number!'); } options = DSUtils._(definition, options); // cache miss, request resource from server var item = _this.store[resourceName].index[id]; if (!item && options.loadFromServer) { _this.find(resourceName, id, options); } // return resource from cache return item; } function getAll(resourceName, ids) { var _this = this; var definition = _this.definitions[resourceName]; var resource = _this.store[resourceName]; var collection = []; if (!definition) { throw new NER(resourceName); } else if (ids && !DSUtils.isArray(ids)) { throw new IA('"ids" must be an array!'); } if (DSUtils.isArray(ids)) { var length = ids.length; for (var i = 0; i < length; i++) { if (resource.index[ids[i]]) { collection.push(resource.index[ids[i]]); } } } else { collection = resource.collection.slice(); } return collection; } function hasChanges(resourceName, id) { var _this = this; var definition = _this.definitions[resourceName]; id = DSUtils.resolveId(definition, id); if (!definition) { throw new NER(resourceName); } else if (!DSUtils.isString(id) && !DSUtils.isNumber(id)) { throw new IA('"id" must be a string or a number!'); } // return resource from cache if (_this.get(resourceName, id)) { return diffIsEmpty(_this.changes(resourceName, id)); } else { return false; } } function lastModified(resourceName, id) { var definition = this.definitions[resourceName]; var resource = this.store[resourceName]; id = DSUtils.resolveId(definition, id); if (!definition) { throw new NER(resourceName); } if (id) { if (!(id in resource.modified)) { resource.modified[id] = 0; } return resource.modified[id]; } return resource.collectionModified; } function lastSaved(resourceName, id) { var definition = this.definitions[resourceName]; var resource = this.store[resourceName]; id = DSUtils.resolveId(definition, id); if (!definition) { throw new NER(resourceName); } if (!(id in resource.saved)) { resource.saved[id] = 0; } return resource.saved[id]; } function previous(resourceName, id) { var _this = this; var definition = _this.definitions[resourceName]; var resource = _this.store[resourceName]; id = DSUtils.resolveId(definition, id); if (!definition) { throw new NER(resourceName); } else if (!DSUtils.isString(id) && !DSUtils.isNumber(id)) { throw new IA('"id" must be a string or a number!'); } // return resource from cache return resource.previousAttributes[id] ? DSUtils.copy(resource.previousAttributes[id]) : undefined; } module.exports = { changes: changes, changeHistory: changeHistory, compute: compute, createInstance: createInstance, defineResource: require('./defineResource'), digest: digest, eject: require('./eject'), ejectAll: require('./ejectAll'), filter: require('./filter'), get: get, getAll: getAll, hasChanges: hasChanges, inject: require('./inject'), lastModified: lastModified, lastSaved: lastSaved, link: require('./link'), linkAll: require('./linkAll'), linkInverse: require('./linkInverse'), previous: previous, unlinkInverse: require('./unlinkInverse') }; },{"../../errors":48,"../../utils":50,"./defineResource":38,"./eject":39,"./ejectAll":40,"./filter":41,"./inject":43,"./link":44,"./linkAll":45,"./linkInverse":46,"./unlinkInverse":47}],43:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function _getReactFunction(DS, definition, resource) { var name = definition.name; return function _react(added, removed, changed, oldValueFn, firstTime) { var target = this; var item; var innerId = (oldValueFn && oldValueFn(definition.idAttribute)) ? oldValueFn(definition.idAttribute) : target[definition.idAttribute]; DSUtils.forEach(definition.relationFields, function (field) { delete added[field]; delete removed[field]; delete changed[field]; }); if (!DSUtils.isEmpty(added) || !DSUtils.isEmpty(removed) || !DSUtils.isEmpty(changed) || firstTime) { item = DS.get(name, innerId); resource.modified[innerId] = DSUtils.updateTimestamp(resource.modified[innerId]); resource.collectionModified = DSUtils.updateTimestamp(resource.collectionModified); if (definition.keepChangeHistory) { var changeRecord = { resourceName: name, target: item, added: added, removed: removed, changed: changed, timestamp: resource.modified[innerId] }; resource.changeHistories[innerId].push(changeRecord); resource.changeHistory.push(changeRecord); } } if (definition.computed) { item = item || DS.get(name, innerId); DSUtils.forOwn(definition.computed, function (fn, field) { var compute = false; // check if required fields changed DSUtils.forEach(fn.deps, function (dep) { if (dep in added || dep in removed || dep in changed || !(field in item)) { compute = true; } }); compute = compute || !fn.deps.length; if (compute) { DSUtils.compute.call(item, fn, field); } }); } if (definition.relations) { item = item || DS.get(name, innerId); DSUtils.forEach(definition.relationList, function (def) { if (item[def.localField] && (def.localKey in added || def.localKey in removed || def.localKey in changed)) { DS.link(name, item[definition.idAttribute], [def.relation]); } }); } if (definition.idAttribute in changed) { definition.errorFn('Doh! You just changed the primary key of an object! Your data for the "' + name + '" resource is now in an undefined (probably broken) state.'); } }; } function _inject(definition, resource, attrs, options) { var _this = this; var _react = _getReactFunction(_this, definition, resource, attrs, options); var injected; if (DSUtils.isArray(attrs)) { injected = []; for (var i = 0; i < attrs.length; i++) { injected.push(_inject.call(_this, definition, resource, attrs[i], options)); } } else { // check if "idAttribute" is a computed property var c = definition.computed; var idA = definition.idAttribute; if (c && c[idA]) { var args = []; DSUtils.forEach(c[idA].deps, function (dep) { args.push(attrs[dep]); }); attrs[idA] = c[idA][c[idA].length - 1].apply(attrs, args); } if (!(idA in attrs)) { var error = new DSErrors.R(definition.name + '.inject: "attrs" must contain the property specified by `idAttribute`!'); options.errorFn(error); throw error; } else { try { DSUtils.forEach(definition.relationList, function (def) { var relationName = def.relation; var relationDef = _this.definitions[relationName]; var toInject = attrs[def.localField]; if (toInject) { if (!relationDef) { throw new DSErrors.R(definition.name + ' relation is defined but the resource is not!'); } if (DSUtils.isArray(toInject)) { var items = []; DSUtils.forEach(toInject, function (toInjectItem) { if (toInjectItem !== _this.store[relationName][toInjectItem[relationDef.idAttribute]]) { try { var injectedItem = _this.inject(relationName, toInjectItem, options); if (def.foreignKey) { injectedItem[def.foreignKey] = attrs[definition.idAttribute]; } items.push(injectedItem); } catch (err) { options.errorFn(err, 'Failed to inject ' + def.type + ' relation: "' + relationName + '"!'); } } }); attrs[def.localField] = items; } else { if (toInject !== _this.store[relationName][toInject[relationDef.idAttribute]]) { try { attrs[def.localField] = _this.inject(relationName, attrs[def.localField], options); if (def.foreignKey) { attrs[def.localField][def.foreignKey] = attrs[definition.idAttribute]; } } catch (err) { options.errorFn(err, 'Failed to inject ' + def.type + ' relation: "' + relationName + '"!'); } } } } }); var id = attrs[idA]; var item = _this.get(definition.name, id); var initialLastModified = item ? resource.modified[id] : 0; if (!item) { if (options.useClass) { if (attrs instanceof definition[definition['class']]) { item = attrs; } else { item = new definition[definition['class']](); } } else { item = {}; } resource.previousAttributes[id] = DSUtils.copy(attrs); DSUtils.deepMixIn(item, attrs); resource.collection.push(item); resource.changeHistories[id] = []; if (DSUtils.w) { resource.observers[id] = new _this.observe.ObjectObserver(item); resource.observers[id].open(_react, item); } resource.index[id] = item; _react.call(item, {}, {}, {}, null, true); } else { DSUtils.deepMixIn(item, attrs); if (definition.resetHistoryOnInject) { resource.previousAttributes[id] = {}; DSUtils.deepMixIn(resource.previousAttributes[id], attrs); if (resource.changeHistories[id].length) { DSUtils.forEach(resource.changeHistories[id], function (changeRecord) { DSUtils.remove(resource.changeHistory, changeRecord); }); resource.changeHistories[id].splice(0, resource.changeHistories[id].length); } } if (DSUtils.w) { resource.observers[id].deliver(); } } resource.saved[id] = DSUtils.updateTimestamp(resource.saved[id]); resource.modified[id] = initialLastModified && resource.modified[id] === initialLastModified ? DSUtils.updateTimestamp(resource.modified[id]) : resource.modified[id]; resource.expiresHeap.remove(item); resource.expiresHeap.push({ item: item, timestamp: resource.saved[id], expires: definition.maxAge ? resource.saved[id] + definition.maxAge : Number.MAX_VALUE }); injected = item; } catch (err) { options.errorFn(err, attrs); } } } return injected; } function _link(definition, injected, options) { var _this = this; DSUtils.forEach(definition.relationList, function (def) { if (options.findBelongsTo && def.type === 'belongsTo' && injected[definition.idAttribute]) { _this.link(definition.name, injected[definition.idAttribute], [def.relation]); } else if ((options.findHasMany && def.type === 'hasMany') || (options.findHasOne && def.type === 'hasOne')) { _this.link(definition.name, injected[definition.idAttribute], [def.relation]); } }); } function inject(resourceName, attrs, options) { var _this = this; var definition = _this.definitions[resourceName]; var resource = _this.store[resourceName]; var injected; if (!definition) { throw new DSErrors.NER(resourceName); } else if (!DSUtils.isObject(attrs) && !DSUtils.isArray(attrs)) { throw new DSErrors.IA(resourceName + '.inject: "attrs" must be an object or an array!'); } var name = definition.name; options = DSUtils._(definition, options); if (options.notify) { options.beforeInject(options, attrs); _this.emit(options, 'beforeInject', DSUtils.copy(attrs)); } injected = _inject.call(_this, definition, resource, attrs, options); resource.collectionModified = DSUtils.updateTimestamp(resource.collectionModified); if (options.findInverseLinks) { if (DSUtils.isArray(injected)) { if (injected.length) { _this.linkInverse(name, injected[0][definition.idAttribute]); } } else { _this.linkInverse(name, injected[definition.idAttribute]); } } if (DSUtils.isArray(injected)) { DSUtils.forEach(injected, function (injectedI) { _link.call(_this, definition, injectedI, options); }); } else { _link.call(_this, definition, injected, options); } if (options.notify) { options.afterInject(options, injected); _this.emit(options, 'afterInject', DSUtils.copy(injected)); } return injected; } module.exports = inject; },{"../../errors":48,"../../utils":50}],44:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function link(resourceName, id, relations) { var _this = this; var definition = _this.definitions[resourceName]; relations = relations || []; id = DSUtils.resolveId(definition, id); if (!definition) { throw new DSErrors.NER(resourceName); } else if (!DSUtils.isString(id) && !DSUtils.isNumber(id)) { throw new DSErrors.IA('"id" must be a string or a number!'); } else if (!DSUtils.isArray(relations)) { throw new DSErrors.IA('"relations" must be an array!'); } var linked = _this.get(resourceName, id); if (linked) { DSUtils.forEach(definition.relationList, function (def) { var relationName = def.relation; if (relations.length && !DSUtils.contains(relations, relationName)) { return; } var params = {}; if (def.type === 'belongsTo') { var parent = linked[def.localKey] ? _this.get(relationName, linked[def.localKey]) : null; if (parent) { linked[def.localField] = parent; } } else if (def.type === 'hasMany') { params[def.foreignKey] = linked[definition.idAttribute]; linked[def.localField] = _this.defaults.constructor.prototype.defaultFilter.call(_this, _this.store[relationName].collection, relationName, params, { allowSimpleWhere: true }); } else if (def.type === 'hasOne') { params[def.foreignKey] = linked[definition.idAttribute]; var children = _this.defaults.constructor.prototype.defaultFilter.call(_this, _this.store[relationName].collection, relationName, params, { allowSimpleWhere: true }); if (children.length) { linked[def.localField] = children[0]; } } }); } return linked; } module.exports = link; },{"../../errors":48,"../../utils":50}],45:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function linkAll(resourceName, params, relations) { var _this = this; var definition = _this.definitions[resourceName]; relations = relations || []; if (!definition) { throw new DSErrors.NER(resourceName); } else if (!DSUtils.isArray(relations)) { throw new DSErrors.IA('"relations" must be an array!'); } var linked = _this.filter(resourceName, params); if (linked) { DSUtils.forEach(definition.relationList, function (def) { var relationName = def.relation; if (relations.length && !DSUtils.contains(relations, relationName)) { return; } if (def.type === 'belongsTo') { DSUtils.forEach(linked, function (injectedItem) { var parent = injectedItem[def.localKey] ? _this.get(relationName, injectedItem[def.localKey]) : null; if (parent) { injectedItem[def.localField] = parent; } }); } else if (def.type === 'hasMany') { DSUtils.forEach(linked, function (injectedItem) { var params = {}; params[def.foreignKey] = injectedItem[definition.idAttribute]; injectedItem[def.localField] = _this.defaults.constructor.prototype.defaultFilter.call(_this, _this.store[relationName].collection, relationName, params, { allowSimpleWhere: true }); }); } else if (def.type === 'hasOne') { DSUtils.forEach(linked, function (injectedItem) { var params = {}; params[def.foreignKey] = injectedItem[definition.idAttribute]; var children = _this.defaults.constructor.prototype.defaultFilter.call(_this, _this.store[relationName].collection, relationName, params, { allowSimpleWhere: true }); if (children.length) { injectedItem[def.localField] = children[0]; } }); } }); } return linked; } module.exports = linkAll; },{"../../errors":48,"../../utils":50}],46:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function linkInverse(resourceName, id, relations) { var _this = this; var definition = _this.definitions[resourceName]; relations = relations || []; id = DSUtils.resolveId(definition, id); if (!definition) { throw new DSErrors.NER(resourceName); } else if (!DSUtils.isString(id) && !DSUtils.isNumber(id)) { throw new DSErrors.IA('"id" must be a string or a number!'); } else if (!DSUtils.isArray(relations)) { throw new DSErrors.IA('"relations" must be an array!'); } var linked = _this.get(resourceName, id); if (linked) { DSUtils.forOwn(_this.definitions, function (d) { DSUtils.forOwn(d.relations, function (relatedModels) { DSUtils.forOwn(relatedModels, function (defs, relationName) { if (relations.length && !DSUtils.contains(relations, d.name)) { return; } if (definition.name === relationName) { _this.linkAll(d.name, {}, [definition.name]); } }); }); }); } return linked; } module.exports = linkInverse; },{"../../errors":48,"../../utils":50}],47:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function unlinkInverse(resourceName, id, relations) { var _this = this; var definition = _this.definitions[resourceName]; relations = relations || []; id = DSUtils.resolveId(definition, id); if (!definition) { throw new DSErrors.NER(resourceName); } else if (!DSUtils.isString(id) && !DSUtils.isNumber(id)) { throw new DSErrors.IA('"id" must be a string or a number!'); } else if (!DSUtils.isArray(relations)) { throw new DSErrors.IA('"relations" must be an array!'); } var linked = _this.get(resourceName, id); if (linked) { DSUtils.forOwn(_this.definitions, function (d) { DSUtils.forOwn(d.relations, function (relatedModels) { DSUtils.forOwn(relatedModels, function (defs, relationName) { if (definition.name === relationName) { DSUtils.forEach(defs, function (def) { DSUtils.forEach(_this.store[def.name].collection, function (item) { if (def.type === 'hasMany' && item[def.localField]) { var index; DSUtils.forEach(item[def.localField], function (subItem, i) { if (subItem === linked) { index = i; } }); item[def.localField].splice(index, 1); } else if (item[def.localField] === linked) { delete item[def.localField]; } }); }); } }); }); }); } return linked; } module.exports = unlinkInverse; },{"../../errors":48,"../../utils":50}],48:[function(require,module,exports){ function IllegalArgumentError(message) { Error.call(this); if (typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, this.constructor); } this.type = this.constructor.name; this.message = message || 'Illegal Argument!'; } IllegalArgumentError.prototype = new Error(); IllegalArgumentError.prototype.constructor = IllegalArgumentError; function RuntimeError(message) { Error.call(this); if (typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, this.constructor); } this.type = this.constructor.name; this.message = message || 'RuntimeError Error!'; } RuntimeError.prototype = new Error(); RuntimeError.prototype.constructor = RuntimeError; function NonexistentResourceError(resourceName) { Error.call(this); if (typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, this.constructor); } this.type = this.constructor.name; this.message = (resourceName || '') + ' is not a registered resource!'; } NonexistentResourceError.prototype = new Error(); NonexistentResourceError.prototype.constructor = NonexistentResourceError; module.exports = { IllegalArgumentError: IllegalArgumentError, IA: IllegalArgumentError, RuntimeError: RuntimeError, R: RuntimeError, NonexistentResourceError: NonexistentResourceError, NER: NonexistentResourceError }; },{}],49:[function(require,module,exports){ var DS = require('./datastore'); module.exports = { DS: DS, createStore: function (options) { return new DS(options); }, DSUtils: require('./utils'), DSErrors: require('./errors'), version: { full: '1.4.1', major: parseInt('1', 10), minor: parseInt('4', 10), patch: parseInt('1', 10), alpha: 'false' !== 'false' ? 'false' : false, beta: 'false' !== 'false' ? 'false' : false } }; },{"./datastore":37,"./errors":48,"./utils":50}],50:[function(require,module,exports){ /* jshint -W041 */ var w, _Promise; var objectProto = Object.prototype; var toString = objectProto.toString; var DSErrors = require('./errors'); var forEach = require('mout/array/forEach'); var slice = require('mout/array/slice'); var forOwn = require('mout/object/forOwn'); var observe = require('../lib/observe-js/observe-js'); var es6Promise = require('es6-promise'); es6Promise.polyfill(); var isArray = Array.isArray || function isArray(value) { return toString.call(value) == '[object Array]' || false; }; function isRegExp(value) { return toString.call(value) == '[object RegExp]' || false; } // adapted from lodash.isBoolean function isBoolean(value) { return (value === true || value === false || value && typeof value == 'object' && toString.call(value) == '[object Boolean]') || false; } // adapted from lodash.isString function isString(value) { return typeof value == 'string' || (value && typeof value == 'object' && toString.call(value) == '[object String]') || false; } function isObject(value) { return toString.call(value) == '[object Object]' || false; } // adapted from lodash.isDate function isDate(value) { return (value && typeof value == 'object' && toString.call(value) == '[object Date]') || false; } // adapted from lodash.isNumber function isNumber(value) { var type = typeof value; return type == 'number' || (value && type == 'object' && toString.call(value) == '[object Number]') || false; } // adapted from lodash.isFunction function isFunction(value) { return typeof value == 'function' || (value && toString.call(value) === '[object Function]') || false; } // adapted from mout.isEmpty function isEmpty(val) { if (val == null) { // typeof null == 'object' so we check it first return true; } else if (typeof val === 'string' || isArray(val)) { return !val.length; } else if (typeof val === 'object') { var result = true; forOwn(val, function () { result = false; return false; // break loop }); return result; } else { return true; } } function intersection(array1, array2) { if (!array1 || !array2) { return []; } var result = []; var item; for (var i = 0, length = array1.length; i < length; i++) { item = array1[i]; if (DSUtils.contains(result, item)) { continue; } if (DSUtils.contains(array2, item)) { result.push(item); } } return result; } function filter(array, cb, thisObj) { var results = []; forEach(array, function (value, key, arr) { if (cb(value, key, arr)) { results.push(value); } }, thisObj); return results; } function finallyPolyfill(cb) { var constructor = this.constructor; return this.then(function (value) { return constructor.resolve(cb()).then(function () { return value; }); }, function (reason) { return constructor.resolve(cb()).then(function () { throw reason; }); }); } try { w = window; if (!w.Promise.prototype['finally']) { w.Promise.prototype['finally'] = finallyPolyfill; } _Promise = w.Promise; w = {}; } catch (e) { w = null; _Promise = require('bluebird'); } function updateTimestamp(timestamp) { var newTimestamp = typeof Date.now === 'function' ? Date.now() : new Date().getTime(); if (timestamp && newTimestamp <= timestamp) { return timestamp + 1; } else { return newTimestamp; } } function Events(target) { var events = {}; target = target || this; target.on = function (type, func, ctx) { events[type] = events[type] || []; events[type].push({ f: func, c: ctx }); }; target.off = function (type, func) { var listeners = events[type]; if (!listeners) { events = {}; } else if (func) { for (var i = 0; i < listeners.length; i++) { if (listeners[i] === func) { listeners.splice(i, 1); break; } } } else { listeners.splice(0, listeners.length); } }; target.emit = function () { var args = Array.prototype.slice.call(arguments); var listeners = events[args.shift()] || []; if (listeners) { for (var i = 0; i < listeners.length; i++) { listeners[i].f.apply(listeners[i].c, args); } } }; } /** * @method bubbleUp * @param {array} heap The heap. * @param {function} weightFunc The weight function. * @param {number} n The index of the element to bubble up. */ function bubbleUp(heap, weightFunc, n) { var element = heap[n]; var weight = weightFunc(element); // When at 0, an element can not go up any further. while (n > 0) { // Compute the parent element's index, and fetch it. var parentN = Math.floor((n + 1) / 2) - 1; var parent = heap[parentN]; // If the parent has a lesser weight, things are in order and we // are done. if (weight >= weightFunc(parent)) { break; } else { heap[parentN] = element; heap[n] = parent; n = parentN; } } } /** * @method bubbleDown * @param {array} heap The heap. * @param {function} weightFunc The weight function. * @param {number} n The index of the element to sink down. */ function bubbleDown(heap, weightFunc, n) { var length = heap.length; var node = heap[n]; var nodeWeight = weightFunc(node); while (true) { var child2N = (n + 1) * 2, child1N = child2N - 1; var swap = null; if (child1N < length) { var child1 = heap[child1N], child1Weight = weightFunc(child1); // If the score is less than our node's, we need to swap. if (child1Weight < nodeWeight) { swap = child1N; } } // Do the same checks for the other child. if (child2N < length) { var child2 = heap[child2N], child2Weight = weightFunc(child2); if (child2Weight < (swap === null ? nodeWeight : weightFunc(heap[child1N]))) { swap = child2N; } } if (swap === null) { break; } else { heap[n] = heap[swap]; heap[swap] = node; n = swap; } } } function DSBinaryHeap(weightFunc, compareFunc) { if (weightFunc && !isFunction(weightFunc)) { throw new Error('DSBinaryHeap(weightFunc): weightFunc: must be a function!'); } weightFunc = weightFunc || function (x) { return x; }; compareFunc = compareFunc || function (x, y) { return x === y; }; this.weightFunc = weightFunc; this.compareFunc = compareFunc; this.heap = []; } var dsp = DSBinaryHeap.prototype; dsp.push = function (node) { this.heap.push(node); bubbleUp(this.heap, this.weightFunc, this.heap.length - 1); }; dsp.peek = function () { return this.heap[0]; }; dsp.pop = function () { var front = this.heap[0], end = this.heap.pop(); if (this.heap.length > 0) { this.heap[0] = end; bubbleDown(this.heap, this.weightFunc, 0); } return front; }; dsp.remove = function (node) { var length = this.heap.length; for (var i = 0; i < length; i++) { if (this.compareFunc(this.heap[i], node)) { var removed = this.heap[i]; var end = this.heap.pop(); if (i !== length - 1) { this.heap[i] = end; bubbleUp(this.heap, this.weightFunc, i); bubbleDown(this.heap, this.weightFunc, i); } return removed; } } return null; }; dsp.removeAll = function () { this.heap = []; }; dsp.size = function () { return this.heap.length; }; var toPromisify = [ 'beforeValidate', 'validate', 'afterValidate', 'beforeCreate', 'afterCreate', 'beforeUpdate', 'afterUpdate', 'beforeDestroy', 'afterDestroy' ]; // adapted from angular.copy function copy(source, destination, stackSource, stackDest) { if (!destination) { destination = source; if (source) { if (isArray(source)) { destination = copy(source, [], stackSource, stackDest); } else if (isDate(source)) { destination = new Date(source.getTime()); } else if (isRegExp(source)) { destination = new RegExp(source.source, source.toString().match(/[^\/]*$/)[0]); destination.lastIndex = source.lastIndex; } else if (isObject(source)) { var emptyObject = Object.create(Object.getPrototypeOf(source)); destination = copy(source, emptyObject, stackSource, stackDest); } } } else { if (source === destination) { throw new Error('Cannot copy! Source and destination are identical.'); } stackSource = stackSource || []; stackDest = stackDest || []; if (isObject(source)) { var index = stackSource.indexOf(source); if (index !== -1) return stackDest[index]; stackSource.push(source); stackDest.push(destination); } var result; if (isArray(source)) { destination.length = 0; for (var i = 0; i < source.length; i++) { result = copy(source[i], null, stackSource, stackDest); if (isObject(source[i])) { stackSource.push(source[i]); stackDest.push(result); } destination.push(result); } } else { if (isArray(destination)) { destination.length = 0; } else { forEach(destination, function (value, key) { delete destination[key]; }); } for (var key in source) { if (source.hasOwnProperty(key)) { result = copy(source[key], null, stackSource, stackDest); if (isObject(source[key])) { stackSource.push(source[key]); stackDest.push(result); } destination[key] = result; } } } } return destination; } // adapted from angular.equals function equals(o1, o2) { if (o1 === o2) return true; if (o1 === null || o2 === null) return false; if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN var t1 = typeof o1, t2 = typeof o2, length, key, keySet; if (t1 == t2) { if (t1 == 'object') { if (isArray(o1)) { if (!isArray(o2)) return false; if ((length = o1.length) == o2.length) { for (key = 0; key < length; key++) { if (!equals(o1[key], o2[key])) return false; } return true; } } else if (isDate(o1)) { if (!isDate(o2)) return false; return equals(o1.getTime(), o2.getTime()); } else if (isRegExp(o1) && isRegExp(o2)) { return o1.toString() == o2.toString(); } else { if (isArray(o2)) return false; keySet = {}; for (key in o1) { if (key.charAt(0) === '$' || isFunction(o1[key])) continue; if (!equals(o1[key], o2[key])) return false; keySet[key] = true; } for (key in o2) { if (!keySet.hasOwnProperty(key) && key.charAt(0) !== '$' && o2[key] !== undefined && !isFunction(o2[key])) return false; } return true; } } } return false; } function resolveId(definition, idOrInstance) { if (this.isString(idOrInstance) || isNumber(idOrInstance)) { return idOrInstance; } else if (idOrInstance && definition) { return idOrInstance[definition.idAttribute] || idOrInstance; } else { return idOrInstance; } } function resolveItem(resource, idOrInstance) { if (resource && (isString(idOrInstance) || isNumber(idOrInstance))) { return resource.index[idOrInstance] || idOrInstance; } else { return idOrInstance; } } function isValidString(val) { return (val != null && val !== ''); } function join(items, separator) { separator = separator || ''; return filter(items, isValidString).join(separator); } function makePath(var_args) { var result = join(slice(arguments), '/'); return result.replace(/([^:\/]|^)\/{2,}/g, '$1/'); } observe.setEqualityFn(equals); var DSUtils = { // Options that inherit from defaults _: function (parent, options) { var _this = this; options = options || {}; if (options && options.constructor === parent.constructor) { return options; } else if (!isObject(options)) { throw new DSErrors.IA('"options" must be an object!'); } forEach(toPromisify, function (name) { if (typeof options[name] === 'function' && options[name].toString().indexOf('var args = Array') === -1) { options[name] = _this.promisify(options[name]); } }); var O = function Options(attrs) { var self = this; forOwn(attrs, function (value, key) { self[key] = value; }); }; O.prototype = parent; return new O(options); }, compute: function (fn, field) { var _this = this; var args = []; forEach(fn.deps, function (dep) { args.push(_this[dep]); }); // compute property _this[field] = fn[fn.length - 1].apply(_this, args); }, contains: require('mout/array/contains'), copy: copy, deepMixIn: require('mout/object/deepMixIn'), diffObjectFromOldObject: observe.diffObjectFromOldObject, DSBinaryHeap: DSBinaryHeap, equals: equals, Events: Events, filter: filter, forEach: forEach, forOwn: forOwn, fromJson: function (json) { return isString(json) ? JSON.parse(json) : json; }, get: require('mout/object/get'), intersection: intersection, isArray: isArray, isBoolean: isBoolean, isDate: isDate, isEmpty: isEmpty, isFunction: isFunction, isObject: isObject, isNumber: isNumber, isRegExp: isRegExp, isString: isString, makePath: makePath, observe: observe, pascalCase: require('mout/string/pascalCase'), pick: require('mout/object/pick'), Promise: _Promise, promisify: function (fn, target) { var Promise = this.Promise; if (!fn) { return; } else if (typeof fn !== 'function') { throw new Error('Can only promisify functions!'); } return function () { var args = Array.prototype.slice.apply(arguments); return new Promise(function (resolve, reject) { args.push(function (err, result) { if (err) { reject(err); } else { resolve(result); } }); try { var promise = fn.apply(target || this, args); if (promise && promise.then) { promise.then(resolve, reject); } } catch (err) { reject(err); } }); }; }, remove: require('mout/array/remove'), set: require('mout/object/set'), slice: slice, sort: require('mout/array/sort'), toJson: JSON.stringify, updateTimestamp: updateTimestamp, upperCase: require('mout/string/upperCase'), removeCircular: function (object) { var objects = []; return (function rmCirc(value) { var i; var nu; if (typeof value === 'object' && value !== null && !(value instanceof Boolean) && !(value instanceof Date) && !(value instanceof Number) && !(value instanceof RegExp) && !(value instanceof String)) { for (i = 0; i < objects.length; i += 1) { if (objects[i] === value) { return undefined; } } objects.push(value); if (DSUtils.isArray(value)) { nu = []; for (i = 0; i < value.length; i += 1) { nu[i] = rmCirc(value[i]); } } else { nu = {}; forOwn(value, function (v, k) { nu[k] = rmCirc(value[k]); }); } return nu; } return value; }(object)); }, resolveItem: resolveItem, resolveId: resolveId, w: w }; module.exports = DSUtils; },{"../lib/observe-js/observe-js":1,"./errors":48,"bluebird":"bluebird","es6-promise":2,"mout/array/contains":4,"mout/array/forEach":5,"mout/array/remove":7,"mout/array/slice":8,"mout/array/sort":9,"mout/object/deepMixIn":13,"mout/object/forOwn":15,"mout/object/get":16,"mout/object/pick":19,"mout/object/set":20,"mout/string/pascalCase":23,"mout/string/upperCase":26}]},{},[49])(49) });
fields/types/geopoint/GeoPointField.js
lastjune/keystone
import Field from '../Field'; import React from 'react'; import { FormRow, FormField, FormInput } from 'elemental'; module.exports = Field.create({ displayName: 'GeopointField', focusTargetRef: 'lat', valueChanged (which, event) { this.props.value[which] = event.target.value; this.props.onChange({ path: this.props.path, value: this.props.value }); }, renderValue () { if (this.props.value[1] && this.props.value[0]) { return <FormInput noedit>{this.props.value[1]}, {this.props.value[0]}</FormInput>;//eslint-disable-line comma-spacing } return <FormInput noedit>(not set)</FormInput>; }, renderField () { return ( <FormRow> <FormField width="one-half"> <FormInput name={this.props.path + '[1]'} placeholder="Latitude" ref="lat" value={this.props.value[1]} onChange={this.valueChanged.bind(this, 1)} autoComplete="off" /> </FormField> <FormField width="one-half"> <FormInput name={this.props.path + '[0]'} placeholder="Longitude" ref="lng" value={this.props.value[0]} onChange={this.valueChanged.bind(this, 0)} autoComplete="off" /> </FormField> </FormRow> ); } });
src/svg-icons/notification/power.js
frnk94/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationPower = (props) => ( <SvgIcon {...props}> <path d="M16.01 7L16 3h-2v4h-4V3H8v4h-.01C7 6.99 6 7.99 6 8.99v5.49L9.5 18v3h5v-3l3.5-3.51v-5.5c0-1-1-2-1.99-1.99z"/> </SvgIcon> ); NotificationPower = pure(NotificationPower); NotificationPower.displayName = 'NotificationPower'; NotificationPower.muiName = 'SvgIcon'; export default NotificationPower;
app/containers/chat/ChatPage.js
MichaelMure/Arbore
// @flow import { connect } from 'react-redux' import type { Store } from 'utils/types' import ChatPage from 'components/chat/ChatPage' import * as ui from 'actions/ui' import { Page } from 'models/UiState' const mapStateToProps = (state: Store) => ({ contacts: state.contactList, }) const mapDispatchToProps = dispatch => ({ onGoToContactClick: () => { dispatch(ui.setPage(Page.CONTACT)) } }) export default connect(mapStateToProps, mapDispatchToProps)(ChatPage)
src/browser/auth/SignInError.js
skallet/este
// @flow import type { State } from '../../common/types'; import React from 'react'; import errorMessages from '../../common/auth/errorMessages'; import { FormattedMessage } from 'react-intl'; import { connect } from 'react-redux'; import { firebaseMessages } from '../../common/lib/redux-firebase'; import { Message, } from '../app/components'; const getMessage = error => errorMessages[error.name] || firebaseMessages[error.name] || error.toString(); const SignInError = ({ error }) => { if (!error) return null; const message = getMessage(error); return ( <Message danger> {typeof message !== 'string' ? <FormattedMessage {...message} values={error.params} /> : error.toString() } </Message> ); }; export default connect( (state: State) => ({ error: state.auth.error, }), )(SignInError);
StatelessForm.js
kristian-puccio/react-native-stateless-form
import React from 'react'; import { Platform, Component, PropTypes, ScrollView, View, StyleSheet, } from 'react-native'; let styles; export default class StatelessForm extends Component { componentDidMount() { this.willFocusInput = false; } childrenWithProps() { let nextInput = null; let inputCount = 0; return React.Children .map(this.props.children, (child) => child).reverse().map((child) => { if (typeof child.props.value !== 'undefined') { inputCount++; const input = React.cloneElement(child, { nextInput, ref: `input${inputCount}`, onNextInputFocus: this.handleNextInputFocus, postFocus: this.handleFocus, postBlur: this.handleBlur, }); nextInput = input; return input; } return child; }) .reverse(); } handleNextInputFocus = (nextInput, currentInput) => { if (nextInput) { const input = this.refs[nextInput.ref]; this.willFocusInput = true; input.focus(); } else { currentInput.blur(); } }; handleBlur = () => { if (!this.willFocusInput) { this.refs.scrollView.scrollTo({ y: 0 }); } this.willFocusInput = false; }; handleFocus = (scrollTo) => { this.willFocusInput = false; this.refs.scrollView.scrollTo({ y: scrollTo }); }; render() { return ( <ScrollView keyboardShouldPersistTaps={ false } { ...this.props } ref="scrollView" style={ [styles.container, this.props.style] } > { this.childrenWithProps() } { Platform.OS === 'android' && <View style={ styles.androidSpacer } /> } </ScrollView> ); } } StatelessForm.propTypes = { children: PropTypes.node, style: PropTypes.oneOfType([ React.PropTypes.number, React.PropTypes.object, React.PropTypes.arrayOf(React.PropTypes.object), ]), }; StatelessForm.defaultProps = { style: {}, }; styles = StyleSheet.create({ // eslint-disable-line container: { flex: 1, alignSelf: 'stretch', }, androidSpacer: { height: 500, }, });
docs/docsite/_static/jquery.js
gptech/ansible
/*! * jQuery JavaScript Library v1.4.2 * 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: Sat Feb 13 22:33:48 2010 -0500 */ (function(A,w){function ma(){if(!c.isReady){try{s.documentElement.doScroll("left")}catch(a){setTimeout(ma,1);return}c.ready()}}function Qa(a,b){b.src?c.ajax({url:b.src,async:false,dataType:"script"}):c.globalEval(b.text||b.textContent||b.innerHTML||"");b.parentNode&&b.parentNode.removeChild(b)}function X(a,b,d,f,e,j){var i=a.length;if(typeof b==="object"){for(var o in b)X(a,o,b[o],f,e,d);return a}if(d!==w){f=!j&&f&&c.isFunction(d);for(o=0;o<i;o++)e(a[o],b,f?d.call(a[o],o,e(a[o],b)):d,j);return a}return i? e(a[0],b):w}function J(){return(new Date).getTime()}function Y(){return false}function Z(){return true}function na(a,b,d){d[0].type=a;return c.event.handle.apply(b,d)}function oa(a){var b,d=[],f=[],e=arguments,j,i,o,k,n,r;i=c.data(this,"events");if(!(a.liveFired===this||!i||!i.live||a.button&&a.type==="click")){a.liveFired=this;var u=i.live.slice(0);for(k=0;k<u.length;k++){i=u[k];i.origType.replace(O,"")===a.type?f.push(i.selector):u.splice(k--,1)}j=c(a.target).closest(f,a.currentTarget);n=0;for(r= j.length;n<r;n++)for(k=0;k<u.length;k++){i=u[k];if(j[n].selector===i.selector){o=j[n].elem;f=null;if(i.preType==="mouseenter"||i.preType==="mouseleave")f=c(a.relatedTarget).closest(i.selector)[0];if(!f||f!==o)d.push({elem:o,handleObj:i})}}n=0;for(r=d.length;n<r;n++){j=d[n];a.currentTarget=j.elem;a.data=j.handleObj.data;a.handleObj=j.handleObj;if(j.handleObj.origHandler.apply(j.elem,e)===false){b=false;break}}return b}}function pa(a,b){return"live."+(a&&a!=="*"?a+".":"")+b.replace(/\./g,"`").replace(/ /g, "&")}function qa(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function ra(a,b){var d=0;b.each(function(){if(this.nodeName===(a[d]&&a[d].nodeName)){var f=c.data(a[d++]),e=c.data(this,f);if(f=f&&f.events){delete e.handle;e.events={};for(var j in f)for(var i in f[j])c.event.add(this,j,f[j][i],f[j][i].data)}}})}function sa(a,b,d){var f,e,j;b=b&&b[0]?b[0].ownerDocument||b[0]:s;if(a.length===1&&typeof a[0]==="string"&&a[0].length<512&&b===s&&!ta.test(a[0])&&(c.support.checkClone||!ua.test(a[0]))){e= true;if(j=c.fragments[a[0]])if(j!==1)f=j}if(!f){f=b.createDocumentFragment();c.clean(a,b,f,d)}if(e)c.fragments[a[0]]=j?f:1;return{fragment:f,cacheable:e}}function K(a,b){var d={};c.each(va.concat.apply([],va.slice(0,b)),function(){d[this]=a});return d}function wa(a){return"scrollTo"in a&&a.document?a:a.nodeType===9?a.defaultView||a.parentWindow:false}var c=function(a,b){return new c.fn.init(a,b)},Ra=A.jQuery,Sa=A.$,s=A.document,T,Ta=/^[^<]*(<[\w\W]+>)[^>]*$|^#([\w-]+)$/,Ua=/^.[^:#\[\.,]*$/,Va=/\S/, Wa=/^(\s|\u00A0)+|(\s|\u00A0)+$/g,Xa=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,P=navigator.userAgent,xa=false,Q=[],L,$=Object.prototype.toString,aa=Object.prototype.hasOwnProperty,ba=Array.prototype.push,R=Array.prototype.slice,ya=Array.prototype.indexOf;c.fn=c.prototype={init:function(a,b){var d,f;if(!a)return this;if(a.nodeType){this.context=this[0]=a;this.length=1;return this}if(a==="body"&&!b){this.context=s;this[0]=s.body;this.selector="body";this.length=1;return this}if(typeof a==="string")if((d=Ta.exec(a))&& (d[1]||!b))if(d[1]){f=b?b.ownerDocument||b:s;if(a=Xa.exec(a))if(c.isPlainObject(b)){a=[s.createElement(a[1])];c.fn.attr.call(a,b,true)}else a=[f.createElement(a[1])];else{a=sa([d[1]],[f]);a=(a.cacheable?a.fragment.cloneNode(true):a.fragment).childNodes}return c.merge(this,a)}else{if(b=s.getElementById(d[2])){if(b.id!==d[2])return T.find(a);this.length=1;this[0]=b}this.context=s;this.selector=a;return this}else if(!b&&/^\w+$/.test(a)){this.selector=a;this.context=s;a=s.getElementsByTagName(a);return c.merge(this, a)}else return!b||b.jquery?(b||T).find(a):c(b).find(a);else if(c.isFunction(a))return T.ready(a);if(a.selector!==w){this.selector=a.selector;this.context=a.context}return c.makeArray(a,this)},selector:"",jquery:"1.4.2",length:0,size:function(){return this.length},toArray:function(){return R.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this.slice(a)[0]:this[a]},pushStack:function(a,b,d){var f=c();c.isArray(a)?ba.apply(f,a):c.merge(f,a);f.prevObject=this;f.context=this.context;if(b=== "find")f.selector=this.selector+(this.selector?" ":"")+d;else if(b)f.selector=this.selector+"."+b+"("+d+")";return f},each:function(a,b){return c.each(this,a,b)},ready:function(a){c.bindReady();if(c.isReady)a.call(s,c);else Q&&Q.push(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(R.apply(this,arguments),"slice",R.call(arguments).join(","))},map:function(a){return this.pushStack(c.map(this, function(b,d){return a.call(b,d,b)}))},end:function(){return this.prevObject||c(null)},push:ba,sort:[].sort,splice:[].splice};c.fn.init.prototype=c.fn;c.extend=c.fn.extend=function(){var a=arguments[0]||{},b=1,d=arguments.length,f=false,e,j,i,o;if(typeof a==="boolean"){f=a;a=arguments[1]||{};b=2}if(typeof a!=="object"&&!c.isFunction(a))a={};if(d===b){a=this;--b}for(;b<d;b++)if((e=arguments[b])!=null)for(j in e){i=a[j];o=e[j];if(a!==o)if(f&&o&&(c.isPlainObject(o)||c.isArray(o))){i=i&&(c.isPlainObject(i)|| c.isArray(i))?i:c.isArray(o)?[]:{};a[j]=c.extend(f,i,o)}else if(o!==w)a[j]=o}return a};c.extend({noConflict:function(a){A.$=Sa;if(a)A.jQuery=Ra;return c},isReady:false,ready:function(){if(!c.isReady){if(!s.body)return setTimeout(c.ready,13);c.isReady=true;if(Q){for(var a,b=0;a=Q[b++];)a.call(s,c);Q=null}c.fn.triggerHandler&&c(s).triggerHandler("ready")}},bindReady:function(){if(!xa){xa=true;if(s.readyState==="complete")return c.ready();if(s.addEventListener){s.addEventListener("DOMContentLoaded", L,false);A.addEventListener("load",c.ready,false)}else if(s.attachEvent){s.attachEvent("onreadystatechange",L);A.attachEvent("onload",c.ready);var a=false;try{a=A.frameElement==null}catch(b){}s.documentElement.doScroll&&a&&ma()}}},isFunction:function(a){return $.call(a)==="[object Function]"},isArray:function(a){return $.call(a)==="[object Array]"},isPlainObject:function(a){if(!a||$.call(a)!=="[object Object]"||a.nodeType||a.setInterval)return false;if(a.constructor&&!aa.call(a,"constructor")&&!aa.call(a.constructor.prototype, "isPrototypeOf"))return false;var b;for(b in a);return b===w||aa.call(a,b)},isEmptyObject:function(a){for(var b in a)return false;return true},error:function(a){throw a;},parseJSON:function(a){if(typeof a!=="string"||!a)return null;a=c.trim(a);if(/^[\],:{}\s]*$/.test(a.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,"")))return A.JSON&&A.JSON.parse?A.JSON.parse(a):(new Function("return "+ a))();else c.error("Invalid JSON: "+a)},noop:function(){},globalEval:function(a){if(a&&Va.test(a)){var b=s.getElementsByTagName("head")[0]||s.documentElement,d=s.createElement("script");d.type="text/javascript";if(c.support.scriptEval)d.appendChild(s.createTextNode(a));else d.text=a;b.insertBefore(d,b.firstChild);b.removeChild(d)}},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,b,d){var f,e=0,j=a.length,i=j===w||c.isFunction(a);if(d)if(i)for(f in a){if(b.apply(a[f], d)===false)break}else for(;e<j;){if(b.apply(a[e++],d)===false)break}else if(i)for(f in a){if(b.call(a[f],f,a[f])===false)break}else for(d=a[0];e<j&&b.call(d,e,d)!==false;d=a[++e]);return a},trim:function(a){return(a||"").replace(Wa,"")},makeArray:function(a,b){b=b||[];if(a!=null)a.length==null||typeof a==="string"||c.isFunction(a)||typeof a!=="function"&&a.setInterval?ba.call(b,a):c.merge(b,a);return b},inArray:function(a,b){if(b.indexOf)return b.indexOf(a);for(var d=0,f=b.length;d<f;d++)if(b[d]=== a)return d;return-1},merge:function(a,b){var d=a.length,f=0;if(typeof b.length==="number")for(var e=b.length;f<e;f++)a[d++]=b[f];else for(;b[f]!==w;)a[d++]=b[f++];a.length=d;return a},grep:function(a,b,d){for(var f=[],e=0,j=a.length;e<j;e++)!d!==!b(a[e],e)&&f.push(a[e]);return f},map:function(a,b,d){for(var f=[],e,j=0,i=a.length;j<i;j++){e=b(a[j],j,d);if(e!=null)f[f.length]=e}return f.concat.apply([],f)},guid:1,proxy:function(a,b,d){if(arguments.length===2)if(typeof b==="string"){d=a;a=d[b];b=w}else if(b&& !c.isFunction(b)){d=b;b=w}if(!b&&a)b=function(){return a.apply(d||this,arguments)};if(a)b.guid=a.guid=a.guid||b.guid||c.guid++;return b},uaMatch:function(a){a=a.toLowerCase();a=/(webkit)[ \/]([\w.]+)/.exec(a)||/(opera)(?:.*version)?[ \/]([\w.]+)/.exec(a)||/(msie) ([\w.]+)/.exec(a)||!/compatible/.test(a)&&/(mozilla)(?:.*? rv:([\w.]+))?/.exec(a)||[];return{browser:a[1]||"",version:a[2]||"0"}},browser:{}});P=c.uaMatch(P);if(P.browser){c.browser[P.browser]=true;c.browser.version=P.version}if(c.browser.webkit)c.browser.safari= true;if(ya)c.inArray=function(a,b){return ya.call(b,a)};T=c(s);if(s.addEventListener)L=function(){s.removeEventListener("DOMContentLoaded",L,false);c.ready()};else if(s.attachEvent)L=function(){if(s.readyState==="complete"){s.detachEvent("onreadystatechange",L);c.ready()}};(function(){c.support={};var a=s.documentElement,b=s.createElement("script"),d=s.createElement("div"),f="script"+J();d.style.display="none";d.innerHTML=" <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>"; var e=d.getElementsByTagName("*"),j=d.getElementsByTagName("a")[0];if(!(!e||!e.length||!j)){c.support={leadingWhitespace:d.firstChild.nodeType===3,tbody:!d.getElementsByTagName("tbody").length,htmlSerialize:!!d.getElementsByTagName("link").length,style:/red/.test(j.getAttribute("style")),hrefNormalized:j.getAttribute("href")==="/a",opacity:/^0.55$/.test(j.style.opacity),cssFloat:!!j.style.cssFloat,checkOn:d.getElementsByTagName("input")[0].value==="on",optSelected:s.createElement("select").appendChild(s.createElement("option")).selected, parentNode:d.removeChild(d.appendChild(s.createElement("div"))).parentNode===null,deleteExpando:true,checkClone:false,scriptEval:false,noCloneEvent:true,boxModel:null};b.type="text/javascript";try{b.appendChild(s.createTextNode("window."+f+"=1;"))}catch(i){}a.insertBefore(b,a.firstChild);if(A[f]){c.support.scriptEval=true;delete A[f]}try{delete b.test}catch(o){c.support.deleteExpando=false}a.removeChild(b);if(d.attachEvent&&d.fireEvent){d.attachEvent("onclick",function k(){c.support.noCloneEvent= false;d.detachEvent("onclick",k)});d.cloneNode(true).fireEvent("onclick")}d=s.createElement("div");d.innerHTML="<input type='radio' name='radiotest' checked='checked'/>";a=s.createDocumentFragment();a.appendChild(d.firstChild);c.support.checkClone=a.cloneNode(true).cloneNode(true).lastChild.checked;c(function(){var k=s.createElement("div");k.style.width=k.style.paddingLeft="1px";s.body.appendChild(k);c.boxModel=c.support.boxModel=k.offsetWidth===2;s.body.removeChild(k).style.display="none"});a=function(k){var n= s.createElement("div");k="on"+k;var r=k in n;if(!r){n.setAttribute(k,"return;");r=typeof n[k]==="function"}return r};c.support.submitBubbles=a("submit");c.support.changeBubbles=a("change");a=b=d=e=j=null}})();c.props={"for":"htmlFor","class":"className",readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",colspan:"colSpan",tabindex:"tabIndex",usemap:"useMap",frameborder:"frameBorder"};var G="jQuery"+J(),Ya=0,za={};c.extend({cache:{},expando:G,noData:{embed:true,object:true, applet:true},data:function(a,b,d){if(!(a.nodeName&&c.noData[a.nodeName.toLowerCase()])){a=a==A?za:a;var f=a[G],e=c.cache;if(!f&&typeof b==="string"&&d===w)return null;f||(f=++Ya);if(typeof b==="object"){a[G]=f;e[f]=c.extend(true,{},b)}else if(!e[f]){a[G]=f;e[f]={}}a=e[f];if(d!==w)a[b]=d;return typeof b==="string"?a[b]:a}},removeData:function(a,b){if(!(a.nodeName&&c.noData[a.nodeName.toLowerCase()])){a=a==A?za:a;var d=a[G],f=c.cache,e=f[d];if(b){if(e){delete e[b];c.isEmptyObject(e)&&c.removeData(a)}}else{if(c.support.deleteExpando)delete a[c.expando]; else a.removeAttribute&&a.removeAttribute(c.expando);delete f[d]}}}});c.fn.extend({data:function(a,b){if(typeof a==="undefined"&&this.length)return c.data(this[0]);else if(typeof a==="object")return this.each(function(){c.data(this,a)});var d=a.split(".");d[1]=d[1]?"."+d[1]:"";if(b===w){var f=this.triggerHandler("getData"+d[1]+"!",[d[0]]);if(f===w&&this.length)f=c.data(this[0],a);return f===w&&d[1]?this.data(d[0]):f}else return this.trigger("setData"+d[1]+"!",[d[0],b]).each(function(){c.data(this, a,b)})},removeData:function(a){return this.each(function(){c.removeData(this,a)})}});c.extend({queue:function(a,b,d){if(a){b=(b||"fx")+"queue";var f=c.data(a,b);if(!d)return f||[];if(!f||c.isArray(d))f=c.data(a,b,c.makeArray(d));else f.push(d);return f}},dequeue:function(a,b){b=b||"fx";var d=c.queue(a,b),f=d.shift();if(f==="inprogress")f=d.shift();if(f){b==="fx"&&d.unshift("inprogress");f.call(a,function(){c.dequeue(a,b)})}}});c.fn.extend({queue:function(a,b){if(typeof a!=="string"){b=a;a="fx"}if(b=== w)return c.queue(this[0],a);return this.each(function(){var d=c.queue(this,a,b);a==="fx"&&d[0]!=="inprogress"&&c.dequeue(this,a)})},dequeue:function(a){return this.each(function(){c.dequeue(this,a)})},delay:function(a,b){a=c.fx?c.fx.speeds[a]||a:a;b=b||"fx";return this.queue(b,function(){var d=this;setTimeout(function(){c.dequeue(d,b)},a)})},clearQueue:function(a){return this.queue(a||"fx",[])}});var Aa=/[\n\t]/g,ca=/\s+/,Za=/\r/g,$a=/href|src|style/,ab=/(button|input)/i,bb=/(button|input|object|select|textarea)/i, cb=/^(a|area)$/i,Ba=/radio|checkbox/;c.fn.extend({attr:function(a,b){return X(this,a,b,true,c.attr)},removeAttr:function(a){return this.each(function(){c.attr(this,a,"");this.nodeType===1&&this.removeAttribute(a)})},addClass:function(a){if(c.isFunction(a))return this.each(function(n){var r=c(this);r.addClass(a.call(this,n,r.attr("class")))});if(a&&typeof a==="string")for(var b=(a||"").split(ca),d=0,f=this.length;d<f;d++){var e=this[d];if(e.nodeType===1)if(e.className){for(var j=" "+e.className+" ", i=e.className,o=0,k=b.length;o<k;o++)if(j.indexOf(" "+b[o]+" ")<0)i+=" "+b[o];e.className=c.trim(i)}else e.className=a}return this},removeClass:function(a){if(c.isFunction(a))return this.each(function(k){var n=c(this);n.removeClass(a.call(this,k,n.attr("class")))});if(a&&typeof a==="string"||a===w)for(var b=(a||"").split(ca),d=0,f=this.length;d<f;d++){var e=this[d];if(e.nodeType===1&&e.className)if(a){for(var j=(" "+e.className+" ").replace(Aa," "),i=0,o=b.length;i<o;i++)j=j.replace(" "+b[i]+" ", " ");e.className=c.trim(j)}else e.className=""}return this},toggleClass:function(a,b){var d=typeof a,f=typeof b==="boolean";if(c.isFunction(a))return this.each(function(e){var j=c(this);j.toggleClass(a.call(this,e,j.attr("class"),b),b)});return this.each(function(){if(d==="string")for(var e,j=0,i=c(this),o=b,k=a.split(ca);e=k[j++];){o=f?o:!i.hasClass(e);i[o?"addClass":"removeClass"](e)}else if(d==="undefined"||d==="boolean"){this.className&&c.data(this,"__className__",this.className);this.className= this.className||a===false?"":c.data(this,"__className__")||""}})},hasClass:function(a){a=" "+a+" ";for(var b=0,d=this.length;b<d;b++)if((" "+this[b].className+" ").replace(Aa," ").indexOf(a)>-1)return true;return false},val:function(a){if(a===w){var b=this[0];if(b){if(c.nodeName(b,"option"))return(b.attributes.value||{}).specified?b.value:b.text;if(c.nodeName(b,"select")){var d=b.selectedIndex,f=[],e=b.options;b=b.type==="select-one";if(d<0)return null;var j=b?d:0;for(d=b?d+1:e.length;j<d;j++){var i= e[j];if(i.selected){a=c(i).val();if(b)return a;f.push(a)}}return f}if(Ba.test(b.type)&&!c.support.checkOn)return b.getAttribute("value")===null?"on":b.value;return(b.value||"").replace(Za,"")}return w}var o=c.isFunction(a);return this.each(function(k){var n=c(this),r=a;if(this.nodeType===1){if(o)r=a.call(this,k,n.val());if(typeof r==="number")r+="";if(c.isArray(r)&&Ba.test(this.type))this.checked=c.inArray(n.val(),r)>=0;else if(c.nodeName(this,"select")){var u=c.makeArray(r);c("option",this).each(function(){this.selected= c.inArray(c(this).val(),u)>=0});if(!u.length)this.selectedIndex=-1}else this.value=r}})}});c.extend({attrFn:{val:true,css:true,html:true,text:true,data:true,width:true,height:true,offset:true},attr:function(a,b,d,f){if(!a||a.nodeType===3||a.nodeType===8)return w;if(f&&b in c.attrFn)return c(a)[b](d);f=a.nodeType!==1||!c.isXMLDoc(a);var e=d!==w;b=f&&c.props[b]||b;if(a.nodeType===1){var j=$a.test(b);if(b in a&&f&&!j){if(e){b==="type"&&ab.test(a.nodeName)&&a.parentNode&&c.error("type property can't be changed"); a[b]=d}if(c.nodeName(a,"form")&&a.getAttributeNode(b))return a.getAttributeNode(b).nodeValue;if(b==="tabIndex")return(b=a.getAttributeNode("tabIndex"))&&b.specified?b.value:bb.test(a.nodeName)||cb.test(a.nodeName)&&a.href?0:w;return a[b]}if(!c.support.style&&f&&b==="style"){if(e)a.style.cssText=""+d;return a.style.cssText}e&&a.setAttribute(b,""+d);a=!c.support.hrefNormalized&&f&&j?a.getAttribute(b,2):a.getAttribute(b);return a===null?w:a}return c.style(a,b,d)}});var O=/\.(.*)$/,db=function(a){return a.replace(/[^\w\s\.\|`]/g, function(b){return"\\"+b})};c.event={add:function(a,b,d,f){if(!(a.nodeType===3||a.nodeType===8)){if(a.setInterval&&a!==A&&!a.frameElement)a=A;var e,j;if(d.handler){e=d;d=e.handler}if(!d.guid)d.guid=c.guid++;if(j=c.data(a)){var i=j.events=j.events||{},o=j.handle;if(!o)j.handle=o=function(){return typeof c!=="undefined"&&!c.event.triggered?c.event.handle.apply(o.elem,arguments):w};o.elem=a;b=b.split(" ");for(var k,n=0,r;k=b[n++];){j=e?c.extend({},e):{handler:d,data:f};if(k.indexOf(".")>-1){r=k.split("."); k=r.shift();j.namespace=r.slice(0).sort().join(".")}else{r=[];j.namespace=""}j.type=k;j.guid=d.guid;var u=i[k],z=c.event.special[k]||{};if(!u){u=i[k]=[];if(!z.setup||z.setup.call(a,f,r,o)===false)if(a.addEventListener)a.addEventListener(k,o,false);else a.attachEvent&&a.attachEvent("on"+k,o)}if(z.add){z.add.call(a,j);if(!j.handler.guid)j.handler.guid=d.guid}u.push(j);c.event.global[k]=true}a=null}}},global:{},remove:function(a,b,d,f){if(!(a.nodeType===3||a.nodeType===8)){var e,j=0,i,o,k,n,r,u,z=c.data(a), C=z&&z.events;if(z&&C){if(b&&b.type){d=b.handler;b=b.type}if(!b||typeof b==="string"&&b.charAt(0)==="."){b=b||"";for(e in C)c.event.remove(a,e+b)}else{for(b=b.split(" ");e=b[j++];){n=e;i=e.indexOf(".")<0;o=[];if(!i){o=e.split(".");e=o.shift();k=new RegExp("(^|\\.)"+c.map(o.slice(0).sort(),db).join("\\.(?:.*\\.)?")+"(\\.|$)")}if(r=C[e])if(d){n=c.event.special[e]||{};for(B=f||0;B<r.length;B++){u=r[B];if(d.guid===u.guid){if(i||k.test(u.namespace)){f==null&&r.splice(B--,1);n.remove&&n.remove.call(a,u)}if(f!= null)break}}if(r.length===0||f!=null&&r.length===1){if(!n.teardown||n.teardown.call(a,o)===false)Ca(a,e,z.handle);delete C[e]}}else for(var B=0;B<r.length;B++){u=r[B];if(i||k.test(u.namespace)){c.event.remove(a,n,u.handler,B);r.splice(B--,1)}}}if(c.isEmptyObject(C)){if(b=z.handle)b.elem=null;delete z.events;delete z.handle;c.isEmptyObject(z)&&c.removeData(a)}}}}},trigger:function(a,b,d,f){var e=a.type||a;if(!f){a=typeof a==="object"?a[G]?a:c.extend(c.Event(e),a):c.Event(e);if(e.indexOf("!")>=0){a.type= e=e.slice(0,-1);a.exclusive=true}if(!d){a.stopPropagation();c.event.global[e]&&c.each(c.cache,function(){this.events&&this.events[e]&&c.event.trigger(a,b,this.handle.elem)})}if(!d||d.nodeType===3||d.nodeType===8)return w;a.result=w;a.target=d;b=c.makeArray(b);b.unshift(a)}a.currentTarget=d;(f=c.data(d,"handle"))&&f.apply(d,b);f=d.parentNode||d.ownerDocument;try{if(!(d&&d.nodeName&&c.noData[d.nodeName.toLowerCase()]))if(d["on"+e]&&d["on"+e].apply(d,b)===false)a.result=false}catch(j){}if(!a.isPropagationStopped()&& f)c.event.trigger(a,b,f,true);else if(!a.isDefaultPrevented()){f=a.target;var i,o=c.nodeName(f,"a")&&e==="click",k=c.event.special[e]||{};if((!k._default||k._default.call(d,a)===false)&&!o&&!(f&&f.nodeName&&c.noData[f.nodeName.toLowerCase()])){try{if(f[e]){if(i=f["on"+e])f["on"+e]=null;c.event.triggered=true;f[e]()}}catch(n){}if(i)f["on"+e]=i;c.event.triggered=false}}},handle:function(a){var b,d,f,e;a=arguments[0]=c.event.fix(a||A.event);a.currentTarget=this;b=a.type.indexOf(".")<0&&!a.exclusive; if(!b){d=a.type.split(".");a.type=d.shift();f=new RegExp("(^|\\.)"+d.slice(0).sort().join("\\.(?:.*\\.)?")+"(\\.|$)")}e=c.data(this,"events");d=e[a.type];if(e&&d){d=d.slice(0);e=0;for(var j=d.length;e<j;e++){var i=d[e];if(b||f.test(i.namespace)){a.handler=i.handler;a.data=i.data;a.handleObj=i;i=i.handler.apply(this,arguments);if(i!==w){a.result=i;if(i===false){a.preventDefault();a.stopPropagation()}}if(a.isImmediatePropagationStopped())break}}}return a.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 originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "), fix:function(a){if(a[G])return a;var b=a;a=c.Event(b);for(var d=this.props.length,f;d;){f=this.props[--d];a[f]=b[f]}if(!a.target)a.target=a.srcElement||s;if(a.target.nodeType===3)a.target=a.target.parentNode;if(!a.relatedTarget&&a.fromElement)a.relatedTarget=a.fromElement===a.target?a.toElement:a.fromElement;if(a.pageX==null&&a.clientX!=null){b=s.documentElement;d=s.body;a.pageX=a.clientX+(b&&b.scrollLeft||d&&d.scrollLeft||0)-(b&&b.clientLeft||d&&d.clientLeft||0);a.pageY=a.clientY+(b&&b.scrollTop|| d&&d.scrollTop||0)-(b&&b.clientTop||d&&d.clientTop||0)}if(!a.which&&(a.charCode||a.charCode===0?a.charCode:a.keyCode))a.which=a.charCode||a.keyCode;if(!a.metaKey&&a.ctrlKey)a.metaKey=a.ctrlKey;if(!a.which&&a.button!==w)a.which=a.button&1?1:a.button&2?3:a.button&4?2:0;return a},guid:1E8,proxy:c.proxy,special:{ready:{setup:c.bindReady,teardown:c.noop},live:{add:function(a){c.event.add(this,a.origType,c.extend({},a,{handler:oa}))},remove:function(a){var b=true,d=a.origType.replace(O,"");c.each(c.data(this, "events").live||[],function(){if(d===this.origType.replace(O,""))return b=false});b&&c.event.remove(this,a.origType,oa)}},beforeunload:{setup:function(a,b,d){if(this.setInterval)this.onbeforeunload=d;return false},teardown:function(a,b){if(this.onbeforeunload===b)this.onbeforeunload=null}}}};var Ca=s.removeEventListener?function(a,b,d){a.removeEventListener(b,d,false)}:function(a,b,d){a.detachEvent("on"+b,d)};c.Event=function(a){if(!this.preventDefault)return new c.Event(a);if(a&&a.type){this.originalEvent= a;this.type=a.type}else this.type=a;this.timeStamp=J();this[G]=true};c.Event.prototype={preventDefault:function(){this.isDefaultPrevented=Z;var a=this.originalEvent;if(a){a.preventDefault&&a.preventDefault();a.returnValue=false}},stopPropagation:function(){this.isPropagationStopped=Z;var a=this.originalEvent;if(a){a.stopPropagation&&a.stopPropagation();a.cancelBubble=true}},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=Z;this.stopPropagation()},isDefaultPrevented:Y,isPropagationStopped:Y, isImmediatePropagationStopped:Y};var Da=function(a){var b=a.relatedTarget;try{for(;b&&b!==this;)b=b.parentNode;if(b!==this){a.type=a.data;c.event.handle.apply(this,arguments)}}catch(d){}},Ea=function(a){a.type=a.data;c.event.handle.apply(this,arguments)};c.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){c.event.special[a]={setup:function(d){c.event.add(this,b,d&&d.selector?Ea:Da,a)},teardown:function(d){c.event.remove(this,b,d&&d.selector?Ea:Da)}}});if(!c.support.submitBubbles)c.event.special.submit= {setup:function(){if(this.nodeName.toLowerCase()!=="form"){c.event.add(this,"click.specialSubmit",function(a){var b=a.target,d=b.type;if((d==="submit"||d==="image")&&c(b).closest("form").length)return na("submit",this,arguments)});c.event.add(this,"keypress.specialSubmit",function(a){var b=a.target,d=b.type;if((d==="text"||d==="password")&&c(b).closest("form").length&&a.keyCode===13)return na("submit",this,arguments)})}else return false},teardown:function(){c.event.remove(this,".specialSubmit")}}; if(!c.support.changeBubbles){var da=/textarea|input|select/i,ea,Fa=function(a){var b=a.type,d=a.value;if(b==="radio"||b==="checkbox")d=a.checked;else if(b==="select-multiple")d=a.selectedIndex>-1?c.map(a.options,function(f){return f.selected}).join("-"):"";else if(a.nodeName.toLowerCase()==="select")d=a.selectedIndex;return d},fa=function(a,b){var d=a.target,f,e;if(!(!da.test(d.nodeName)||d.readOnly)){f=c.data(d,"_change_data");e=Fa(d);if(a.type!=="focusout"||d.type!=="radio")c.data(d,"_change_data", e);if(!(f===w||e===f))if(f!=null||e){a.type="change";return c.event.trigger(a,b,d)}}};c.event.special.change={filters:{focusout:fa,click:function(a){var b=a.target,d=b.type;if(d==="radio"||d==="checkbox"||b.nodeName.toLowerCase()==="select")return fa.call(this,a)},keydown:function(a){var b=a.target,d=b.type;if(a.keyCode===13&&b.nodeName.toLowerCase()!=="textarea"||a.keyCode===32&&(d==="checkbox"||d==="radio")||d==="select-multiple")return fa.call(this,a)},beforeactivate:function(a){a=a.target;c.data(a, "_change_data",Fa(a))}},setup:function(){if(this.type==="file")return false;for(var a in ea)c.event.add(this,a+".specialChange",ea[a]);return da.test(this.nodeName)},teardown:function(){c.event.remove(this,".specialChange");return da.test(this.nodeName)}};ea=c.event.special.change.filters}s.addEventListener&&c.each({focus:"focusin",blur:"focusout"},function(a,b){function d(f){f=c.event.fix(f);f.type=b;return c.event.handle.call(this,f)}c.event.special[b]={setup:function(){this.addEventListener(a, d,true)},teardown:function(){this.removeEventListener(a,d,true)}}});c.each(["bind","one"],function(a,b){c.fn[b]=function(d,f,e){if(typeof d==="object"){for(var j in d)this[b](j,f,d[j],e);return this}if(c.isFunction(f)){e=f;f=w}var i=b==="one"?c.proxy(e,function(k){c(this).unbind(k,i);return e.apply(this,arguments)}):e;if(d==="unload"&&b!=="one")this.one(d,f,e);else{j=0;for(var o=this.length;j<o;j++)c.event.add(this[j],d,i,f)}return this}});c.fn.extend({unbind:function(a,b){if(typeof a==="object"&& !a.preventDefault)for(var d in a)this.unbind(d,a[d]);else{d=0;for(var f=this.length;d<f;d++)c.event.remove(this[d],a,b)}return this},delegate:function(a,b,d,f){return this.live(b,d,f,a)},undelegate:function(a,b,d){return arguments.length===0?this.unbind("live"):this.die(b,null,d,a)},trigger:function(a,b){return this.each(function(){c.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0]){a=c.Event(a);a.preventDefault();a.stopPropagation();c.event.trigger(a,b,this[0]);return a.result}}, toggle:function(a){for(var b=arguments,d=1;d<b.length;)c.proxy(a,b[d++]);return this.click(c.proxy(a,function(f){var e=(c.data(this,"lastToggle"+a.guid)||0)%d;c.data(this,"lastToggle"+a.guid,e+1);f.preventDefault();return b[e].apply(this,arguments)||false}))},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}});var Ga={focus:"focusin",blur:"focusout",mouseenter:"mouseover",mouseleave:"mouseout"};c.each(["live","die"],function(a,b){c.fn[b]=function(d,f,e,j){var i,o=0,k,n,r=j||this.selector, u=j?this:c(this.context);if(c.isFunction(f)){e=f;f=w}for(d=(d||"").split(" ");(i=d[o++])!=null;){j=O.exec(i);k="";if(j){k=j[0];i=i.replace(O,"")}if(i==="hover")d.push("mouseenter"+k,"mouseleave"+k);else{n=i;if(i==="focus"||i==="blur"){d.push(Ga[i]+k);i+=k}else i=(Ga[i]||i)+k;b==="live"?u.each(function(){c.event.add(this,pa(i,r),{data:f,selector:r,handler:e,origType:i,origHandler:e,preType:n})}):u.unbind(pa(i,r),e)}}return this}});c.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){c.fn[b]=function(d){return d?this.bind(b,d):this.trigger(b)};if(c.attrFn)c.attrFn[b]=true});A.attachEvent&&!A.addEventListener&&A.attachEvent("onunload",function(){for(var a in c.cache)if(c.cache[a].handle)try{c.event.remove(c.cache[a].handle.elem)}catch(b){}});(function(){function a(g){for(var h="",l,m=0;g[m];m++){l=g[m];if(l.nodeType===3||l.nodeType===4)h+=l.nodeValue;else if(l.nodeType!==8)h+=a(l.childNodes)}return h}function b(g,h,l,m,q,p){q=0;for(var v=m.length;q<v;q++){var t=m[q]; if(t){t=t[g];for(var y=false;t;){if(t.sizcache===l){y=m[t.sizset];break}if(t.nodeType===1&&!p){t.sizcache=l;t.sizset=q}if(t.nodeName.toLowerCase()===h){y=t;break}t=t[g]}m[q]=y}}}function d(g,h,l,m,q,p){q=0;for(var v=m.length;q<v;q++){var t=m[q];if(t){t=t[g];for(var y=false;t;){if(t.sizcache===l){y=m[t.sizset];break}if(t.nodeType===1){if(!p){t.sizcache=l;t.sizset=q}if(typeof h!=="string"){if(t===h){y=true;break}}else if(k.filter(h,[t]).length>0){y=t;break}}t=t[g]}m[q]=y}}}var f=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, e=0,j=Object.prototype.toString,i=false,o=true;[0,0].sort(function(){o=false;return 0});var k=function(g,h,l,m){l=l||[];var q=h=h||s;if(h.nodeType!==1&&h.nodeType!==9)return[];if(!g||typeof g!=="string")return l;for(var p=[],v,t,y,S,H=true,M=x(h),I=g;(f.exec(""),v=f.exec(I))!==null;){I=v[3];p.push(v[1]);if(v[2]){S=v[3];break}}if(p.length>1&&r.exec(g))if(p.length===2&&n.relative[p[0]])t=ga(p[0]+p[1],h);else for(t=n.relative[p[0]]?[h]:k(p.shift(),h);p.length;){g=p.shift();if(n.relative[g])g+=p.shift(); t=ga(g,t)}else{if(!m&&p.length>1&&h.nodeType===9&&!M&&n.match.ID.test(p[0])&&!n.match.ID.test(p[p.length-1])){v=k.find(p.shift(),h,M);h=v.expr?k.filter(v.expr,v.set)[0]:v.set[0]}if(h){v=m?{expr:p.pop(),set:z(m)}:k.find(p.pop(),p.length===1&&(p[0]==="~"||p[0]==="+")&&h.parentNode?h.parentNode:h,M);t=v.expr?k.filter(v.expr,v.set):v.set;if(p.length>0)y=z(t);else H=false;for(;p.length;){var D=p.pop();v=D;if(n.relative[D])v=p.pop();else D="";if(v==null)v=h;n.relative[D](y,v,M)}}else y=[]}y||(y=t);y||k.error(D|| g);if(j.call(y)==="[object Array]")if(H)if(h&&h.nodeType===1)for(g=0;y[g]!=null;g++){if(y[g]&&(y[g]===true||y[g].nodeType===1&&E(h,y[g])))l.push(t[g])}else for(g=0;y[g]!=null;g++)y[g]&&y[g].nodeType===1&&l.push(t[g]);else l.push.apply(l,y);else z(y,l);if(S){k(S,q,l,m);k.uniqueSort(l)}return l};k.uniqueSort=function(g){if(B){i=o;g.sort(B);if(i)for(var h=1;h<g.length;h++)g[h]===g[h-1]&&g.splice(h--,1)}return g};k.matches=function(g,h){return k(g,null,null,h)};k.find=function(g,h,l){var m,q;if(!g)return[]; for(var p=0,v=n.order.length;p<v;p++){var t=n.order[p];if(q=n.leftMatch[t].exec(g)){var y=q[1];q.splice(1,1);if(y.substr(y.length-1)!=="\\"){q[1]=(q[1]||"").replace(/\\/g,"");m=n.find[t](q,h,l);if(m!=null){g=g.replace(n.match[t],"");break}}}}m||(m=h.getElementsByTagName("*"));return{set:m,expr:g}};k.filter=function(g,h,l,m){for(var q=g,p=[],v=h,t,y,S=h&&h[0]&&x(h[0]);g&&h.length;){for(var H in n.filter)if((t=n.leftMatch[H].exec(g))!=null&&t[2]){var M=n.filter[H],I,D;D=t[1];y=false;t.splice(1,1);if(D.substr(D.length- 1)!=="\\"){if(v===p)p=[];if(n.preFilter[H])if(t=n.preFilter[H](t,v,l,p,m,S)){if(t===true)continue}else y=I=true;if(t)for(var U=0;(D=v[U])!=null;U++)if(D){I=M(D,t,U,v);var Ha=m^!!I;if(l&&I!=null)if(Ha)y=true;else v[U]=false;else if(Ha){p.push(D);y=true}}if(I!==w){l||(v=p);g=g.replace(n.match[H],"");if(!y)return[];break}}}if(g===q)if(y==null)k.error(g);else break;q=g}return v};k.error=function(g){throw"Syntax error, unrecognized expression: "+g;};var n=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|)\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(g){return g.getAttribute("href")}}, relative:{"+":function(g,h){var l=typeof h==="string",m=l&&!/\W/.test(h);l=l&&!m;if(m)h=h.toLowerCase();m=0;for(var q=g.length,p;m<q;m++)if(p=g[m]){for(;(p=p.previousSibling)&&p.nodeType!==1;);g[m]=l||p&&p.nodeName.toLowerCase()===h?p||false:p===h}l&&k.filter(h,g,true)},">":function(g,h){var l=typeof h==="string";if(l&&!/\W/.test(h)){h=h.toLowerCase();for(var m=0,q=g.length;m<q;m++){var p=g[m];if(p){l=p.parentNode;g[m]=l.nodeName.toLowerCase()===h?l:false}}}else{m=0;for(q=g.length;m<q;m++)if(p=g[m])g[m]= l?p.parentNode:p.parentNode===h;l&&k.filter(h,g,true)}},"":function(g,h,l){var m=e++,q=d;if(typeof h==="string"&&!/\W/.test(h)){var p=h=h.toLowerCase();q=b}q("parentNode",h,m,g,p,l)},"~":function(g,h,l){var m=e++,q=d;if(typeof h==="string"&&!/\W/.test(h)){var p=h=h.toLowerCase();q=b}q("previousSibling",h,m,g,p,l)}},find:{ID:function(g,h,l){if(typeof h.getElementById!=="undefined"&&!l)return(g=h.getElementById(g[1]))?[g]:[]},NAME:function(g,h){if(typeof h.getElementsByName!=="undefined"){var l=[]; h=h.getElementsByName(g[1]);for(var m=0,q=h.length;m<q;m++)h[m].getAttribute("name")===g[1]&&l.push(h[m]);return l.length===0?null:l}},TAG:function(g,h){return h.getElementsByTagName(g[1])}},preFilter:{CLASS:function(g,h,l,m,q,p){g=" "+g[1].replace(/\\/g,"")+" ";if(p)return g;p=0;for(var v;(v=h[p])!=null;p++)if(v)if(q^(v.className&&(" "+v.className+" ").replace(/[\t\n]/g," ").indexOf(g)>=0))l||m.push(v);else if(l)h[p]=false;return false},ID:function(g){return g[1].replace(/\\/g,"")},TAG:function(g){return g[1].toLowerCase()}, CHILD:function(g){if(g[1]==="nth"){var h=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(g[2]==="even"&&"2n"||g[2]==="odd"&&"2n+1"||!/\D/.test(g[2])&&"0n+"+g[2]||g[2]);g[2]=h[1]+(h[2]||1)-0;g[3]=h[3]-0}g[0]=e++;return g},ATTR:function(g,h,l,m,q,p){h=g[1].replace(/\\/g,"");if(!p&&n.attrMap[h])g[1]=n.attrMap[h];if(g[2]==="~=")g[4]=" "+g[4]+" ";return g},PSEUDO:function(g,h,l,m,q){if(g[1]==="not")if((f.exec(g[3])||"").length>1||/^\w/.test(g[3]))g[3]=k(g[3],null,null,h);else{g=k.filter(g[3],h,l,true^q);l||m.push.apply(m, g);return false}else if(n.match.POS.test(g[0])||n.match.CHILD.test(g[0]))return true;return g},POS:function(g){g.unshift(true);return g}},filters:{enabled:function(g){return g.disabled===false&&g.type!=="hidden"},disabled:function(g){return g.disabled===true},checked:function(g){return g.checked===true},selected:function(g){return g.selected===true},parent:function(g){return!!g.firstChild},empty:function(g){return!g.firstChild},has:function(g,h,l){return!!k(l[3],g).length},header:function(g){return/h\d/i.test(g.nodeName)}, text:function(g){return"text"===g.type},radio:function(g){return"radio"===g.type},checkbox:function(g){return"checkbox"===g.type},file:function(g){return"file"===g.type},password:function(g){return"password"===g.type},submit:function(g){return"submit"===g.type},image:function(g){return"image"===g.type},reset:function(g){return"reset"===g.type},button:function(g){return"button"===g.type||g.nodeName.toLowerCase()==="button"},input:function(g){return/input|select|textarea|button/i.test(g.nodeName)}}, setFilters:{first:function(g,h){return h===0},last:function(g,h,l,m){return h===m.length-1},even:function(g,h){return h%2===0},odd:function(g,h){return h%2===1},lt:function(g,h,l){return h<l[3]-0},gt:function(g,h,l){return h>l[3]-0},nth:function(g,h,l){return l[3]-0===h},eq:function(g,h,l){return l[3]-0===h}},filter:{PSEUDO:function(g,h,l,m){var q=h[1],p=n.filters[q];if(p)return p(g,l,h,m);else if(q==="contains")return(g.textContent||g.innerText||a([g])||"").indexOf(h[3])>=0;else if(q==="not"){h= h[3];l=0;for(m=h.length;l<m;l++)if(h[l]===g)return false;return true}else k.error("Syntax error, unrecognized expression: "+q)},CHILD:function(g,h){var l=h[1],m=g;switch(l){case "only":case "first":for(;m=m.previousSibling;)if(m.nodeType===1)return false;if(l==="first")return true;m=g;case "last":for(;m=m.nextSibling;)if(m.nodeType===1)return false;return true;case "nth":l=h[2];var q=h[3];if(l===1&&q===0)return true;h=h[0];var p=g.parentNode;if(p&&(p.sizcache!==h||!g.nodeIndex)){var v=0;for(m=p.firstChild;m;m= m.nextSibling)if(m.nodeType===1)m.nodeIndex=++v;p.sizcache=h}g=g.nodeIndex-q;return l===0?g===0:g%l===0&&g/l>=0}},ID:function(g,h){return g.nodeType===1&&g.getAttribute("id")===h},TAG:function(g,h){return h==="*"&&g.nodeType===1||g.nodeName.toLowerCase()===h},CLASS:function(g,h){return(" "+(g.className||g.getAttribute("class"))+" ").indexOf(h)>-1},ATTR:function(g,h){var l=h[1];g=n.attrHandle[l]?n.attrHandle[l](g):g[l]!=null?g[l]:g.getAttribute(l);l=g+"";var m=h[2];h=h[4];return g==null?m==="!=":m=== "="?l===h:m==="*="?l.indexOf(h)>=0:m==="~="?(" "+l+" ").indexOf(h)>=0:!h?l&&g!==false:m==="!="?l!==h:m==="^="?l.indexOf(h)===0:m==="$="?l.substr(l.length-h.length)===h:m==="|="?l===h||l.substr(0,h.length+1)===h+"-":false},POS:function(g,h,l,m){var q=n.setFilters[h[2]];if(q)return q(g,l,h,m)}}},r=n.match.POS;for(var u in n.match){n.match[u]=new RegExp(n.match[u].source+/(?![^\[]*\])(?![^\(]*\))/.source);n.leftMatch[u]=new RegExp(/(^(?:.|\r|\n)*?)/.source+n.match[u].source.replace(/\\(\d+)/g,function(g, h){return"\\"+(h-0+1)}))}var z=function(g,h){g=Array.prototype.slice.call(g,0);if(h){h.push.apply(h,g);return h}return g};try{Array.prototype.slice.call(s.documentElement.childNodes,0)}catch(C){z=function(g,h){h=h||[];if(j.call(g)==="[object Array]")Array.prototype.push.apply(h,g);else if(typeof g.length==="number")for(var l=0,m=g.length;l<m;l++)h.push(g[l]);else for(l=0;g[l];l++)h.push(g[l]);return h}}var B;if(s.documentElement.compareDocumentPosition)B=function(g,h){if(!g.compareDocumentPosition|| !h.compareDocumentPosition){if(g==h)i=true;return g.compareDocumentPosition?-1:1}g=g.compareDocumentPosition(h)&4?-1:g===h?0:1;if(g===0)i=true;return g};else if("sourceIndex"in s.documentElement)B=function(g,h){if(!g.sourceIndex||!h.sourceIndex){if(g==h)i=true;return g.sourceIndex?-1:1}g=g.sourceIndex-h.sourceIndex;if(g===0)i=true;return g};else if(s.createRange)B=function(g,h){if(!g.ownerDocument||!h.ownerDocument){if(g==h)i=true;return g.ownerDocument?-1:1}var l=g.ownerDocument.createRange(),m= h.ownerDocument.createRange();l.setStart(g,0);l.setEnd(g,0);m.setStart(h,0);m.setEnd(h,0);g=l.compareBoundaryPoints(Range.START_TO_END,m);if(g===0)i=true;return g};(function(){var g=s.createElement("div"),h="script"+(new Date).getTime();g.innerHTML="<a name='"+h+"'/>";var l=s.documentElement;l.insertBefore(g,l.firstChild);if(s.getElementById(h)){n.find.ID=function(m,q,p){if(typeof q.getElementById!=="undefined"&&!p)return(q=q.getElementById(m[1]))?q.id===m[1]||typeof q.getAttributeNode!=="undefined"&& q.getAttributeNode("id").nodeValue===m[1]?[q]:w:[]};n.filter.ID=function(m,q){var p=typeof m.getAttributeNode!=="undefined"&&m.getAttributeNode("id");return m.nodeType===1&&p&&p.nodeValue===q}}l.removeChild(g);l=g=null})();(function(){var g=s.createElement("div");g.appendChild(s.createComment(""));if(g.getElementsByTagName("*").length>0)n.find.TAG=function(h,l){l=l.getElementsByTagName(h[1]);if(h[1]==="*"){h=[];for(var m=0;l[m];m++)l[m].nodeType===1&&h.push(l[m]);l=h}return l};g.innerHTML="<a href='#'></a>"; if(g.firstChild&&typeof g.firstChild.getAttribute!=="undefined"&&g.firstChild.getAttribute("href")!=="#")n.attrHandle.href=function(h){return h.getAttribute("href",2)};g=null})();s.querySelectorAll&&function(){var g=k,h=s.createElement("div");h.innerHTML="<p class='TEST'></p>";if(!(h.querySelectorAll&&h.querySelectorAll(".TEST").length===0)){k=function(m,q,p,v){q=q||s;if(!v&&q.nodeType===9&&!x(q))try{return z(q.querySelectorAll(m),p)}catch(t){}return g(m,q,p,v)};for(var l in g)k[l]=g[l];h=null}}(); (function(){var g=s.createElement("div");g.innerHTML="<div class='test e'></div><div class='test'></div>";if(!(!g.getElementsByClassName||g.getElementsByClassName("e").length===0)){g.lastChild.className="e";if(g.getElementsByClassName("e").length!==1){n.order.splice(1,0,"CLASS");n.find.CLASS=function(h,l,m){if(typeof l.getElementsByClassName!=="undefined"&&!m)return l.getElementsByClassName(h[1])};g=null}}})();var E=s.compareDocumentPosition?function(g,h){return!!(g.compareDocumentPosition(h)&16)}: function(g,h){return g!==h&&(g.contains?g.contains(h):true)},x=function(g){return(g=(g?g.ownerDocument||g:0).documentElement)?g.nodeName!=="HTML":false},ga=function(g,h){var l=[],m="",q;for(h=h.nodeType?[h]:h;q=n.match.PSEUDO.exec(g);){m+=q[0];g=g.replace(n.match.PSEUDO,"")}g=n.relative[g]?g+"*":g;q=0;for(var p=h.length;q<p;q++)k(g,h[q],l);return k.filter(m,l)};c.find=k;c.expr=k.selectors;c.expr[":"]=c.expr.filters;c.unique=k.uniqueSort;c.text=a;c.isXMLDoc=x;c.contains=E})();var eb=/Until$/,fb=/^(?:parents|prevUntil|prevAll)/, gb=/,/;R=Array.prototype.slice;var Ia=function(a,b,d){if(c.isFunction(b))return c.grep(a,function(e,j){return!!b.call(e,j,e)===d});else if(b.nodeType)return c.grep(a,function(e){return e===b===d});else if(typeof b==="string"){var f=c.grep(a,function(e){return e.nodeType===1});if(Ua.test(b))return c.filter(b,f,!d);else b=c.filter(b,f)}return c.grep(a,function(e){return c.inArray(e,b)>=0===d})};c.fn.extend({find:function(a){for(var b=this.pushStack("","find",a),d=0,f=0,e=this.length;f<e;f++){d=b.length; c.find(a,this[f],b);if(f>0)for(var j=d;j<b.length;j++)for(var i=0;i<d;i++)if(b[i]===b[j]){b.splice(j--,1);break}}return b},has:function(a){var b=c(a);return this.filter(function(){for(var d=0,f=b.length;d<f;d++)if(c.contains(this,b[d]))return true})},not:function(a){return this.pushStack(Ia(this,a,false),"not",a)},filter:function(a){return this.pushStack(Ia(this,a,true),"filter",a)},is:function(a){return!!a&&c.filter(a,this).length>0},closest:function(a,b){if(c.isArray(a)){var d=[],f=this[0],e,j= {},i;if(f&&a.length){e=0;for(var o=a.length;e<o;e++){i=a[e];j[i]||(j[i]=c.expr.match.POS.test(i)?c(i,b||this.context):i)}for(;f&&f.ownerDocument&&f!==b;){for(i in j){e=j[i];if(e.jquery?e.index(f)>-1:c(f).is(e)){d.push({selector:i,elem:f});delete j[i]}}f=f.parentNode}}return d}var k=c.expr.match.POS.test(a)?c(a,b||this.context):null;return this.map(function(n,r){for(;r&&r.ownerDocument&&r!==b;){if(k?k.index(r)>-1:c(r).is(a))return r;r=r.parentNode}return null})},index:function(a){if(!a||typeof a=== "string")return c.inArray(this[0],a?c(a):this.parent().children());return c.inArray(a.jquery?a[0]:a,this)},add:function(a,b){a=typeof a==="string"?c(a,b||this.context):c.makeArray(a);b=c.merge(this.get(),a);return this.pushStack(qa(a[0])||qa(b[0])?b:c.unique(b))},andSelf:function(){return this.add(this.prevObject)}});c.each({parent:function(a){return(a=a.parentNode)&&a.nodeType!==11?a:null},parents:function(a){return c.dir(a,"parentNode")},parentsUntil:function(a,b,d){return c.dir(a,"parentNode", d)},next:function(a){return c.nth(a,2,"nextSibling")},prev:function(a){return c.nth(a,2,"previousSibling")},nextAll:function(a){return c.dir(a,"nextSibling")},prevAll:function(a){return c.dir(a,"previousSibling")},nextUntil:function(a,b,d){return c.dir(a,"nextSibling",d)},prevUntil:function(a,b,d){return c.dir(a,"previousSibling",d)},siblings:function(a){return c.sibling(a.parentNode.firstChild,a)},children:function(a){return c.sibling(a.firstChild)},contents:function(a){return c.nodeName(a,"iframe")? a.contentDocument||a.contentWindow.document:c.makeArray(a.childNodes)}},function(a,b){c.fn[a]=function(d,f){var e=c.map(this,b,d);eb.test(a)||(f=d);if(f&&typeof f==="string")e=c.filter(f,e);e=this.length>1?c.unique(e):e;if((this.length>1||gb.test(f))&&fb.test(a))e=e.reverse();return this.pushStack(e,a,R.call(arguments).join(","))}});c.extend({filter:function(a,b,d){if(d)a=":not("+a+")";return c.find.matches(a,b)},dir:function(a,b,d){var f=[];for(a=a[b];a&&a.nodeType!==9&&(d===w||a.nodeType!==1||!c(a).is(d));){a.nodeType=== 1&&f.push(a);a=a[b]}return f},nth:function(a,b,d){b=b||1;for(var f=0;a;a=a[d])if(a.nodeType===1&&++f===b)break;return a},sibling:function(a,b){for(var d=[];a;a=a.nextSibling)a.nodeType===1&&a!==b&&d.push(a);return d}});var Ja=/ jQuery\d+="(?:\d+|null)"/g,V=/^\s+/,Ka=/(<([\w:]+)[^>]*?)\/>/g,hb=/^(?:area|br|col|embed|hr|img|input|link|meta|param)$/i,La=/<([\w:]+)/,ib=/<tbody/i,jb=/<|&#?\w+;/,ta=/<script|<object|<embed|<option|<style/i,ua=/checked\s*(?:[^=]|=\s*.checked.)/i,Ma=function(a,b,d){return hb.test(d)? a:b+"></"+d+">"},F={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,"",""]};F.optgroup=F.option;F.tbody=F.tfoot=F.colgroup=F.caption=F.thead;F.th=F.td;if(!c.support.htmlSerialize)F._default=[1,"div<div>","</div>"];c.fn.extend({text:function(a){if(c.isFunction(a))return this.each(function(b){var d= c(this);d.text(a.call(this,b,d.text()))});if(typeof a!=="object"&&a!==w)return this.empty().append((this[0]&&this[0].ownerDocument||s).createTextNode(a));return c.text(this)},wrapAll:function(a){if(c.isFunction(a))return this.each(function(d){c(this).wrapAll(a.call(this,d))});if(this[0]){var b=c(a,this[0].ownerDocument).eq(0).clone(true);this[0].parentNode&&b.insertBefore(this[0]);b.map(function(){for(var d=this;d.firstChild&&d.firstChild.nodeType===1;)d=d.firstChild;return d}).append(this)}return this}, wrapInner:function(a){if(c.isFunction(a))return this.each(function(b){c(this).wrapInner(a.call(this,b))});return this.each(function(){var b=c(this),d=b.contents();d.length?d.wrapAll(a):b.append(a)})},wrap:function(a){return this.each(function(){c(this).wrapAll(a)})},unwrap:function(){return this.parent().each(function(){c.nodeName(this,"body")||c(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.appendChild(a)})}, prepend:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b,this)});else if(arguments.length){var a=c(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,false,function(b){this.parentNode.insertBefore(b, this.nextSibling)});else if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,c(arguments[0]).toArray());return a}},remove:function(a,b){for(var d=0,f;(f=this[d])!=null;d++)if(!a||c.filter(a,[f]).length){if(!b&&f.nodeType===1){c.cleanData(f.getElementsByTagName("*"));c.cleanData([f])}f.parentNode&&f.parentNode.removeChild(f)}return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++)for(b.nodeType===1&&c.cleanData(b.getElementsByTagName("*"));b.firstChild;)b.removeChild(b.firstChild); return this},clone:function(a){var b=this.map(function(){if(!c.support.noCloneEvent&&!c.isXMLDoc(this)){var d=this.outerHTML,f=this.ownerDocument;if(!d){d=f.createElement("div");d.appendChild(this.cloneNode(true));d=d.innerHTML}return c.clean([d.replace(Ja,"").replace(/=([^="'>\s]+\/)>/g,'="$1">').replace(V,"")],f)[0]}else return this.cloneNode(true)});if(a===true){ra(this,b);ra(this.find("*"),b.find("*"))}return b},html:function(a){if(a===w)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(Ja, ""):null;else if(typeof a==="string"&&!ta.test(a)&&(c.support.leadingWhitespace||!V.test(a))&&!F[(La.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Ka,Ma);try{for(var b=0,d=this.length;b<d;b++)if(this[b].nodeType===1){c.cleanData(this[b].getElementsByTagName("*"));this[b].innerHTML=a}}catch(f){this.empty().append(a)}}else c.isFunction(a)?this.each(function(e){var j=c(this),i=j.html();j.empty().append(function(){return a.call(this,e,i)})}):this.empty().append(a);return this},replaceWith:function(a){if(this[0]&& this[0].parentNode){if(c.isFunction(a))return this.each(function(b){var d=c(this),f=d.html();d.replaceWith(a.call(this,b,f))});if(typeof a!=="string")a=c(a).detach();return this.each(function(){var b=this.nextSibling,d=this.parentNode;c(this).remove();b?c(b).before(a):c(d).append(a)})}else return this.pushStack(c(c.isFunction(a)?a():a),"replaceWith",a)},detach:function(a){return this.remove(a,true)},domManip:function(a,b,d){function f(u){return c.nodeName(u,"table")?u.getElementsByTagName("tbody")[0]|| u.appendChild(u.ownerDocument.createElement("tbody")):u}var e,j,i=a[0],o=[],k;if(!c.support.checkClone&&arguments.length===3&&typeof i==="string"&&ua.test(i))return this.each(function(){c(this).domManip(a,b,d,true)});if(c.isFunction(i))return this.each(function(u){var z=c(this);a[0]=i.call(this,u,b?z.html():w);z.domManip(a,b,d)});if(this[0]){e=i&&i.parentNode;e=c.support.parentNode&&e&&e.nodeType===11&&e.childNodes.length===this.length?{fragment:e}:sa(a,this,o);k=e.fragment;if(j=k.childNodes.length=== 1?(k=k.firstChild):k.firstChild){b=b&&c.nodeName(j,"tr");for(var n=0,r=this.length;n<r;n++)d.call(b?f(this[n],j):this[n],n>0||e.cacheable||this.length>1?k.cloneNode(true):k)}o.length&&c.each(o,Qa)}return this}});c.fragments={};c.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){c.fn[a]=function(d){var f=[];d=c(d);var e=this.length===1&&this[0].parentNode;if(e&&e.nodeType===11&&e.childNodes.length===1&&d.length===1){d[b](this[0]); return this}else{e=0;for(var j=d.length;e<j;e++){var i=(e>0?this.clone(true):this).get();c.fn[b].apply(c(d[e]),i);f=f.concat(i)}return this.pushStack(f,a,d.selector)}}});c.extend({clean:function(a,b,d,f){b=b||s;if(typeof b.createElement==="undefined")b=b.ownerDocument||b[0]&&b[0].ownerDocument||s;for(var e=[],j=0,i;(i=a[j])!=null;j++){if(typeof i==="number")i+="";if(i){if(typeof i==="string"&&!jb.test(i))i=b.createTextNode(i);else if(typeof i==="string"){i=i.replace(Ka,Ma);var o=(La.exec(i)||["", ""])[1].toLowerCase(),k=F[o]||F._default,n=k[0],r=b.createElement("div");for(r.innerHTML=k[1]+i+k[2];n--;)r=r.lastChild;if(!c.support.tbody){n=ib.test(i);o=o==="table"&&!n?r.firstChild&&r.firstChild.childNodes:k[1]==="<table>"&&!n?r.childNodes:[];for(k=o.length-1;k>=0;--k)c.nodeName(o[k],"tbody")&&!o[k].childNodes.length&&o[k].parentNode.removeChild(o[k])}!c.support.leadingWhitespace&&V.test(i)&&r.insertBefore(b.createTextNode(V.exec(i)[0]),r.firstChild);i=r.childNodes}if(i.nodeType)e.push(i);else e= c.merge(e,i)}}if(d)for(j=0;e[j];j++)if(f&&c.nodeName(e[j],"script")&&(!e[j].type||e[j].type.toLowerCase()==="text/javascript"))f.push(e[j].parentNode?e[j].parentNode.removeChild(e[j]):e[j]);else{e[j].nodeType===1&&e.splice.apply(e,[j+1,0].concat(c.makeArray(e[j].getElementsByTagName("script"))));d.appendChild(e[j])}return e},cleanData:function(a){for(var b,d,f=c.cache,e=c.event.special,j=c.support.deleteExpando,i=0,o;(o=a[i])!=null;i++)if(d=o[c.expando]){b=f[d];if(b.events)for(var k in b.events)e[k]? c.event.remove(o,k):Ca(o,k,b.handle);if(j)delete o[c.expando];else o.removeAttribute&&o.removeAttribute(c.expando);delete f[d]}}});var kb=/z-?index|font-?weight|opacity|zoom|line-?height/i,Na=/alpha\([^)]*\)/,Oa=/opacity=([^)]*)/,ha=/float/i,ia=/-([a-z])/ig,lb=/([A-Z])/g,mb=/^-?\d+(?:px)?$/i,nb=/^-?\d/,ob={position:"absolute",visibility:"hidden",display:"block"},pb=["Left","Right"],qb=["Top","Bottom"],rb=s.defaultView&&s.defaultView.getComputedStyle,Pa=c.support.cssFloat?"cssFloat":"styleFloat",ja= function(a,b){return b.toUpperCase()};c.fn.css=function(a,b){return X(this,a,b,true,function(d,f,e){if(e===w)return c.curCSS(d,f);if(typeof e==="number"&&!kb.test(f))e+="px";c.style(d,f,e)})};c.extend({style:function(a,b,d){if(!a||a.nodeType===3||a.nodeType===8)return w;if((b==="width"||b==="height")&&parseFloat(d)<0)d=w;var f=a.style||a,e=d!==w;if(!c.support.opacity&&b==="opacity"){if(e){f.zoom=1;b=parseInt(d,10)+""==="NaN"?"":"alpha(opacity="+d*100+")";a=f.filter||c.curCSS(a,"filter")||"";f.filter= Na.test(a)?a.replace(Na,b):b}return f.filter&&f.filter.indexOf("opacity=")>=0?parseFloat(Oa.exec(f.filter)[1])/100+"":""}if(ha.test(b))b=Pa;b=b.replace(ia,ja);if(e)f[b]=d;return f[b]},css:function(a,b,d,f){if(b==="width"||b==="height"){var e,j=b==="width"?pb:qb;function i(){e=b==="width"?a.offsetWidth:a.offsetHeight;f!=="border"&&c.each(j,function(){f||(e-=parseFloat(c.curCSS(a,"padding"+this,true))||0);if(f==="margin")e+=parseFloat(c.curCSS(a,"margin"+this,true))||0;else e-=parseFloat(c.curCSS(a, "border"+this+"Width",true))||0})}a.offsetWidth!==0?i():c.swap(a,ob,i);return Math.max(0,Math.round(e))}return c.curCSS(a,b,d)},curCSS:function(a,b,d){var f,e=a.style;if(!c.support.opacity&&b==="opacity"&&a.currentStyle){f=Oa.test(a.currentStyle.filter||"")?parseFloat(RegExp.$1)/100+"":"";return f===""?"1":f}if(ha.test(b))b=Pa;if(!d&&e&&e[b])f=e[b];else if(rb){if(ha.test(b))b="float";b=b.replace(lb,"-$1").toLowerCase();e=a.ownerDocument.defaultView;if(!e)return null;if(a=e.getComputedStyle(a,null))f= a.getPropertyValue(b);if(b==="opacity"&&f==="")f="1"}else if(a.currentStyle){d=b.replace(ia,ja);f=a.currentStyle[b]||a.currentStyle[d];if(!mb.test(f)&&nb.test(f)){b=e.left;var j=a.runtimeStyle.left;a.runtimeStyle.left=a.currentStyle.left;e.left=d==="fontSize"?"1em":f||0;f=e.pixelLeft+"px";e.left=b;a.runtimeStyle.left=j}}return f},swap:function(a,b,d){var f={};for(var e in b){f[e]=a.style[e];a.style[e]=b[e]}d.call(a);for(e in b)a.style[e]=f[e]}});if(c.expr&&c.expr.filters){c.expr.filters.hidden=function(a){var b= a.offsetWidth,d=a.offsetHeight,f=a.nodeName.toLowerCase()==="tr";return b===0&&d===0&&!f?true:b>0&&d>0&&!f?false:c.curCSS(a,"display")==="none"};c.expr.filters.visible=function(a){return!c.expr.filters.hidden(a)}}var sb=J(),tb=/<script(.|\s)*?\/script>/gi,ub=/select|textarea/i,vb=/color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week/i,N=/=\?(&|$)/,ka=/\?/,wb=/(\?|&)_=.*?(&|$)/,xb=/^(\w+:)?\/\/([^\/?#]+)/,yb=/%20/g,zb=c.fn.load;c.fn.extend({load:function(a,b,d){if(typeof a!== "string")return zb.call(this,a);else if(!this.length)return this;var f=a.indexOf(" ");if(f>=0){var e=a.slice(f,a.length);a=a.slice(0,f)}f="GET";if(b)if(c.isFunction(b)){d=b;b=null}else if(typeof b==="object"){b=c.param(b,c.ajaxSettings.traditional);f="POST"}var j=this;c.ajax({url:a,type:f,dataType:"html",data:b,complete:function(i,o){if(o==="success"||o==="notmodified")j.html(e?c("<div />").append(i.responseText.replace(tb,"")).find(e):i.responseText);d&&j.each(d,[i.responseText,o,i])}});return this}, serialize:function(){return c.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?c.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||ub.test(this.nodeName)||vb.test(this.type))}).map(function(a,b){a=c(this).val();return a==null?null:c.isArray(a)?c.map(a,function(d){return{name:b.name,value:d}}):{name:b.name,value:a}}).get()}});c.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "), function(a,b){c.fn[b]=function(d){return this.bind(b,d)}});c.extend({get:function(a,b,d,f){if(c.isFunction(b)){f=f||d;d=b;b=null}return c.ajax({type:"GET",url:a,data:b,success:d,dataType:f})},getScript:function(a,b){return c.get(a,null,b,"script")},getJSON:function(a,b,d){return c.get(a,b,d,"json")},post:function(a,b,d,f){if(c.isFunction(b)){f=f||d;d=b;b={}}return c.ajax({type:"POST",url:a,data:b,success:d,dataType:f})},ajaxSetup:function(a){c.extend(c.ajaxSettings,a)},ajaxSettings:{url:location.href, global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:A.XMLHttpRequest&&(A.location.protocol!=="file:"||!A.ActiveXObject)?function(){return new A.XMLHttpRequest}:function(){try{return new A.ActiveXObject("Microsoft.XMLHTTP")}catch(a){}},accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},etag:{},ajax:function(a){function b(){e.success&& e.success.call(k,o,i,x);e.global&&f("ajaxSuccess",[x,e])}function d(){e.complete&&e.complete.call(k,x,i);e.global&&f("ajaxComplete",[x,e]);e.global&&!--c.active&&c.event.trigger("ajaxStop")}function f(q,p){(e.context?c(e.context):c.event).trigger(q,p)}var e=c.extend(true,{},c.ajaxSettings,a),j,i,o,k=a&&a.context||e,n=e.type.toUpperCase();if(e.data&&e.processData&&typeof e.data!=="string")e.data=c.param(e.data,e.traditional);if(e.dataType==="jsonp"){if(n==="GET")N.test(e.url)||(e.url+=(ka.test(e.url)? "&":"?")+(e.jsonp||"callback")+"=?");else if(!e.data||!N.test(e.data))e.data=(e.data?e.data+"&":"")+(e.jsonp||"callback")+"=?";e.dataType="json"}if(e.dataType==="json"&&(e.data&&N.test(e.data)||N.test(e.url))){j=e.jsonpCallback||"jsonp"+sb++;if(e.data)e.data=(e.data+"").replace(N,"="+j+"$1");e.url=e.url.replace(N,"="+j+"$1");e.dataType="script";A[j]=A[j]||function(q){o=q;b();d();A[j]=w;try{delete A[j]}catch(p){}z&&z.removeChild(C)}}if(e.dataType==="script"&&e.cache===null)e.cache=false;if(e.cache=== false&&n==="GET"){var r=J(),u=e.url.replace(wb,"$1_="+r+"$2");e.url=u+(u===e.url?(ka.test(e.url)?"&":"?")+"_="+r:"")}if(e.data&&n==="GET")e.url+=(ka.test(e.url)?"&":"?")+e.data;e.global&&!c.active++&&c.event.trigger("ajaxStart");r=(r=xb.exec(e.url))&&(r[1]&&r[1]!==location.protocol||r[2]!==location.host);if(e.dataType==="script"&&n==="GET"&&r){var z=s.getElementsByTagName("head")[0]||s.documentElement,C=s.createElement("script");C.src=e.url;if(e.scriptCharset)C.charset=e.scriptCharset;if(!j){var B= false;C.onload=C.onreadystatechange=function(){if(!B&&(!this.readyState||this.readyState==="loaded"||this.readyState==="complete")){B=true;b();d();C.onload=C.onreadystatechange=null;z&&C.parentNode&&z.removeChild(C)}}}z.insertBefore(C,z.firstChild);return w}var E=false,x=e.xhr();if(x){e.username?x.open(n,e.url,e.async,e.username,e.password):x.open(n,e.url,e.async);try{if(e.data||a&&a.contentType)x.setRequestHeader("Content-Type",e.contentType);if(e.ifModified){c.lastModified[e.url]&&x.setRequestHeader("If-Modified-Since", c.lastModified[e.url]);c.etag[e.url]&&x.setRequestHeader("If-None-Match",c.etag[e.url])}r||x.setRequestHeader("X-Requested-With","XMLHttpRequest");x.setRequestHeader("Accept",e.dataType&&e.accepts[e.dataType]?e.accepts[e.dataType]+", */*":e.accepts._default)}catch(ga){}if(e.beforeSend&&e.beforeSend.call(k,x,e)===false){e.global&&!--c.active&&c.event.trigger("ajaxStop");x.abort();return false}e.global&&f("ajaxSend",[x,e]);var g=x.onreadystatechange=function(q){if(!x||x.readyState===0||q==="abort"){E|| d();E=true;if(x)x.onreadystatechange=c.noop}else if(!E&&x&&(x.readyState===4||q==="timeout")){E=true;x.onreadystatechange=c.noop;i=q==="timeout"?"timeout":!c.httpSuccess(x)?"error":e.ifModified&&c.httpNotModified(x,e.url)?"notmodified":"success";var p;if(i==="success")try{o=c.httpData(x,e.dataType,e)}catch(v){i="parsererror";p=v}if(i==="success"||i==="notmodified")j||b();else c.handleError(e,x,i,p);d();q==="timeout"&&x.abort();if(e.async)x=null}};try{var h=x.abort;x.abort=function(){x&&h.call(x); g("abort")}}catch(l){}e.async&&e.timeout>0&&setTimeout(function(){x&&!E&&g("timeout")},e.timeout);try{x.send(n==="POST"||n==="PUT"||n==="DELETE"?e.data:null)}catch(m){c.handleError(e,x,null,m);d()}e.async||g();return x}},handleError:function(a,b,d,f){if(a.error)a.error.call(a.context||a,b,d,f);if(a.global)(a.context?c(a.context):c.event).trigger("ajaxError",[b,a,f])},active:0,httpSuccess:function(a){try{return!a.status&&location.protocol==="file:"||a.status>=200&&a.status<300||a.status===304||a.status=== 1223||a.status===0}catch(b){}return false},httpNotModified:function(a,b){var d=a.getResponseHeader("Last-Modified"),f=a.getResponseHeader("Etag");if(d)c.lastModified[b]=d;if(f)c.etag[b]=f;return a.status===304||a.status===0},httpData:function(a,b,d){var f=a.getResponseHeader("content-type")||"",e=b==="xml"||!b&&f.indexOf("xml")>=0;a=e?a.responseXML:a.responseText;e&&a.documentElement.nodeName==="parsererror"&&c.error("parsererror");if(d&&d.dataFilter)a=d.dataFilter(a,b);if(typeof a==="string")if(b=== "json"||!b&&f.indexOf("json")>=0)a=c.parseJSON(a);else if(b==="script"||!b&&f.indexOf("javascript")>=0)c.globalEval(a);return a},param:function(a,b){function d(i,o){if(c.isArray(o))c.each(o,function(k,n){b||/\[\]$/.test(i)?f(i,n):d(i+"["+(typeof n==="object"||c.isArray(n)?k:"")+"]",n)});else!b&&o!=null&&typeof o==="object"?c.each(o,function(k,n){d(i+"["+k+"]",n)}):f(i,o)}function f(i,o){o=c.isFunction(o)?o():o;e[e.length]=encodeURIComponent(i)+"="+encodeURIComponent(o)}var e=[];if(b===w)b=c.ajaxSettings.traditional; if(c.isArray(a)||a.jquery)c.each(a,function(){f(this.name,this.value)});else for(var j in a)d(j,a[j]);return e.join("&").replace(yb,"+")}});var la={},Ab=/toggle|show|hide/,Bb=/^([+-]=)?([\d+-.]+)(.*)$/,W,va=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];c.fn.extend({show:function(a,b){if(a||a===0)return this.animate(K("show",3),a,b);else{a=0;for(b=this.length;a<b;a++){var d=c.data(this[a],"olddisplay"); this[a].style.display=d||"";if(c.css(this[a],"display")==="none"){d=this[a].nodeName;var f;if(la[d])f=la[d];else{var e=c("<"+d+" />").appendTo("body");f=e.css("display");if(f==="none")f="block";e.remove();la[d]=f}c.data(this[a],"olddisplay",f)}}a=0;for(b=this.length;a<b;a++)this[a].style.display=c.data(this[a],"olddisplay")||"";return this}},hide:function(a,b){if(a||a===0)return this.animate(K("hide",3),a,b);else{a=0;for(b=this.length;a<b;a++){var d=c.data(this[a],"olddisplay");!d&&d!=="none"&&c.data(this[a], "olddisplay",c.css(this[a],"display"))}a=0;for(b=this.length;a<b;a++)this[a].style.display="none";return this}},_toggle:c.fn.toggle,toggle:function(a,b){var d=typeof a==="boolean";if(c.isFunction(a)&&c.isFunction(b))this._toggle.apply(this,arguments);else a==null||d?this.each(function(){var f=d?a:c(this).is(":hidden");c(this)[f?"show":"hide"]()}):this.animate(K("toggle",3),a,b);return this},fadeTo:function(a,b,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,d)}, animate:function(a,b,d,f){var e=c.speed(b,d,f);if(c.isEmptyObject(a))return this.each(e.complete);return this[e.queue===false?"each":"queue"](function(){var j=c.extend({},e),i,o=this.nodeType===1&&c(this).is(":hidden"),k=this;for(i in a){var n=i.replace(ia,ja);if(i!==n){a[n]=a[i];delete a[i];i=n}if(a[i]==="hide"&&o||a[i]==="show"&&!o)return j.complete.call(this);if((i==="height"||i==="width")&&this.style){j.display=c.css(this,"display");j.overflow=this.style.overflow}if(c.isArray(a[i])){(j.specialEasing= j.specialEasing||{})[i]=a[i][1];a[i]=a[i][0]}}if(j.overflow!=null)this.style.overflow="hidden";j.curAnim=c.extend({},a);c.each(a,function(r,u){var z=new c.fx(k,j,r);if(Ab.test(u))z[u==="toggle"?o?"show":"hide":u](a);else{var C=Bb.exec(u),B=z.cur(true)||0;if(C){u=parseFloat(C[2]);var E=C[3]||"px";if(E!=="px"){k.style[r]=(u||1)+E;B=(u||1)/z.cur(true)*B;k.style[r]=B+E}if(C[1])u=(C[1]==="-="?-1:1)*u+B;z.custom(B,u,E)}else z.custom(B,u,"")}});return true})},stop:function(a,b){var d=c.timers;a&&this.queue([]); this.each(function(){for(var f=d.length-1;f>=0;f--)if(d[f].elem===this){b&&d[f](true);d.splice(f,1)}});b||this.dequeue();return this}});c.each({slideDown:K("show",1),slideUp:K("hide",1),slideToggle:K("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}},function(a,b){c.fn[a]=function(d,f){return this.animate(b,d,f)}});c.extend({speed:function(a,b,d){var f=a&&typeof a==="object"?a:{complete:d||!d&&b||c.isFunction(a)&&a,duration:a,easing:d&&b||b&&!c.isFunction(b)&&b};f.duration=c.fx.off?0:typeof f.duration=== "number"?f.duration:c.fx.speeds[f.duration]||c.fx.speeds._default;f.old=f.complete;f.complete=function(){f.queue!==false&&c(this).dequeue();c.isFunction(f.old)&&f.old.call(this)};return f},easing:{linear:function(a,b,d,f){return d+f*a},swing:function(a,b,d,f){return(-Math.cos(a*Math.PI)/2+0.5)*f+d}},timers:[],fx:function(a,b,d){this.options=b;this.elem=a;this.prop=d;if(!b.orig)b.orig={}}});c.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this);(c.fx.step[this.prop]|| c.fx.step._default)(this);if((this.prop==="height"||this.prop==="width")&&this.elem.style)this.elem.style.display="block"},cur:function(a){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];return(a=parseFloat(c.css(this.elem,this.prop,a)))&&a>-10000?a:parseFloat(c.curCSS(this.elem,this.prop))||0},custom:function(a,b,d){function f(j){return e.step(j)}this.startTime=J();this.start=a;this.end=b;this.unit=d||this.unit||"px";this.now=this.start; this.pos=this.state=0;var e=this;f.elem=this.elem;if(f()&&c.timers.push(f)&&!W)W=setInterval(c.fx.tick,13)},show:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.show=true;this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur());c(this.elem).show()},hide:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.hide=true;this.custom(this.cur(),0)},step:function(a){var b=J(),d=true;if(a||b>=this.options.duration+this.startTime){this.now= this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;for(var f in this.options.curAnim)if(this.options.curAnim[f]!==true)d=false;if(d){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;a=c.data(this.elem,"olddisplay");this.elem.style.display=a?a:this.options.display;if(c.css(this.elem,"display")==="none")this.elem.style.display="block"}this.options.hide&&c(this.elem).hide();if(this.options.hide||this.options.show)for(var e in this.options.curAnim)c.style(this.elem, e,this.options.orig[e]);this.options.complete.call(this.elem)}return false}else{e=b-this.startTime;this.state=e/this.options.duration;a=this.options.easing||(c.easing.swing?"swing":"linear");this.pos=c.easing[this.options.specialEasing&&this.options.specialEasing[this.prop]||a](this.state,e,0,1,this.options.duration);this.now=this.start+(this.end-this.start)*this.pos;this.update()}return true}};c.extend(c.fx,{tick:function(){for(var a=c.timers,b=0;b<a.length;b++)a[b]()||a.splice(b--,1);a.length|| c.fx.stop()},stop:function(){clearInterval(W);W=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){c.style(a.elem,"opacity",a.now)},_default:function(a){if(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;else a.elem[a.prop]=a.now}}});if(c.expr&&c.expr.filters)c.expr.filters.animated=function(a){return c.grep(c.timers,function(b){return a===b.elem}).length};c.fn.offset="getBoundingClientRect"in s.documentElement? function(a){var b=this[0];if(a)return this.each(function(e){c.offset.setOffset(this,a,e)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);var d=b.getBoundingClientRect(),f=b.ownerDocument;b=f.body;f=f.documentElement;return{top:d.top+(self.pageYOffset||c.support.boxModel&&f.scrollTop||b.scrollTop)-(f.clientTop||b.clientTop||0),left:d.left+(self.pageXOffset||c.support.boxModel&&f.scrollLeft||b.scrollLeft)-(f.clientLeft||b.clientLeft||0)}}:function(a){var b= this[0];if(a)return this.each(function(r){c.offset.setOffset(this,a,r)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);c.offset.initialize();var d=b.offsetParent,f=b,e=b.ownerDocument,j,i=e.documentElement,o=e.body;f=(e=e.defaultView)?e.getComputedStyle(b,null):b.currentStyle;for(var k=b.offsetTop,n=b.offsetLeft;(b=b.parentNode)&&b!==o&&b!==i;){if(c.offset.supportsFixedPosition&&f.position==="fixed")break;j=e?e.getComputedStyle(b,null):b.currentStyle; k-=b.scrollTop;n-=b.scrollLeft;if(b===d){k+=b.offsetTop;n+=b.offsetLeft;if(c.offset.doesNotAddBorder&&!(c.offset.doesAddBorderForTableAndCells&&/^t(able|d|h)$/i.test(b.nodeName))){k+=parseFloat(j.borderTopWidth)||0;n+=parseFloat(j.borderLeftWidth)||0}f=d;d=b.offsetParent}if(c.offset.subtractsBorderForOverflowNotVisible&&j.overflow!=="visible"){k+=parseFloat(j.borderTopWidth)||0;n+=parseFloat(j.borderLeftWidth)||0}f=j}if(f.position==="relative"||f.position==="static"){k+=o.offsetTop;n+=o.offsetLeft}if(c.offset.supportsFixedPosition&& f.position==="fixed"){k+=Math.max(i.scrollTop,o.scrollTop);n+=Math.max(i.scrollLeft,o.scrollLeft)}return{top:k,left:n}};c.offset={initialize:function(){var a=s.body,b=s.createElement("div"),d,f,e,j=parseFloat(c.curCSS(a,"marginTop",true))||0;c.extend(b.style,{position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"});b.innerHTML="<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>"; a.insertBefore(b,a.firstChild);d=b.firstChild;f=d.firstChild;e=d.nextSibling.firstChild.firstChild;this.doesNotAddBorder=f.offsetTop!==5;this.doesAddBorderForTableAndCells=e.offsetTop===5;f.style.position="fixed";f.style.top="20px";this.supportsFixedPosition=f.offsetTop===20||f.offsetTop===15;f.style.position=f.style.top="";d.style.overflow="hidden";d.style.position="relative";this.subtractsBorderForOverflowNotVisible=f.offsetTop===-5;this.doesNotIncludeMarginInBodyOffset=a.offsetTop!==j;a.removeChild(b); c.offset.initialize=c.noop},bodyOffset:function(a){var b=a.offsetTop,d=a.offsetLeft;c.offset.initialize();if(c.offset.doesNotIncludeMarginInBodyOffset){b+=parseFloat(c.curCSS(a,"marginTop",true))||0;d+=parseFloat(c.curCSS(a,"marginLeft",true))||0}return{top:b,left:d}},setOffset:function(a,b,d){if(/static/.test(c.curCSS(a,"position")))a.style.position="relative";var f=c(a),e=f.offset(),j=parseInt(c.curCSS(a,"top",true),10)||0,i=parseInt(c.curCSS(a,"left",true),10)||0;if(c.isFunction(b))b=b.call(a, d,e);d={top:b.top-e.top+j,left:b.left-e.left+i};"using"in b?b.using.call(a,d):f.css(d)}};c.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),d=this.offset(),f=/^body|html$/i.test(b[0].nodeName)?{top:0,left:0}:b.offset();d.top-=parseFloat(c.curCSS(a,"marginTop",true))||0;d.left-=parseFloat(c.curCSS(a,"marginLeft",true))||0;f.top+=parseFloat(c.curCSS(b[0],"borderTopWidth",true))||0;f.left+=parseFloat(c.curCSS(b[0],"borderLeftWidth",true))||0;return{top:d.top- f.top,left:d.left-f.left}},offsetParent:function(){return this.map(function(){for(var a=this.offsetParent||s.body;a&&!/^body|html$/i.test(a.nodeName)&&c.css(a,"position")==="static";)a=a.offsetParent;return a})}});c.each(["Left","Top"],function(a,b){var d="scroll"+b;c.fn[d]=function(f){var e=this[0],j;if(!e)return null;if(f!==w)return this.each(function(){if(j=wa(this))j.scrollTo(!a?f:c(j).scrollLeft(),a?f:c(j).scrollTop());else this[d]=f});else return(j=wa(e))?"pageXOffset"in j?j[a?"pageYOffset": "pageXOffset"]:c.support.boxModel&&j.document.documentElement[d]||j.document.body[d]:e[d]}});c.each(["Height","Width"],function(a,b){var d=b.toLowerCase();c.fn["inner"+b]=function(){return this[0]?c.css(this[0],d,false,"padding"):null};c.fn["outer"+b]=function(f){return this[0]?c.css(this[0],d,false,f?"margin":"border"):null};c.fn[d]=function(f){var e=this[0];if(!e)return f==null?null:this;if(c.isFunction(f))return this.each(function(j){var i=c(this);i[d](f.call(this,j,i[d]()))});return"scrollTo"in e&&e.document?e.document.compatMode==="CSS1Compat"&&e.document.documentElement["client"+b]||e.document.body["client"+b]:e.nodeType===9?Math.max(e.documentElement["client"+b],e.body["scroll"+b],e.documentElement["scroll"+b],e.body["offset"+b],e.documentElement["offset"+b]):f===w?c.css(e,d):this.css(d,typeof f==="string"?f:f+"px")}});A.jQuery=A.$=c})(window);
ajax/libs/react-dom/16.8.6/cjs/react-dom-unstable-fire.profiling.min.js
joeyparrish/cdnjs
/** @license React v16.8.6 * react-dom-unstable-fire.profiling.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* Modernizr 3.0.0pre (Custom Build) | MIT */ 'use strict';var aa=require("react"),n=require("object-assign"),r=require("scheduler"),v=require("scheduler/tracing");function ba(a,b,c,d,e,f,g,h){if(!a){a=void 0;if(void 0===b)a=Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var k=[c,d,e,f,g,h],l=0;a=Error(b.replace(/%s/g,function(){return k[l++]}));a.name="Invariant Violation"}a.framesToPop=1;throw a;}} function x(a){for(var b=arguments.length-1,c="https://reactjs.org/docs/error-decoder.html?invariant="+a,d=0;d<b;d++)c+="&args[]="+encodeURIComponent(arguments[d+1]);ba(!1,"Minified React error #"+a+"; visit %s for the full message or use the non-minified dev environment for full errors and additional helpful warnings. ",c)}aa?void 0:x("227");function ca(a,b,c,d,e,f,g,h,k){var l=Array.prototype.slice.call(arguments,3);try{b.apply(c,l)}catch(m){this.onError(m)}} var da=!1,ea=null,fa=!1,ha=null,ia={onError:function(a){da=!0;ea=a}};function ja(a,b,c,d,e,f,g,h,k){da=!1;ea=null;ca.apply(ia,arguments)}function ka(a,b,c,d,e,f,g,h,k){ja.apply(this,arguments);if(da){if(da){var l=ea;da=!1;ea=null}else x("198"),l=void 0;fa||(fa=!0,ha=l)}}var la=null,ma={}; function na(){if(la)for(var a in ma){var b=ma[a],c=la.indexOf(a);-1<c?void 0:x("96",a);if(!oa[c]){b.extractEvents?void 0:x("97",a);oa[c]=b;c=b.eventTypes;for(var d in c){var e=void 0;var f=c[d],g=b,h=d;pa.hasOwnProperty(h)?x("99",h):void 0;pa[h]=f;var k=f.phasedRegistrationNames;if(k){for(e in k)k.hasOwnProperty(e)&&qa(k[e],g,h);e=!0}else f.registrationName?(qa(f.registrationName,g,h),e=!0):e=!1;e?void 0:x("98",d,a)}}}} function qa(a,b,c){ra[a]?x("100",a):void 0;ra[a]=b;sa[a]=b.eventTypes[c].dependencies}var oa=[],pa={},ra={},sa={},ta=null,ua=null,va=null;function wa(a,b,c){var d=a.type||"unknown-event";a.currentTarget=va(c);ka(d,b,void 0,a);a.currentTarget=null}function xa(a,b){null==b?x("30"):void 0;if(null==a)return b;if(Array.isArray(a)){if(Array.isArray(b))return a.push.apply(a,b),a;a.push(b);return a}return Array.isArray(b)?[a].concat(b):[a,b]} function ya(a,b,c){Array.isArray(a)?a.forEach(b,c):a&&b.call(c,a)}var za=null;function Aa(a){if(a){var b=a._dispatchListeners,c=a._dispatchInstances;if(Array.isArray(b))for(var d=0;d<b.length&&!a.isPropagationStopped();d++)wa(a,b[d],c[d]);else b&&wa(a,b,c);a._dispatchListeners=null;a._dispatchInstances=null;a.isPersistent()||a.constructor.release(a)}} var Ba={injectEventPluginOrder:function(a){la?x("101"):void 0;la=Array.prototype.slice.call(a);na()},injectEventPluginsByName:function(a){var b=!1,c;for(c in a)if(a.hasOwnProperty(c)){var d=a[c];ma.hasOwnProperty(c)&&ma[c]===d||(ma[c]?x("102",c):void 0,ma[c]=d,b=!0)}b&&na()}}; function Ca(a,b){var c=a.stateNode;if(!c)return null;var d=ta(c);if(!d)return null;c=d[b];a:switch(b){case "onClick":case "onClickCapture":case "onDoubleClick":case "onDoubleClickCapture":case "onMouseDown":case "onMouseDownCapture":case "onMouseMove":case "onMouseMoveCapture":case "onMouseUp":case "onMouseUpCapture":(d=!d.disabled)||(a=a.type,d=!("button"===a||"input"===a||"select"===a||"textarea"===a));a=!d;break a;default:a=!1}if(a)return null;c&&"function"!==typeof c?x("231",b,typeof c):void 0; return c}function Da(a){null!==a&&(za=xa(za,a));a=za;za=null;if(a&&(ya(a,Aa),za?x("95"):void 0,fa))throw a=ha,fa=!1,ha=null,a;}var Ea=Math.random().toString(36).slice(2),Fa="__reactInternalInstance$"+Ea,Ga="__reactEventHandlers$"+Ea;function Ha(a){if(a[Fa])return a[Fa];for(;!a[Fa];)if(a.parentNode)a=a.parentNode;else return null;a=a[Fa];return 5===a.tag||6===a.tag?a:null}function Ia(a){a=a[Fa];return!a||5!==a.tag&&6!==a.tag?null:a} function Ja(a){if(5===a.tag||6===a.tag)return a.stateNode;x("33")}function Ka(a){return a[Ga]||null}function Ma(a){do a=a.return;while(a&&5!==a.tag);return a?a:null}function Na(a,b,c){if(b=Ca(a,c.dispatchConfig.phasedRegistrationNames[b]))c._dispatchListeners=xa(c._dispatchListeners,b),c._dispatchInstances=xa(c._dispatchInstances,a)} function Oa(a){if(a&&a.dispatchConfig.phasedRegistrationNames){for(var b=a._targetInst,c=[];b;)c.push(b),b=Ma(b);for(b=c.length;0<b--;)Na(c[b],"captured",a);for(b=0;b<c.length;b++)Na(c[b],"bubbled",a)}}function Pa(a,b,c){a&&c&&c.dispatchConfig.registrationName&&(b=Ca(a,c.dispatchConfig.registrationName))&&(c._dispatchListeners=xa(c._dispatchListeners,b),c._dispatchInstances=xa(c._dispatchInstances,a))}function Qa(a){a&&a.dispatchConfig.registrationName&&Pa(a._targetInst,null,a)} function Ra(a){ya(a,Oa)}var Sa=!("undefined"===typeof window||!window.document||!window.document.createElement);function Ta(a,b){var c={};c[a.toLowerCase()]=b.toLowerCase();c["Webkit"+a]="webkit"+b;c["Moz"+a]="moz"+b;return c}var Ua={animationend:Ta("Animation","AnimationEnd"),animationiteration:Ta("Animation","AnimationIteration"),animationstart:Ta("Animation","AnimationStart"),transitionend:Ta("Transition","TransitionEnd")},Va={},Wa={}; Sa&&(Wa=document.createElement("div").style,"AnimationEvent"in window||(delete Ua.animationend.animation,delete Ua.animationiteration.animation,delete Ua.animationstart.animation),"TransitionEvent"in window||delete Ua.transitionend.transition);function Xa(a){if(Va[a])return Va[a];if(!Ua[a])return a;var b=Ua[a],c;for(c in b)if(b.hasOwnProperty(c)&&c in Wa)return Va[a]=b[c];return a} var Ya=Xa("animationend"),Za=Xa("animationiteration"),$a=Xa("animationstart"),ab=Xa("transitionend"),bb="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),cb=null,db=null,eb=null; function fb(){if(eb)return eb;var a,b=db,c=b.length,d,e="value"in cb?cb.value:cb.textContent,f=e.length;for(a=0;a<c&&b[a]===e[a];a++);var g=c-a;for(d=1;d<=g&&b[c-d]===e[f-d];d++);return eb=e.slice(a,1<d?1-d:void 0)}function hb(){return!0}function ib(){return!1} function y(a,b,c,d){this.dispatchConfig=a;this._targetInst=b;this.nativeEvent=c;a=this.constructor.Interface;for(var e in a)a.hasOwnProperty(e)&&((b=a[e])?this[e]=b(c):"target"===e?this.target=d:this[e]=c[e]);this.isDefaultPrevented=(null!=c.defaultPrevented?c.defaultPrevented:!1===c.returnValue)?hb:ib;this.isPropagationStopped=ib;return this} n(y.prototype,{preventDefault:function(){this.defaultPrevented=!0;var a=this.nativeEvent;a&&(a.preventDefault?a.preventDefault():"unknown"!==typeof a.returnValue&&(a.returnValue=!1),this.isDefaultPrevented=hb)},stopPropagation:function(){var a=this.nativeEvent;a&&(a.stopPropagation?a.stopPropagation():"unknown"!==typeof a.cancelBubble&&(a.cancelBubble=!0),this.isPropagationStopped=hb)},persist:function(){this.isPersistent=hb},isPersistent:ib,destructor:function(){var a=this.constructor.Interface, b;for(b in a)this[b]=null;this.nativeEvent=this._targetInst=this.dispatchConfig=null;this.isPropagationStopped=this.isDefaultPrevented=ib;this._dispatchInstances=this._dispatchListeners=null}});y.Interface={type:null,target:null,currentTarget:function(){return null},eventPhase:null,bubbles:null,cancelable:null,timeStamp:function(a){return a.timeStamp||Date.now()},defaultPrevented:null,isTrusted:null}; y.extend=function(a){function b(){}function c(){return d.apply(this,arguments)}var d=this;b.prototype=d.prototype;var e=new b;n(e,c.prototype);c.prototype=e;c.prototype.constructor=c;c.Interface=n({},d.Interface,a);c.extend=d.extend;jb(c);return c};jb(y);function kb(a,b,c,d){if(this.eventPool.length){var e=this.eventPool.pop();this.call(e,a,b,c,d);return e}return new this(a,b,c,d)}function lb(a){a instanceof this?void 0:x("279");a.destructor();10>this.eventPool.length&&this.eventPool.push(a)} function jb(a){a.eventPool=[];a.getPooled=kb;a.release=lb}var mb=y.extend({data:null}),nb=y.extend({data:null}),ob=[9,13,27,32],pb=Sa&&"CompositionEvent"in window,qb=null;Sa&&"documentMode"in document&&(qb=document.documentMode); var rb=Sa&&"TextEvent"in window&&!qb,sb=Sa&&(!pb||qb&&8<qb&&11>=qb),tb=String.fromCharCode(32),ub={beforeInput:{phasedRegistrationNames:{bubbled:"onBeforeInput",captured:"onBeforeInputCapture"},dependencies:["compositionend","keypress","textInput","paste"]},compositionEnd:{phasedRegistrationNames:{bubbled:"onCompositionEnd",captured:"onCompositionEndCapture"},dependencies:"blur compositionend keydown keypress keyup mousedown".split(" ")},compositionStart:{phasedRegistrationNames:{bubbled:"onCompositionStart", captured:"onCompositionStartCapture"},dependencies:"blur compositionstart keydown keypress keyup mousedown".split(" ")},compositionUpdate:{phasedRegistrationNames:{bubbled:"onCompositionUpdate",captured:"onCompositionUpdateCapture"},dependencies:"blur compositionupdate keydown keypress keyup mousedown".split(" ")}},vb=!1; function wb(a,b){switch(a){case "keyup":return-1!==ob.indexOf(b.keyCode);case "keydown":return 229!==b.keyCode;case "keypress":case "mousedown":case "blur":return!0;default:return!1}}function xb(a){a=a.detail;return"object"===typeof a&&"data"in a?a.data:null}var yb=!1;function zb(a,b){switch(a){case "compositionend":return xb(b);case "keypress":if(32!==b.which)return null;vb=!0;return tb;case "textInput":return a=b.data,a===tb&&vb?null:a;default:return null}} function Ab(a,b){if(yb)return"compositionend"===a||!pb&&wb(a,b)?(a=fb(),eb=db=cb=null,yb=!1,a):null;switch(a){case "paste":return null;case "keypress":if(!(b.ctrlKey||b.altKey||b.metaKey)||b.ctrlKey&&b.altKey){if(b.char&&1<b.char.length)return b.char;if(b.which)return String.fromCharCode(b.which)}return null;case "compositionend":return sb&&"ko"!==b.locale?null:b.data;default:return null}} var Bb={eventTypes:ub,extractEvents:function(a,b,c,d){var e=void 0;var f=void 0;if(pb)b:{switch(a){case "compositionstart":e=ub.compositionStart;break b;case "compositionend":e=ub.compositionEnd;break b;case "compositionupdate":e=ub.compositionUpdate;break b}e=void 0}else yb?wb(a,c)&&(e=ub.compositionEnd):"keydown"===a&&229===c.keyCode&&(e=ub.compositionStart);e?(sb&&"ko"!==c.locale&&(yb||e!==ub.compositionStart?e===ub.compositionEnd&&yb&&(f=fb()):(cb=d,db="value"in cb?cb.value:cb.textContent,yb= !0)),e=mb.getPooled(e,b,c,d),f?e.data=f:(f=xb(c),null!==f&&(e.data=f)),Ra(e),f=e):f=null;(a=rb?zb(a,c):Ab(a,c))?(b=nb.getPooled(ub.beforeInput,b,c,d),b.data=a,Ra(b)):b=null;return null===f?b:null===b?f:[f,b]}},Cb=null,Db=null,Eb=null;function Fb(a){if(a=ua(a)){"function"!==typeof Cb?x("280"):void 0;var b=ta(a.stateNode);Cb(a.stateNode,a.type,b)}}function Gb(a){Db?Eb?Eb.push(a):Eb=[a]:Db=a}function Hb(){if(Db){var a=Db,b=Eb;Eb=Db=null;Fb(a);if(b)for(a=0;a<b.length;a++)Fb(b[a])}} function Ib(a,b){return a(b)}function Jb(a,b,c){return a(b,c)}function Kb(){}var Lb=!1;function Mb(a,b){if(Lb)return a(b);Lb=!0;try{return Ib(a,b)}finally{if(Lb=!1,null!==Db||null!==Eb)Kb(),Hb()}}var Ob={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function Pb(a){var b=a&&a.nodeName&&a.nodeName.toLowerCase();return"input"===b?!!Ob[a.type]:"textarea"===b?!0:!1} function Qb(a){a=a.target||a.srcElement||window;a.correspondingUseElement&&(a=a.correspondingUseElement);return 3===a.nodeType?a.parentNode:a}function Rb(a){if(!Sa)return!1;a="on"+a;var b=a in document;b||(b=document.createElement("div"),b.setAttribute(a,"return;"),b="function"===typeof b[a]);return b}function Sb(a){var b=a.type;return(a=a.nodeName)&&"input"===a.toLowerCase()&&("checkbox"===b||"radio"===b)} function Tb(a){var b=Sb(a)?"checked":"value",c=Object.getOwnPropertyDescriptor(a.constructor.prototype,b),d=""+a[b];if(!a.hasOwnProperty(b)&&"undefined"!==typeof c&&"function"===typeof c.get&&"function"===typeof c.set){var e=c.get,f=c.set;Object.defineProperty(a,b,{configurable:!0,get:function(){return e.call(this)},set:function(a){d=""+a;f.call(this,a)}});Object.defineProperty(a,b,{enumerable:c.enumerable});return{getValue:function(){return d},setValue:function(a){d=""+a},stopTracking:function(){a._valueTracker= null;delete a[b]}}}}function Ub(a){a._valueTracker||(a._valueTracker=Tb(a))}function Vb(a){if(!a)return!1;var b=a._valueTracker;if(!b)return!0;var c=b.getValue();var d="";a&&(d=Sb(a)?a.checked?"true":"false":a.value);a=d;return a!==c?(b.setValue(a),!0):!1}var Wb=aa.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;Wb.hasOwnProperty("ReactCurrentDispatcher")||(Wb.ReactCurrentDispatcher={current:null}); var Xb=/^(.*)[\\\/]/,A="function"===typeof Symbol&&Symbol.for,Yb=A?Symbol.for("react.element"):60103,Zb=A?Symbol.for("react.portal"):60106,$b=A?Symbol.for("react.fragment"):60107,ac=A?Symbol.for("react.strict_mode"):60108,bc=A?Symbol.for("react.profiler"):60114,cc=A?Symbol.for("react.provider"):60109,dc=A?Symbol.for("react.context"):60110,ec=A?Symbol.for("react.concurrent_mode"):60111,fc=A?Symbol.for("react.forward_ref"):60112,gc=A?Symbol.for("react.suspense"):60113,hc=A?Symbol.for("react.memo"): 60115,ic=A?Symbol.for("react.lazy"):60116,jc="function"===typeof Symbol&&Symbol.iterator;function kc(a){if(null===a||"object"!==typeof a)return null;a=jc&&a[jc]||a["@@iterator"];return"function"===typeof a?a:null} function lc(a){if(null==a)return null;if("function"===typeof a)return a.displayName||a.name||null;if("string"===typeof a)return a;switch(a){case ec:return"ConcurrentMode";case $b:return"Fragment";case Zb:return"Portal";case bc:return"Profiler";case ac:return"StrictMode";case gc:return"Suspense"}if("object"===typeof a)switch(a.$$typeof){case dc:return"Context.Consumer";case cc:return"Context.Provider";case fc:var b=a.render;b=b.displayName||b.name||"";return a.displayName||(""!==b?"ForwardRef("+b+ ")":"ForwardRef");case hc:return lc(a.type);case ic:if(a=1===a._status?a._result:null)return lc(a)}return null}function mc(a){var b="";do{a:switch(a.tag){case 3:case 4:case 6:case 7:case 10:case 9:var c="";break a;default:var d=a._debugOwner,e=a._debugSource,f=lc(a.type);c=null;d&&(c=lc(d.type));d=f;f="";e?f=" (at "+e.fileName.replace(Xb,"")+":"+e.lineNumber+")":c&&(f=" (created by "+c+")");c="\n in "+(d||"Unknown")+f}b+=c;a=a.return}while(a);return b} var nc=/^[: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][: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\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,oc=Object.prototype.hasOwnProperty,pc={},qc={}; function rc(a){if(oc.call(qc,a))return!0;if(oc.call(pc,a))return!1;if(nc.test(a))return qc[a]=!0;pc[a]=!0;return!1}function sc(a,b,c,d){if(null!==c&&0===c.type)return!1;switch(typeof b){case "function":case "symbol":return!0;case "boolean":if(d)return!1;if(null!==c)return!c.acceptsBooleans;a=a.toLowerCase().slice(0,5);return"data-"!==a&&"aria-"!==a;default:return!1}} function tc(a,b,c,d){if(null===b||"undefined"===typeof b||sc(a,b,c,d))return!0;if(d)return!1;if(null!==c)switch(c.type){case 3:return!b;case 4:return!1===b;case 5:return isNaN(b);case 6:return isNaN(b)||1>b}return!1}function B(a,b,c,d,e){this.acceptsBooleans=2===b||3===b||4===b;this.attributeName=d;this.attributeNamespace=e;this.mustUseProperty=c;this.propertyName=a;this.type=b}var C={}; "children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(a){C[a]=new B(a,0,!1,a,null)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(a){var b=a[0];C[b]=new B(b,1,!1,a[1],null)});["contentEditable","draggable","spellCheck","value"].forEach(function(a){C[a]=new B(a,2,!1,a.toLowerCase(),null)}); ["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(a){C[a]=new B(a,2,!1,a,null)});"allowFullScreen async autoFocus autoPlay controls default defer disabled formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(a){C[a]=new B(a,3,!1,a.toLowerCase(),null)});["checked","multiple","muted","selected"].forEach(function(a){C[a]=new B(a,3,!0,a,null)}); ["capture","download"].forEach(function(a){C[a]=new B(a,4,!1,a,null)});["cols","rows","size","span"].forEach(function(a){C[a]=new B(a,6,!1,a,null)});["rowSpan","start"].forEach(function(a){C[a]=new B(a,5,!1,a.toLowerCase(),null)});var uc=/[\-:]([a-z])/g;function vc(a){return a[1].toUpperCase()} "accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(a){var b=a.replace(uc, vc);C[b]=new B(b,1,!1,a,null)});"xlink:actuate xlink:arcrole xlink:href xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(a){var b=a.replace(uc,vc);C[b]=new B(b,1,!1,a,"http://www.w3.org/1999/xlink")});["xml:base","xml:lang","xml:space"].forEach(function(a){var b=a.replace(uc,vc);C[b]=new B(b,1,!1,a,"http://www.w3.org/XML/1998/namespace")});["tabIndex","crossOrigin"].forEach(function(a){C[a]=new B(a,1,!1,a.toLowerCase(),null)}); function wc(a,b,c,d){var e=C.hasOwnProperty(b)?C[b]:null;var f=null!==e?0===e.type:d?!1:!(2<b.length)||"o"!==b[0]&&"O"!==b[0]||"n"!==b[1]&&"N"!==b[1]?!1:!0;f||(tc(b,c,e,d)&&(c=null),d||null===e?rc(b)&&(null===c?a.removeAttribute(b):a.setAttribute(b,""+c)):e.mustUseProperty?a[e.propertyName]=null===c?3===e.type?!1:"":c:(b=e.attributeName,d=e.attributeNamespace,null===c?a.removeAttribute(b):(e=e.type,c=3===e||4===e&&!0===c?"":""+c,d?a.setAttributeNS(d,b,c):a.setAttribute(b,c))))} function xc(a){switch(typeof a){case "boolean":case "number":case "object":case "string":case "undefined":return a;default:return""}}function yc(a,b){var c=b.checked;return n({},b,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:null!=c?c:a._wrapperState.initialChecked})} function zc(a,b){var c=null==b.defaultValue?"":b.defaultValue,d=null!=b.checked?b.checked:b.defaultChecked;c=xc(null!=b.value?b.value:c);a._wrapperState={initialChecked:d,initialValue:c,controlled:"checkbox"===b.type||"radio"===b.type?null!=b.checked:null!=b.value}}function Ac(a,b){b=b.checked;null!=b&&wc(a,"checked",b,!1)} function Bc(a,b){Ac(a,b);var c=xc(b.value),d=b.type;if(null!=c)if("number"===d){if(0===c&&""===a.value||a.value!=c)a.value=""+c}else a.value!==""+c&&(a.value=""+c);else if("submit"===d||"reset"===d){a.removeAttribute("value");return}b.hasOwnProperty("value")?Cc(a,b.type,c):b.hasOwnProperty("defaultValue")&&Cc(a,b.type,xc(b.defaultValue));null==b.checked&&null!=b.defaultChecked&&(a.defaultChecked=!!b.defaultChecked)} function Dc(a,b,c){if(b.hasOwnProperty("value")||b.hasOwnProperty("defaultValue")){var d=b.type;if(!("submit"!==d&&"reset"!==d||void 0!==b.value&&null!==b.value))return;b=""+a._wrapperState.initialValue;c||b===a.value||(a.value=b);a.defaultValue=b}c=a.name;""!==c&&(a.name="");a.defaultChecked=!a.defaultChecked;a.defaultChecked=!!a._wrapperState.initialChecked;""!==c&&(a.name=c)} function Cc(a,b,c){if("number"!==b||a.ownerDocument.activeElement!==a)null==c?a.defaultValue=""+a._wrapperState.initialValue:a.defaultValue!==""+c&&(a.defaultValue=""+c)}var Ec={change:{phasedRegistrationNames:{bubbled:"onChange",captured:"onChangeCapture"},dependencies:"blur change click focus input keydown keyup selectionchange".split(" ")}};function Fc(a,b,c){a=y.getPooled(Ec.change,a,b,c);a.type="change";Gb(c);Ra(a);return a}var Gc=null,Hc=null;function Ic(a){Da(a)} function Jc(a){var b=Ja(a);if(Vb(b))return a}function Kc(a,b){if("change"===a)return b}var Lc=!1;Sa&&(Lc=Rb("input")&&(!document.documentMode||9<document.documentMode));function Mc(){Gc&&(Gc.detachEvent("onpropertychange",Nc),Hc=Gc=null)}function Nc(a){"value"===a.propertyName&&Jc(Hc)&&(a=Fc(Hc,a,Qb(a)),Mb(Ic,a))}function Oc(a,b,c){"focus"===a?(Mc(),Gc=b,Hc=c,Gc.attachEvent("onpropertychange",Nc)):"blur"===a&&Mc()}function Pc(a){if("selectionchange"===a||"keyup"===a||"keydown"===a)return Jc(Hc)} function Qc(a,b){if("click"===a)return Jc(b)}function Rc(a,b){if("input"===a||"change"===a)return Jc(b)} var Sc={eventTypes:Ec,_isInputEventSupported:Lc,extractEvents:function(a,b,c,d){var e=b?Ja(b):window,f=void 0,g=void 0,h=e.nodeName&&e.nodeName.toLowerCase();"select"===h||"input"===h&&"file"===e.type?f=Kc:Pb(e)?Lc?f=Rc:(f=Pc,g=Oc):(h=e.nodeName)&&"input"===h.toLowerCase()&&("checkbox"===e.type||"radio"===e.type)&&(f=Qc);if(f&&(f=f(a,b)))return Fc(f,c,d);g&&g(a,e,b);"blur"===a&&(a=e._wrapperState)&&a.controlled&&"number"===e.type&&Cc(e,"number",e.value)}},Tc=y.extend({view:null,detail:null}),Uc={Alt:"altKey", Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function Vc(a){var b=this.nativeEvent;return b.getModifierState?b.getModifierState(a):(a=Uc[a])?!!b[a]:!1}function Wc(){return Vc} var Xc=0,Yc=0,Zc=!1,$c=!1,ad=Tc.extend({screenX:null,screenY:null,clientX:null,clientY:null,pageX:null,pageY:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,getModifierState:Wc,button:null,buttons:null,relatedTarget:function(a){return a.relatedTarget||(a.fromElement===a.srcElement?a.toElement:a.fromElement)},movementX:function(a){if("movementX"in a)return a.movementX;var b=Xc;Xc=a.screenX;return Zc?"mousemove"===a.type?a.screenX-b:0:(Zc=!0,0)},movementY:function(a){if("movementY"in a)return a.movementY; var b=Yc;Yc=a.screenY;return $c?"mousemove"===a.type?a.screenY-b:0:($c=!0,0)}}),bd=ad.extend({pointerId:null,width:null,height:null,pressure:null,tangentialPressure:null,tiltX:null,tiltY:null,twist:null,pointerType:null,isPrimary:null}),cd={mouseEnter:{registrationName:"onMouseEnter",dependencies:["mouseout","mouseover"]},mouseLeave:{registrationName:"onMouseLeave",dependencies:["mouseout","mouseover"]},pointerEnter:{registrationName:"onPointerEnter",dependencies:["pointerout","pointerover"]},pointerLeave:{registrationName:"onPointerLeave", dependencies:["pointerout","pointerover"]}},dd={eventTypes:cd,extractEvents:function(a,b,c,d){var e="mouseover"===a||"pointerover"===a,f="mouseout"===a||"pointerout"===a;if(e&&(c.relatedTarget||c.fromElement)||!f&&!e)return null;e=d.window===d?d:(e=d.ownerDocument)?e.defaultView||e.parentWindow:window;f?(f=b,b=(b=c.relatedTarget||c.toElement)?Ha(b):null):f=null;if(f===b)return null;var g=void 0,h=void 0,k=void 0,l=void 0;if("mouseout"===a||"mouseover"===a)g=ad,h=cd.mouseLeave,k=cd.mouseEnter,l="mouse"; else if("pointerout"===a||"pointerover"===a)g=bd,h=cd.pointerLeave,k=cd.pointerEnter,l="pointer";var m=null==f?e:Ja(f);e=null==b?e:Ja(b);a=g.getPooled(h,f,c,d);a.type=l+"leave";a.target=m;a.relatedTarget=e;c=g.getPooled(k,b,c,d);c.type=l+"enter";c.target=e;c.relatedTarget=m;d=b;if(f&&d)a:{b=f;e=d;l=0;for(g=b;g;g=Ma(g))l++;g=0;for(k=e;k;k=Ma(k))g++;for(;0<l-g;)b=Ma(b),l--;for(;0<g-l;)e=Ma(e),g--;for(;l--;){if(b===e||b===e.alternate)break a;b=Ma(b);e=Ma(e)}b=null}else b=null;e=b;for(b=[];f&&f!==e;){l= f.alternate;if(null!==l&&l===e)break;b.push(f);f=Ma(f)}for(f=[];d&&d!==e;){l=d.alternate;if(null!==l&&l===e)break;f.push(d);d=Ma(d)}for(d=0;d<b.length;d++)Pa(b[d],"bubbled",a);for(d=f.length;0<d--;)Pa(f[d],"captured",c);return[a,c]}};function ed(a,b){return a===b&&(0!==a||1/a===1/b)||a!==a&&b!==b}var fd=Object.prototype.hasOwnProperty; function gd(a,b){if(ed(a,b))return!0;if("object"!==typeof a||null===a||"object"!==typeof b||null===b)return!1;var c=Object.keys(a),d=Object.keys(b);if(c.length!==d.length)return!1;for(d=0;d<c.length;d++)if(!fd.call(b,c[d])||!ed(a[c[d]],b[c[d]]))return!1;return!0}function hd(a){var b=a;if(a.alternate)for(;b.return;)b=b.return;else{if(0!==(b.effectTag&2))return 1;for(;b.return;)if(b=b.return,0!==(b.effectTag&2))return 1}return 3===b.tag?2:3}function id(a){2!==hd(a)?x("188"):void 0} function jd(a){var b=a.alternate;if(!b)return b=hd(a),3===b?x("188"):void 0,1===b?null:a;for(var c=a,d=b;;){var e=c.return,f=e?e.alternate:null;if(!e||!f)break;if(e.child===f.child){for(var g=e.child;g;){if(g===c)return id(e),a;if(g===d)return id(e),b;g=g.sibling}x("188")}if(c.return!==d.return)c=e,d=f;else{g=!1;for(var h=e.child;h;){if(h===c){g=!0;c=e;d=f;break}if(h===d){g=!0;d=e;c=f;break}h=h.sibling}if(!g){for(h=f.child;h;){if(h===c){g=!0;c=f;d=e;break}if(h===d){g=!0;d=f;c=e;break}h=h.sibling}g? void 0:x("189")}}c.alternate!==d?x("190"):void 0}3!==c.tag?x("188"):void 0;return c.stateNode.current===c?a:b}function kd(a){a=jd(a);if(!a)return null;for(var b=a;;){if(5===b.tag||6===b.tag)return b;if(b.child)b.child.return=b,b=b.child;else{if(b===a)break;for(;!b.sibling;){if(!b.return||b.return===a)return null;b=b.return}b.sibling.return=b.return;b=b.sibling}}return null} var ld=y.extend({animationName:null,elapsedTime:null,pseudoElement:null}),md=y.extend({clipboardData:function(a){return"clipboardData"in a?a.clipboardData:window.clipboardData}}),nd=Tc.extend({relatedTarget:null});function od(a){var b=a.keyCode;"charCode"in a?(a=a.charCode,0===a&&13===b&&(a=13)):a=b;10===a&&(a=13);return 32<=a||13===a?a:0} var pd={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},qd={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4", 116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},rd=Tc.extend({key:function(a){if(a.key){var b=pd[a.key]||a.key;if("Unidentified"!==b)return b}return"keypress"===a.type?(a=od(a),13===a?"Enter":String.fromCharCode(a)):"keydown"===a.type||"keyup"===a.type?qd[a.keyCode]||"Unidentified":""},location:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,repeat:null,locale:null,getModifierState:Wc,charCode:function(a){return"keypress"=== a.type?od(a):0},keyCode:function(a){return"keydown"===a.type||"keyup"===a.type?a.keyCode:0},which:function(a){return"keypress"===a.type?od(a):"keydown"===a.type||"keyup"===a.type?a.keyCode:0}}),sd=ad.extend({dataTransfer:null}),td=Tc.extend({touches:null,targetTouches:null,changedTouches:null,altKey:null,metaKey:null,ctrlKey:null,shiftKey:null,getModifierState:Wc}),ud=y.extend({propertyName:null,elapsedTime:null,pseudoElement:null}),vd=ad.extend({deltaX:function(a){return"deltaX"in a?a.deltaX:"wheelDeltaX"in a?-a.wheelDeltaX:0},deltaY:function(a){return"deltaY"in a?a.deltaY:"wheelDeltaY"in a?-a.wheelDeltaY:"wheelDelta"in a?-a.wheelDelta:0},deltaZ:null,deltaMode:null}),wd=[["abort","abort"],[Ya,"animationEnd"],[Za,"animationIteration"],[$a,"animationStart"],["canplay","canPlay"],["canplaythrough","canPlayThrough"],["drag","drag"],["dragenter","dragEnter"],["dragexit","dragExit"],["dragleave","dragLeave"],["dragover","dragOver"],["durationchange","durationChange"],["emptied","emptied"],["encrypted","encrypted"], ["ended","ended"],["error","error"],["gotpointercapture","gotPointerCapture"],["load","load"],["loadeddata","loadedData"],["loadedmetadata","loadedMetadata"],["loadstart","loadStart"],["lostpointercapture","lostPointerCapture"],["mousemove","mouseMove"],["mouseout","mouseOut"],["mouseover","mouseOver"],["playing","playing"],["pointermove","pointerMove"],["pointerout","pointerOut"],["pointerover","pointerOver"],["progress","progress"],["scroll","scroll"],["seeking","seeking"],["stalled","stalled"], ["suspend","suspend"],["timeupdate","timeUpdate"],["toggle","toggle"],["touchmove","touchMove"],[ab,"transitionEnd"],["waiting","waiting"],["wheel","wheel"]],xd={},yd={};function zd(a,b){var c=a[0];a=a[1];var d="on"+(a[0].toUpperCase()+a.slice(1));b={phasedRegistrationNames:{bubbled:d,captured:d+"Capture"},dependencies:[c],isInteractive:b};xd[a]=b;yd[c]=b} [["blur","blur"],["cancel","cancel"],["click","click"],["close","close"],["contextmenu","contextMenu"],["copy","copy"],["cut","cut"],["auxclick","auxClick"],["dblclick","doubleClick"],["dragend","dragEnd"],["dragstart","dragStart"],["drop","drop"],["focus","focus"],["input","input"],["invalid","invalid"],["keydown","keyDown"],["keypress","keyPress"],["keyup","keyUp"],["mousedown","mouseDown"],["mouseup","mouseUp"],["paste","paste"],["pause","pause"],["play","play"],["pointercancel","pointerCancel"], ["pointerdown","pointerDown"],["pointerup","pointerUp"],["ratechange","rateChange"],["reset","reset"],["seeked","seeked"],["submit","submit"],["touchcancel","touchCancel"],["touchend","touchEnd"],["touchstart","touchStart"],["volumechange","volumeChange"]].forEach(function(a){zd(a,!0)});wd.forEach(function(a){zd(a,!1)}); var Ad={eventTypes:xd,isInteractiveTopLevelEventType:function(a){a=yd[a];return void 0!==a&&!0===a.isInteractive},extractEvents:function(a,b,c,d){var e=yd[a];if(!e)return null;switch(a){case "keypress":if(0===od(c))return null;case "keydown":case "keyup":a=rd;break;case "blur":case "focus":a=nd;break;case "click":if(2===c.button)return null;case "auxclick":case "dblclick":case "mousedown":case "mousemove":case "mouseup":case "mouseout":case "mouseover":case "contextmenu":a=ad;break;case "drag":case "dragend":case "dragenter":case "dragexit":case "dragleave":case "dragover":case "dragstart":case "drop":a= sd;break;case "touchcancel":case "touchend":case "touchmove":case "touchstart":a=td;break;case Ya:case Za:case $a:a=ld;break;case ab:a=ud;break;case "scroll":a=Tc;break;case "wheel":a=vd;break;case "copy":case "cut":case "paste":a=md;break;case "gotpointercapture":case "lostpointercapture":case "pointercancel":case "pointerdown":case "pointermove":case "pointerout":case "pointerover":case "pointerup":a=bd;break;default:a=y}b=a.getPooled(e,b,c,d);Ra(b);return b}},Bd=Ad.isInteractiveTopLevelEventType, Cd=[];function Dd(a){var b=a.targetInst,c=b;do{if(!c){a.ancestors.push(c);break}var d;for(d=c;d.return;)d=d.return;d=3!==d.tag?null:d.stateNode.containerInfo;if(!d)break;a.ancestors.push(c);c=Ha(d)}while(c);for(c=0;c<a.ancestors.length;c++){b=a.ancestors[c];var e=Qb(a.nativeEvent);d=a.topLevelType;for(var f=a.nativeEvent,g=null,h=0;h<oa.length;h++){var k=oa[h];k&&(k=k.extractEvents(d,b,f,e))&&(g=xa(g,k))}Da(g)}}var Ed=!0; function D(a,b){if(!b)return null;var c=(Bd(a)?Fd:Gd).bind(null,a);b.addEventListener(a,c,!1)}function Hd(a,b){if(!b)return null;var c=(Bd(a)?Fd:Gd).bind(null,a);b.addEventListener(a,c,!0)}function Fd(a,b){Jb(Gd,a,b)} function Gd(a,b){if(Ed){var c=Qb(b);c=Ha(c);null===c||"number"!==typeof c.tag||2===hd(c)||(c=null);if(Cd.length){var d=Cd.pop();d.topLevelType=a;d.nativeEvent=b;d.targetInst=c;a=d}else a={topLevelType:a,nativeEvent:b,targetInst:c,ancestors:[]};try{Mb(Dd,a)}finally{a.topLevelType=null,a.nativeEvent=null,a.targetInst=null,a.ancestors.length=0,10>Cd.length&&Cd.push(a)}}}var Id={},Jd=0,Kd="_reactListenersID"+(""+Math.random()).slice(2); function Ld(a){Object.prototype.hasOwnProperty.call(a,Kd)||(a[Kd]=Jd++,Id[a[Kd]]={});return Id[a[Kd]]}function Md(a){a=a||("undefined"!==typeof document?document:void 0);if("undefined"===typeof a)return null;try{return a.activeElement||a.body}catch(b){return a.body}}function Nd(a){for(;a&&a.firstChild;)a=a.firstChild;return a} function Od(a,b){var c=Nd(a);a=0;for(var d;c;){if(3===c.nodeType){d=a+c.textContent.length;if(a<=b&&d>=b)return{node:c,offset:b-a};a=d}a:{for(;c;){if(c.nextSibling){c=c.nextSibling;break a}c=c.parentNode}c=void 0}c=Nd(c)}}function Pd(a,b){return a&&b?a===b?!0:a&&3===a.nodeType?!1:b&&3===b.nodeType?Pd(a,b.parentNode):"contains"in a?a.contains(b):a.compareDocumentPosition?!!(a.compareDocumentPosition(b)&16):!1:!1} function Qd(){for(var a=window,b=Md();b instanceof a.HTMLIFrameElement;){try{var c="string"===typeof b.contentWindow.location.href}catch(d){c=!1}if(c)a=b.contentWindow;else break;b=Md(a.document)}return b}function Rd(a){var b=a&&a.nodeName&&a.nodeName.toLowerCase();return b&&("input"===b&&("text"===a.type||"search"===a.type||"tel"===a.type||"url"===a.type||"password"===a.type)||"textarea"===b||"true"===a.contentEditable)} function Sd(){var a=Qd();if(Rd(a)){if("selectionStart"in a)var b={start:a.selectionStart,end:a.selectionEnd};else a:{b=(b=a.ownerDocument)&&b.defaultView||window;var c=b.getSelection&&b.getSelection();if(c&&0!==c.rangeCount){b=c.anchorNode;var d=c.anchorOffset,e=c.focusNode;c=c.focusOffset;try{b.nodeType,e.nodeType}catch(U){b=null;break a}var f=0,g=-1,h=-1,k=0,l=0,m=a,p=null;b:for(;;){for(var w;;){m!==b||0!==d&&3!==m.nodeType||(g=f+d);m!==e||0!==c&&3!==m.nodeType||(h=f+c);3===m.nodeType&&(f+=m.nodeValue.length); if(null===(w=m.firstChild))break;p=m;m=w}for(;;){if(m===a)break b;p===b&&++k===d&&(g=f);p===e&&++l===c&&(h=f);if(null!==(w=m.nextSibling))break;m=p;p=m.parentNode}m=w}b=-1===g||-1===h?null:{start:g,end:h}}else b=null}b=b||{start:0,end:0}}else b=null;return{focusedElem:a,selectionRange:b}} function Td(a){var b=Qd(),c=a.focusedElem,d=a.selectionRange;if(b!==c&&c&&c.ownerDocument&&Pd(c.ownerDocument.documentElement,c)){if(null!==d&&Rd(c))if(b=d.start,a=d.end,void 0===a&&(a=b),"selectionStart"in c)c.selectionStart=b,c.selectionEnd=Math.min(a,c.value.length);else if(a=(b=c.ownerDocument||document)&&b.defaultView||window,a.getSelection){a=a.getSelection();var e=c.textContent.length,f=Math.min(d.start,e);d=void 0===d.end?f:Math.min(d.end,e);!a.extend&&f>d&&(e=d,d=f,f=e);e=Od(c,f);var g=Od(c, d);e&&g&&(1!==a.rangeCount||a.anchorNode!==e.node||a.anchorOffset!==e.offset||a.focusNode!==g.node||a.focusOffset!==g.offset)&&(b=b.createRange(),b.setStart(e.node,e.offset),a.removeAllRanges(),f>d?(a.addRange(b),a.extend(g.node,g.offset)):(b.setEnd(g.node,g.offset),a.addRange(b)))}b=[];for(a=c;a=a.parentNode;)1===a.nodeType&&b.push({element:a,left:a.scrollLeft,top:a.scrollTop});"function"===typeof c.focus&&c.focus();for(c=0;c<b.length;c++)a=b[c],a.element.scrollLeft=a.left,a.element.scrollTop=a.top}} var Ud=Sa&&"documentMode"in document&&11>=document.documentMode,Vd={select:{phasedRegistrationNames:{bubbled:"onSelect",captured:"onSelectCapture"},dependencies:"blur contextmenu dragend focus keydown keyup mousedown mouseup selectionchange".split(" ")}},Wd=null,Xd=null,Yd=null,Zd=!1; function $d(a,b){var c=b.window===b?b.document:9===b.nodeType?b:b.ownerDocument;if(Zd||null==Wd||Wd!==Md(c))return null;c=Wd;"selectionStart"in c&&Rd(c)?c={start:c.selectionStart,end:c.selectionEnd}:(c=(c.ownerDocument&&c.ownerDocument.defaultView||window).getSelection(),c={anchorNode:c.anchorNode,anchorOffset:c.anchorOffset,focusNode:c.focusNode,focusOffset:c.focusOffset});return Yd&&gd(Yd,c)?null:(Yd=c,a=y.getPooled(Vd.select,Xd,a,b),a.type="select",a.target=Wd,Ra(a),a)} var ae={eventTypes:Vd,extractEvents:function(a,b,c,d){var e=d.window===d?d.document:9===d.nodeType?d:d.ownerDocument,f;if(!(f=!e)){a:{e=Ld(e);f=sa.onSelect;for(var g=0;g<f.length;g++){var h=f[g];if(!e.hasOwnProperty(h)||!e[h]){e=!1;break a}}e=!0}f=!e}if(f)return null;e=b?Ja(b):window;switch(a){case "focus":if(Pb(e)||"true"===e.contentEditable)Wd=e,Xd=b,Yd=null;break;case "blur":Yd=Xd=Wd=null;break;case "mousedown":Zd=!0;break;case "contextmenu":case "mouseup":case "dragend":return Zd=!1,$d(c,d);case "selectionchange":if(Ud)break; case "keydown":case "keyup":return $d(c,d)}return null}};Ba.injectEventPluginOrder("ResponderEventPlugin SimpleEventPlugin EnterLeaveEventPlugin ChangeEventPlugin SelectEventPlugin BeforeInputEventPlugin".split(" "));ta=Ka;ua=Ia;va=Ja;Ba.injectEventPluginsByName({SimpleEventPlugin:Ad,EnterLeaveEventPlugin:dd,ChangeEventPlugin:Sc,SelectEventPlugin:ae,BeforeInputEventPlugin:Bb});function be(a){var b="";aa.Children.forEach(a,function(a){null!=a&&(b+=a)});return b} function ce(a,b){a=n({children:void 0},b);if(b=be(b.children))a.children=b;return a}function de(a,b,c,d){a=a.options;if(b){b={};for(var e=0;e<c.length;e++)b["$"+c[e]]=!0;for(c=0;c<a.length;c++)e=b.hasOwnProperty("$"+a[c].value),a[c].selected!==e&&(a[c].selected=e),e&&d&&(a[c].defaultSelected=!0)}else{c=""+xc(c);b=null;for(e=0;e<a.length;e++){if(a[e].value===c){a[e].selected=!0;d&&(a[e].defaultSelected=!0);return}null!==b||a[e].disabled||(b=a[e])}null!==b&&(b.selected=!0)}} function ee(a,b){null!=b.dangerouslySetInnerHTML?x("91"):void 0;return n({},b,{value:void 0,defaultValue:void 0,children:""+a._wrapperState.initialValue})}function fe(a,b){var c=b.value;null==c&&(c=b.defaultValue,b=b.children,null!=b&&(null!=c?x("92"):void 0,Array.isArray(b)&&(1>=b.length?void 0:x("93"),b=b[0]),c=b),null==c&&(c=""));a._wrapperState={initialValue:xc(c)}} function ge(a,b){var c=xc(b.value),d=xc(b.defaultValue);null!=c&&(c=""+c,c!==a.value&&(a.value=c),null==b.defaultValue&&a.defaultValue!==c&&(a.defaultValue=c));null!=d&&(a.defaultValue=""+d)}function he(a){var b=a.textContent;b===a._wrapperState.initialValue&&(a.value=b)}var ie={html:"http://www.w3.org/1999/xhtml",mathml:"http://www.w3.org/1998/Math/MathML",svg:"http://www.w3.org/2000/svg"}; function je(a){switch(a){case "svg":return"http://www.w3.org/2000/svg";case "math":return"http://www.w3.org/1998/Math/MathML";default:return"http://www.w3.org/1999/xhtml"}}function ke(a,b){return null==a||"http://www.w3.org/1999/xhtml"===a?je(b):"http://www.w3.org/2000/svg"===a&&"foreignObject"===b?"http://www.w3.org/1999/xhtml":a} var le=void 0,me=function(a){return"undefined"!==typeof MSApp&&MSApp.execUnsafeLocalFunction?function(b,c,d,e){MSApp.execUnsafeLocalFunction(function(){return a(b,c,d,e)})}:a}(function(a,b){if(a.namespaceURI!==ie.svg||"innerHTML"in a)a.innerHTML=b;else{le=le||document.createElement("div");le.innerHTML="<svg>"+b+"</svg>";for(b=le.firstChild;a.firstChild;)a.removeChild(a.firstChild);for(;b.firstChild;)a.appendChild(b.firstChild)}}); function ne(a,b){if(b){var c=a.firstChild;if(c&&c===a.lastChild&&3===c.nodeType){c.nodeValue=b;return}}a.textContent=b} var oe={animationIterationCount:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!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},pe=["Webkit","ms","Moz","O"];Object.keys(oe).forEach(function(a){pe.forEach(function(b){b=b+a.charAt(0).toUpperCase()+a.substring(1);oe[b]=oe[a]})});function qe(a,b,c){return null==b||"boolean"===typeof b||""===b?"":c||"number"!==typeof b||0===b||oe.hasOwnProperty(a)&&oe[a]?(""+b).trim():b+"px"} function re(a,b){a=a.style;for(var c in b)if(b.hasOwnProperty(c)){var d=0===c.indexOf("--"),e=qe(c,b[c],d);"float"===c&&(c="cssFloat");d?a.setProperty(c,e):a[c]=e}}var se=n({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0}); function te(a,b){b&&(se[a]&&(null!=b.children||null!=b.dangerouslySetInnerHTML?x("137",a,""):void 0),null!=b.dangerouslySetInnerHTML&&(null!=b.children?x("60"):void 0,"object"===typeof b.dangerouslySetInnerHTML&&"__html"in b.dangerouslySetInnerHTML?void 0:x("61")),null!=b.style&&"object"!==typeof b.style?x("62",""):void 0)} function ue(a,b){if(-1===a.indexOf("-"))return"string"===typeof b.is;switch(a){case "annotation-xml":case "color-profile":case "font-face":case "font-face-src":case "font-face-uri":case "font-face-format":case "font-face-name":case "missing-glyph":return!1;default:return!0}} function ve(a,b){a=9===a.nodeType||11===a.nodeType?a:a.ownerDocument;var c=Ld(a);b=sa[b];for(var d=0;d<b.length;d++){var e=b[d];if(!c.hasOwnProperty(e)||!c[e]){switch(e){case "scroll":Hd("scroll",a);break;case "focus":case "blur":Hd("focus",a);Hd("blur",a);c.blur=!0;c.focus=!0;break;case "cancel":case "close":Rb(e)&&Hd(e,a);break;case "invalid":case "submit":case "reset":break;default:-1===bb.indexOf(e)&&D(e,a)}c[e]=!0}}}function we(){}var xe=null,ye=null; function ze(a,b){switch(a){case "button":case "input":case "select":case "textarea":return!!b.autoFocus}return!1}function Ae(a,b){return"textarea"===a||"option"===a||"noscript"===a||"string"===typeof b.children||"number"===typeof b.children||"object"===typeof b.dangerouslySetInnerHTML&&null!==b.dangerouslySetInnerHTML&&null!=b.dangerouslySetInnerHTML.__html} var Be="function"===typeof setTimeout?setTimeout:void 0,Ce="function"===typeof clearTimeout?clearTimeout:void 0,De=r.unstable_scheduleCallback,Ee=r.unstable_cancelCallback; function Fe(a,b,c,d,e){a[Ga]=e;"input"===c&&"radio"===e.type&&null!=e.name&&Ac(a,e);ue(c,d);d=ue(c,e);for(var f=0;f<b.length;f+=2){var g=b[f],h=b[f+1];"style"===g?re(a,h):"dangerouslySetInnerHTML"===g?me(a,h):"children"===g?ne(a,h):wc(a,g,h,d)}switch(c){case "input":Bc(a,e);break;case "textarea":ge(a,e);break;case "select":b=a._wrapperState.wasMultiple,a._wrapperState.wasMultiple=!!e.multiple,c=e.value,null!=c?de(a,!!e.multiple,c,!1):b!==!!e.multiple&&(null!=e.defaultValue?de(a,!!e.multiple,e.defaultValue, !0):de(a,!!e.multiple,e.multiple?[]:"",!1))}}function Ge(a){for(a=a.nextSibling;a&&1!==a.nodeType&&3!==a.nodeType;)a=a.nextSibling;return a}function He(a){for(a=a.firstChild;a&&1!==a.nodeType&&3!==a.nodeType;)a=a.nextSibling;return a}new Set;var Ie=[],Je=-1;function E(a){0>Je||(a.current=Ie[Je],Ie[Je]=null,Je--)}function F(a,b){Je++;Ie[Je]=a.current;a.current=b}var Ke={},G={current:Ke},H={current:!1},Le=Ke; function Me(a,b){var c=a.type.contextTypes;if(!c)return Ke;var d=a.stateNode;if(d&&d.__reactInternalMemoizedUnmaskedChildContext===b)return d.__reactInternalMemoizedMaskedChildContext;var e={},f;for(f in c)e[f]=b[f];d&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=b,a.__reactInternalMemoizedMaskedChildContext=e);return e}function I(a){a=a.childContextTypes;return null!==a&&void 0!==a}function Ne(a){E(H,a);E(G,a)}function Oe(a){E(H,a);E(G,a)} function Pe(a,b,c){G.current!==Ke?x("168"):void 0;F(G,b,a);F(H,c,a)}function Qe(a,b,c){var d=a.stateNode;a=b.childContextTypes;if("function"!==typeof d.getChildContext)return c;d=d.getChildContext();for(var e in d)e in a?void 0:x("108",lc(b)||"Unknown",e);return n({},c,d)}function Re(a){var b=a.stateNode;b=b&&b.__reactInternalMemoizedMergedChildContext||Ke;Le=G.current;F(G,b,a);F(H,H.current,a);return!0} function Se(a,b,c){var d=a.stateNode;d?void 0:x("169");c?(b=Qe(a,b,Le),d.__reactInternalMemoizedMergedChildContext=b,E(H,a),E(G,a),F(G,b,a)):E(H,a);F(H,c,a)}var Te=null,Ue=null;function Ve(a){return function(b){try{return a(b)}catch(c){}}}var We="undefined"!==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__; function Xe(a){if("undefined"===typeof __REACT_DEVTOOLS_GLOBAL_HOOK__)return!1;var b=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(b.isDisabled||!b.supportsFiber)return!0;try{var c=b.inject(a);Te=Ve(function(a){return b.onCommitFiberRoot(c,a)});Ue=Ve(function(a){return b.onCommitFiberUnmount(c,a)})}catch(d){}return!0} function Ye(a,b,c,d){this.tag=a;this.key=c;this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null;this.index=0;this.ref=null;this.pendingProps=b;this.contextDependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null;this.mode=d;this.effectTag=0;this.lastEffect=this.firstEffect=this.nextEffect=null;this.childExpirationTime=this.expirationTime=0;this.alternate=null;this.treeBaseDuration=this.selfBaseDuration=this.actualStartTime=this.actualDuration=Number.NaN; this.actualDuration=0;this.actualStartTime=-1;this.treeBaseDuration=this.selfBaseDuration=0}function J(a,b,c,d){return new Ye(a,b,c,d)}function Ze(a){a=a.prototype;return!(!a||!a.isReactComponent)}function $e(a){if("function"===typeof a)return Ze(a)?1:0;if(void 0!==a&&null!==a){a=a.$$typeof;if(a===fc)return 11;if(a===hc)return 14}return 2} function af(a,b){var c=a.alternate;null===c?(c=J(a.tag,b,a.key,a.mode),c.elementType=a.elementType,c.type=a.type,c.stateNode=a.stateNode,c.alternate=a,a.alternate=c):(c.pendingProps=b,c.effectTag=0,c.nextEffect=null,c.firstEffect=null,c.lastEffect=null,c.actualDuration=0,c.actualStartTime=-1);c.childExpirationTime=a.childExpirationTime;c.expirationTime=a.expirationTime;c.child=a.child;c.memoizedProps=a.memoizedProps;c.memoizedState=a.memoizedState;c.updateQueue=a.updateQueue;c.contextDependencies= a.contextDependencies;c.sibling=a.sibling;c.index=a.index;c.ref=a.ref;c.selfBaseDuration=a.selfBaseDuration;c.treeBaseDuration=a.treeBaseDuration;return c} function bf(a,b,c,d,e,f){var g=2;d=a;if("function"===typeof a)Ze(a)&&(g=1);else if("string"===typeof a)g=5;else a:switch(a){case $b:return cf(c.children,e,f,b);case ec:return df(c,e|3,f,b);case ac:return df(c,e|2,f,b);case bc:return a=J(12,c,b,e|4),a.elementType=bc,a.type=bc,a.expirationTime=f,a;case gc:return a=J(13,c,b,e),a.elementType=gc,a.type=gc,a.expirationTime=f,a;default:if("object"===typeof a&&null!==a)switch(a.$$typeof){case cc:g=10;break a;case dc:g=9;break a;case fc:g=11;break a;case hc:g= 14;break a;case ic:g=16;d=null;break a}x("130",null==a?a:typeof a,"")}b=J(g,c,b,e);b.elementType=a;b.type=d;b.expirationTime=f;return b}function cf(a,b,c,d){a=J(7,a,d,b);a.expirationTime=c;return a}function df(a,b,c,d){a=J(8,a,d,b);b=0===(b&1)?ac:ec;a.elementType=b;a.type=b;a.expirationTime=c;return a}function ef(a,b,c){a=J(6,a,null,b);a.expirationTime=c;return a} function ff(a,b,c){b=J(4,null!==a.children?a.children:[],a.key,b);b.expirationTime=c;b.stateNode={containerInfo:a.containerInfo,pendingChildren:null,implementation:a.implementation};return b}function gf(a,b){a.didError=!1;var c=a.earliestPendingTime;0===c?a.earliestPendingTime=a.latestPendingTime=b:c<b?a.earliestPendingTime=b:a.latestPendingTime>b&&(a.latestPendingTime=b);hf(b,a)} function jf(a,b){a.didError=!1;if(0===b)a.earliestPendingTime=0,a.latestPendingTime=0,a.earliestSuspendedTime=0,a.latestSuspendedTime=0,a.latestPingedTime=0;else{b<a.latestPingedTime&&(a.latestPingedTime=0);var c=a.latestPendingTime;0!==c&&(c>b?a.earliestPendingTime=a.latestPendingTime=0:a.earliestPendingTime>b&&(a.earliestPendingTime=a.latestPendingTime));c=a.earliestSuspendedTime;0===c?gf(a,b):b<a.latestSuspendedTime?(a.earliestSuspendedTime=0,a.latestSuspendedTime=0,a.latestPingedTime=0,gf(a,b)): b>c&&gf(a,b)}hf(0,a)}function kf(a,b){var c=a.latestPendingTime,d=a.latestSuspendedTime;a=a.latestPingedTime;return 0!==c&&c<b||0!==d&&d<b||0!==a&&a<b} function lf(a,b){a.didError=!1;a.latestPingedTime>=b&&(a.latestPingedTime=0);var c=a.earliestPendingTime,d=a.latestPendingTime;c===b?a.earliestPendingTime=d===b?a.latestPendingTime=0:d:d===b&&(a.latestPendingTime=c);c=a.earliestSuspendedTime;d=a.latestSuspendedTime;0===c?a.earliestSuspendedTime=a.latestSuspendedTime=b:c<b?a.earliestSuspendedTime=b:d>b&&(a.latestSuspendedTime=b);hf(b,a)}function mf(a,b){var c=a.earliestPendingTime;a=a.earliestSuspendedTime;c>b&&(b=c);a>b&&(b=a);return b} function hf(a,b){var c=b.earliestSuspendedTime,d=b.latestSuspendedTime,e=b.earliestPendingTime,f=b.latestPingedTime;e=0!==e?e:f;0===e&&(0===a||d<a)&&(e=d);a=e;0!==a&&c>a&&(a=c);b.nextExpirationTimeToWorkOn=e;b.expirationTime=a}function K(a,b){if(a&&a.defaultProps){b=n({},b);a=a.defaultProps;for(var c in a)void 0===b[c]&&(b[c]=a[c])}return b} function nf(a){var b=a._result;switch(a._status){case 1:return b;case 2:throw b;case 0:throw b;default:a._status=0;b=a._ctor;b=b();b.then(function(b){0===a._status&&(b=b.default,a._status=1,a._result=b)},function(b){0===a._status&&(a._status=2,a._result=b)});switch(a._status){case 1:return a._result;case 2:throw a._result;}a._result=b;throw b;}}var of=(new aa.Component).refs; function pf(a,b,c,d){b=a.memoizedState;c=c(d,b);c=null===c||void 0===c?b:n({},b,c);a.memoizedState=c;d=a.updateQueue;null!==d&&0===a.expirationTime&&(d.baseState=c)} var yf={isMounted:function(a){return(a=a._reactInternalFiber)?2===hd(a):!1},enqueueSetState:function(a,b,c){a=a._reactInternalFiber;var d=qf();d=rf(d,a);var e=sf(d);e.payload=b;void 0!==c&&null!==c&&(e.callback=c);tf();uf(a,e);vf(a,d)},enqueueReplaceState:function(a,b,c){a=a._reactInternalFiber;var d=qf();d=rf(d,a);var e=sf(d);e.tag=wf;e.payload=b;void 0!==c&&null!==c&&(e.callback=c);tf();uf(a,e);vf(a,d)},enqueueForceUpdate:function(a,b){a=a._reactInternalFiber;var c=qf();c=rf(c,a);var d=sf(c);d.tag= xf;void 0!==b&&null!==b&&(d.callback=b);tf();uf(a,d);vf(a,c)}};function zf(a,b,c,d,e,f,g){a=a.stateNode;return"function"===typeof a.shouldComponentUpdate?a.shouldComponentUpdate(d,f,g):b.prototype&&b.prototype.isPureReactComponent?!gd(c,d)||!gd(e,f):!0} function Af(a,b,c){var d=!1,e=Ke;var f=b.contextType;"object"===typeof f&&null!==f?f=L(f):(e=I(b)?Le:G.current,d=b.contextTypes,f=(d=null!==d&&void 0!==d)?Me(a,e):Ke);b=new b(c,f);a.memoizedState=null!==b.state&&void 0!==b.state?b.state:null;b.updater=yf;a.stateNode=b;b._reactInternalFiber=a;d&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=e,a.__reactInternalMemoizedMaskedChildContext=f);return b} function Bf(a,b,c,d){a=b.state;"function"===typeof b.componentWillReceiveProps&&b.componentWillReceiveProps(c,d);"function"===typeof b.UNSAFE_componentWillReceiveProps&&b.UNSAFE_componentWillReceiveProps(c,d);b.state!==a&&yf.enqueueReplaceState(b,b.state,null)} function Cf(a,b,c,d){var e=a.stateNode;e.props=c;e.state=a.memoizedState;e.refs=of;var f=b.contextType;"object"===typeof f&&null!==f?e.context=L(f):(f=I(b)?Le:G.current,e.context=Me(a,f));f=a.updateQueue;null!==f&&(Df(a,f,c,e,d),e.state=a.memoizedState);f=b.getDerivedStateFromProps;"function"===typeof f&&(pf(a,b,f,c),e.state=a.memoizedState);"function"===typeof b.getDerivedStateFromProps||"function"===typeof e.getSnapshotBeforeUpdate||"function"!==typeof e.UNSAFE_componentWillMount&&"function"!== typeof e.componentWillMount||(b=e.state,"function"===typeof e.componentWillMount&&e.componentWillMount(),"function"===typeof e.UNSAFE_componentWillMount&&e.UNSAFE_componentWillMount(),b!==e.state&&yf.enqueueReplaceState(e,e.state,null),f=a.updateQueue,null!==f&&(Df(a,f,c,e,d),e.state=a.memoizedState));"function"===typeof e.componentDidMount&&(a.effectTag|=4)}var Ef=Array.isArray; function Ff(a,b,c){a=c.ref;if(null!==a&&"function"!==typeof a&&"object"!==typeof a){if(c._owner){c=c._owner;var d=void 0;c&&(1!==c.tag?x("309"):void 0,d=c.stateNode);d?void 0:x("147",a);var e=""+a;if(null!==b&&null!==b.ref&&"function"===typeof b.ref&&b.ref._stringRef===e)return b.ref;b=function(a){var b=d.refs;b===of&&(b=d.refs={});null===a?delete b[e]:b[e]=a};b._stringRef=e;return b}"string"!==typeof a?x("284"):void 0;c._owner?void 0:x("290",a)}return a} function Gf(a,b){"textarea"!==a.type&&x("31","[object Object]"===Object.prototype.toString.call(b)?"object with keys {"+Object.keys(b).join(", ")+"}":b,"")} function Hf(a){function b(b,c){if(a){var d=b.lastEffect;null!==d?(d.nextEffect=c,b.lastEffect=c):b.firstEffect=b.lastEffect=c;c.nextEffect=null;c.effectTag=8}}function c(c,d){if(!a)return null;for(;null!==d;)b(c,d),d=d.sibling;return null}function d(a,b){for(a=new Map;null!==b;)null!==b.key?a.set(b.key,b):a.set(b.index,b),b=b.sibling;return a}function e(a,b,c){a=af(a,b,c);a.index=0;a.sibling=null;return a}function f(b,c,d){b.index=d;if(!a)return c;d=b.alternate;if(null!==d)return d=d.index,d<c?(b.effectTag= 2,c):d;b.effectTag=2;return c}function g(b){a&&null===b.alternate&&(b.effectTag=2);return b}function h(a,b,c,d){if(null===b||6!==b.tag)return b=ef(c,a.mode,d),b.return=a,b;b=e(b,c,d);b.return=a;return b}function k(a,b,c,d){if(null!==b&&b.elementType===c.type)return d=e(b,c.props,d),d.ref=Ff(a,b,c),d.return=a,d;d=bf(c.type,c.key,c.props,null,a.mode,d);d.ref=Ff(a,b,c);d.return=a;return d}function l(a,b,c,d){if(null===b||4!==b.tag||b.stateNode.containerInfo!==c.containerInfo||b.stateNode.implementation!== c.implementation)return b=ff(c,a.mode,d),b.return=a,b;b=e(b,c.children||[],d);b.return=a;return b}function m(a,b,c,d,f){if(null===b||7!==b.tag)return b=cf(c,a.mode,d,f),b.return=a,b;b=e(b,c,d);b.return=a;return b}function p(a,b,c){if("string"===typeof b||"number"===typeof b)return b=ef(""+b,a.mode,c),b.return=a,b;if("object"===typeof b&&null!==b){switch(b.$$typeof){case Yb:return c=bf(b.type,b.key,b.props,null,a.mode,c),c.ref=Ff(a,null,b),c.return=a,c;case Zb:return b=ff(b,a.mode,c),b.return=a,b}if(Ef(b)|| kc(b))return b=cf(b,a.mode,c,null),b.return=a,b;Gf(a,b)}return null}function w(a,b,c,d){var e=null!==b?b.key:null;if("string"===typeof c||"number"===typeof c)return null!==e?null:h(a,b,""+c,d);if("object"===typeof c&&null!==c){switch(c.$$typeof){case Yb:return c.key===e?c.type===$b?m(a,b,c.props.children,d,e):k(a,b,c,d):null;case Zb:return c.key===e?l(a,b,c,d):null}if(Ef(c)||kc(c))return null!==e?null:m(a,b,c,d,null);Gf(a,c)}return null}function U(a,b,c,d,e){if("string"===typeof d||"number"===typeof d)return a= a.get(c)||null,h(b,a,""+d,e);if("object"===typeof d&&null!==d){switch(d.$$typeof){case Yb:return a=a.get(null===d.key?c:d.key)||null,d.type===$b?m(b,a,d.props.children,e,d.key):k(b,a,d,e);case Zb:return a=a.get(null===d.key?c:d.key)||null,l(b,a,d,e)}if(Ef(d)||kc(d))return a=a.get(c)||null,m(b,a,d,e,null);Gf(b,d)}return null}function Nb(e,g,h,k){for(var l=null,m=null,q=g,u=g=0,z=null;null!==q&&u<h.length;u++){q.index>u?(z=q,q=null):z=q.sibling;var t=w(e,q,h[u],k);if(null===t){null===q&&(q=z);break}a&& q&&null===t.alternate&&b(e,q);g=f(t,g,u);null===m?l=t:m.sibling=t;m=t;q=z}if(u===h.length)return c(e,q),l;if(null===q){for(;u<h.length;u++)if(q=p(e,h[u],k))g=f(q,g,u),null===m?l=q:m.sibling=q,m=q;return l}for(q=d(e,q);u<h.length;u++)if(z=U(q,e,u,h[u],k))a&&null!==z.alternate&&q.delete(null===z.key?u:z.key),g=f(z,g,u),null===m?l=z:m.sibling=z,m=z;a&&q.forEach(function(a){return b(e,a)});return l}function La(e,g,h,k){var l=kc(h);"function"!==typeof l?x("150"):void 0;h=l.call(h);null==h?x("151"):void 0; for(var m=l=null,q=g,u=g=0,z=null,t=h.next();null!==q&&!t.done;u++,t=h.next()){q.index>u?(z=q,q=null):z=q.sibling;var gb=w(e,q,t.value,k);if(null===gb){q||(q=z);break}a&&q&&null===gb.alternate&&b(e,q);g=f(gb,g,u);null===m?l=gb:m.sibling=gb;m=gb;q=z}if(t.done)return c(e,q),l;if(null===q){for(;!t.done;u++,t=h.next())t=p(e,t.value,k),null!==t&&(g=f(t,g,u),null===m?l=t:m.sibling=t,m=t);return l}for(q=d(e,q);!t.done;u++,t=h.next())t=U(q,e,u,t.value,k),null!==t&&(a&&null!==t.alternate&&q.delete(null=== t.key?u:t.key),g=f(t,g,u),null===m?l=t:m.sibling=t,m=t);a&&q.forEach(function(a){return b(e,a)});return l}return function(a,d,f,h){var k="object"===typeof f&&null!==f&&f.type===$b&&null===f.key;k&&(f=f.props.children);var l="object"===typeof f&&null!==f;if(l)switch(f.$$typeof){case Yb:a:{l=f.key;for(k=d;null!==k;){if(k.key===l)if(7===k.tag?f.type===$b:k.elementType===f.type){c(a,k.sibling);d=e(k,f.type===$b?f.props.children:f.props,h);d.ref=Ff(a,k,f);d.return=a;a=d;break a}else{c(a,k);break}else b(a, k);k=k.sibling}f.type===$b?(d=cf(f.props.children,a.mode,h,f.key),d.return=a,a=d):(h=bf(f.type,f.key,f.props,null,a.mode,h),h.ref=Ff(a,d,f),h.return=a,a=h)}return g(a);case Zb:a:{for(k=f.key;null!==d;){if(d.key===k)if(4===d.tag&&d.stateNode.containerInfo===f.containerInfo&&d.stateNode.implementation===f.implementation){c(a,d.sibling);d=e(d,f.children||[],h);d.return=a;a=d;break a}else{c(a,d);break}else b(a,d);d=d.sibling}d=ff(f,a.mode,h);d.return=a;a=d}return g(a)}if("string"===typeof f||"number"=== typeof f)return f=""+f,null!==d&&6===d.tag?(c(a,d.sibling),d=e(d,f,h),d.return=a,a=d):(c(a,d),d=ef(f,a.mode,h),d.return=a,a=d),g(a);if(Ef(f))return Nb(a,d,f,h);if(kc(f))return La(a,d,f,h);l&&Gf(a,f);if("undefined"===typeof f&&!k)switch(a.tag){case 1:case 0:h=a.type,x("152",h.displayName||h.name||"Component")}return c(a,d)}}var If=Hf(!0),Jf=Hf(!1),Kf={},M={current:Kf},Lf={current:Kf},Mf={current:Kf};function Nf(a){a===Kf?x("174"):void 0;return a} function Of(a,b){F(Mf,b,a);F(Lf,a,a);F(M,Kf,a);var c=b.nodeType;switch(c){case 9:case 11:b=(b=b.documentElement)?b.namespaceURI:ke(null,"");break;default:c=8===c?b.parentNode:b,b=c.namespaceURI||null,c=c.tagName,b=ke(b,c)}E(M,a);F(M,b,a)}function Pf(a){E(M,a);E(Lf,a);E(Mf,a)}function Qf(a){Nf(Mf.current);var b=Nf(M.current);var c=ke(b,a.type);b!==c&&(F(Lf,a,a),F(M,c,a))}function Rf(a){Lf.current===a&&(E(M,a),E(Lf,a))} var Sf=0,Tf=2,Uf=4,Vf=8,Wf=16,Xf=32,Yf=64,Zf=128,$f=Wb.ReactCurrentDispatcher,ag=0,bg=null,N=null,O=null,cg=null,P=null,dg=null,eg=0,fg=null,gg=0,hg=!1,ig=null,jg=0;function kg(){x("321")}function lg(a,b){if(null===b)return!1;for(var c=0;c<b.length&&c<a.length;c++)if(!ed(a[c],b[c]))return!1;return!0} function mg(a,b,c,d,e,f){ag=f;bg=b;O=null!==a?a.memoizedState:null;$f.current=null===O?ng:og;b=c(d,e);if(hg){do hg=!1,jg+=1,O=null!==a?a.memoizedState:null,dg=cg,fg=P=N=null,$f.current=og,b=c(d,e);while(hg);ig=null;jg=0}$f.current=pg;a=bg;a.memoizedState=cg;a.expirationTime=eg;a.updateQueue=fg;a.effectTag|=gg;a=null!==N&&null!==N.next;ag=0;dg=P=cg=O=N=bg=null;eg=0;fg=null;gg=0;a?x("300"):void 0;return b}function qg(){$f.current=pg;ag=0;dg=P=cg=O=N=bg=null;eg=0;fg=null;gg=0;hg=!1;ig=null;jg=0} function rg(){var a={memoizedState:null,baseState:null,queue:null,baseUpdate:null,next:null};null===P?cg=P=a:P=P.next=a;return P}function sg(){if(null!==dg)P=dg,dg=P.next,N=O,O=null!==N?N.next:null;else{null===O?x("310"):void 0;N=O;var a={memoizedState:N.memoizedState,baseState:N.baseState,queue:N.queue,baseUpdate:N.baseUpdate,next:null};P=null===P?cg=a:P.next=a;O=N.next}return P}function tg(a,b){return"function"===typeof b?b(a):b} function ug(a){var b=sg(),c=b.queue;null===c?x("311"):void 0;c.lastRenderedReducer=a;if(0<jg){var d=c.dispatch;if(null!==ig){var e=ig.get(c);if(void 0!==e){ig.delete(c);var f=b.memoizedState;do f=a(f,e.action),e=e.next;while(null!==e);ed(f,b.memoizedState)||(vg=!0);b.memoizedState=f;b.baseUpdate===c.last&&(b.baseState=f);c.lastRenderedState=f;return[f,d]}}return[b.memoizedState,d]}d=c.last;var g=b.baseUpdate;f=b.baseState;null!==g?(null!==d&&(d.next=null),d=g.next):d=null!==d?d.next:null;if(null!== d){var h=e=null,k=d,l=!1;do{var m=k.expirationTime;m<ag?(l||(l=!0,h=g,e=f),m>eg&&(eg=m)):f=k.eagerReducer===a?k.eagerState:a(f,k.action);g=k;k=k.next}while(null!==k&&k!==d);l||(h=g,e=f);ed(f,b.memoizedState)||(vg=!0);b.memoizedState=f;b.baseUpdate=h;b.baseState=e;c.lastRenderedState=f}return[b.memoizedState,c.dispatch]} function wg(a,b,c,d){a={tag:a,create:b,destroy:c,deps:d,next:null};null===fg?(fg={lastEffect:null},fg.lastEffect=a.next=a):(b=fg.lastEffect,null===b?fg.lastEffect=a.next=a:(c=b.next,b.next=a,a.next=c,fg.lastEffect=a));return a}function xg(a,b,c,d){var e=rg();gg|=a;e.memoizedState=wg(b,c,void 0,void 0===d?null:d)} function yg(a,b,c,d){var e=sg();d=void 0===d?null:d;var f=void 0;if(null!==N){var g=N.memoizedState;f=g.destroy;if(null!==d&&lg(d,g.deps)){wg(Sf,c,f,d);return}}gg|=a;e.memoizedState=wg(b,c,f,d)}function zg(a,b){if("function"===typeof b)return a=a(),b(a),function(){b(null)};if(null!==b&&void 0!==b)return a=a(),b.current=a,function(){b.current=null}}function Ag(){} function Bg(a,b,c){25>jg?void 0:x("301");var d=a.alternate;if(a===bg||null!==d&&d===bg)if(hg=!0,a={expirationTime:ag,action:c,eagerReducer:null,eagerState:null,next:null},null===ig&&(ig=new Map),c=ig.get(b),void 0===c)ig.set(b,a);else{for(b=c;null!==b.next;)b=b.next;b.next=a}else{tf();var e=qf();e=rf(e,a);var f={expirationTime:e,action:c,eagerReducer:null,eagerState:null,next:null},g=b.last;if(null===g)f.next=f;else{var h=g.next;null!==h&&(f.next=h);g.next=f}b.last=f;if(0===a.expirationTime&&(null=== d||0===d.expirationTime)&&(d=b.lastRenderedReducer,null!==d))try{var k=b.lastRenderedState,l=d(k,c);f.eagerReducer=d;f.eagerState=l;if(ed(l,k))return}catch(m){}finally{}vf(a,e)}} var pg={readContext:L,useCallback:kg,useContext:kg,useEffect:kg,useImperativeHandle:kg,useLayoutEffect:kg,useMemo:kg,useReducer:kg,useRef:kg,useState:kg,useDebugValue:kg},ng={readContext:L,useCallback:function(a,b){rg().memoizedState=[a,void 0===b?null:b];return a},useContext:L,useEffect:function(a,b){return xg(516,Zf|Yf,a,b)},useImperativeHandle:function(a,b,c){c=null!==c&&void 0!==c?c.concat([a]):null;return xg(4,Uf|Xf,zg.bind(null,b,a),c)},useLayoutEffect:function(a,b){return xg(4,Uf|Xf,a,b)}, useMemo:function(a,b){var c=rg();b=void 0===b?null:b;a=a();c.memoizedState=[a,b];return a},useReducer:function(a,b,c){var d=rg();b=void 0!==c?c(b):b;d.memoizedState=d.baseState=b;a=d.queue={last:null,dispatch:null,lastRenderedReducer:a,lastRenderedState:b};a=a.dispatch=Bg.bind(null,bg,a);return[d.memoizedState,a]},useRef:function(a){var b=rg();a={current:a};return b.memoizedState=a},useState:function(a){var b=rg();"function"===typeof a&&(a=a());b.memoizedState=b.baseState=a;a=b.queue={last:null,dispatch:null, lastRenderedReducer:tg,lastRenderedState:a};a=a.dispatch=Bg.bind(null,bg,a);return[b.memoizedState,a]},useDebugValue:Ag},og={readContext:L,useCallback:function(a,b){var c=sg();b=void 0===b?null:b;var d=c.memoizedState;if(null!==d&&null!==b&&lg(b,d[1]))return d[0];c.memoizedState=[a,b];return a},useContext:L,useEffect:function(a,b){return yg(516,Zf|Yf,a,b)},useImperativeHandle:function(a,b,c){c=null!==c&&void 0!==c?c.concat([a]):null;return yg(4,Uf|Xf,zg.bind(null,b,a),c)},useLayoutEffect:function(a, b){return yg(4,Uf|Xf,a,b)},useMemo:function(a,b){var c=sg();b=void 0===b?null:b;var d=c.memoizedState;if(null!==d&&null!==b&&lg(b,d[1]))return d[0];a=a();c.memoizedState=[a,b];return a},useReducer:ug,useRef:function(){return sg().memoizedState},useState:function(a){return ug(tg,a)},useDebugValue:Ag},Cg=0,Dg=-1;function Eg(a){Dg=r.unstable_now();0>a.actualStartTime&&(a.actualStartTime=r.unstable_now())} function Fg(a,b){if(0<=Dg){var c=r.unstable_now()-Dg;a.actualDuration+=c;b&&(a.selfBaseDuration=c);Dg=-1}}var Gg=null,Hg=null,Ig=!1;function Jg(a,b){var c=J(5,null,null,0);c.elementType="DELETED";c.type="DELETED";c.stateNode=b;c.return=a;c.effectTag=8;null!==a.lastEffect?(a.lastEffect.nextEffect=c,a.lastEffect=c):a.firstEffect=a.lastEffect=c} function Kg(a,b){switch(a.tag){case 5:var c=a.type;b=1!==b.nodeType||c.toLowerCase()!==b.nodeName.toLowerCase()?null:b;return null!==b?(a.stateNode=b,!0):!1;case 6:return b=""===a.pendingProps||3!==b.nodeType?null:b,null!==b?(a.stateNode=b,!0):!1;case 13:return!1;default:return!1}}function Lg(a){if(Ig){var b=Hg;if(b){var c=b;if(!Kg(a,b)){b=Ge(c);if(!b||!Kg(a,b)){a.effectTag|=2;Ig=!1;Gg=a;return}Jg(Gg,c)}Gg=a;Hg=He(b)}else a.effectTag|=2,Ig=!1,Gg=a}} function Mg(a){for(a=a.return;null!==a&&5!==a.tag&&3!==a.tag&&18!==a.tag;)a=a.return;Gg=a}function Ng(a){if(a!==Gg)return!1;if(!Ig)return Mg(a),Ig=!0,!1;var b=a.type;if(5!==a.tag||"head"!==b&&"body"!==b&&!Ae(b,a.memoizedProps))for(b=Hg;b;)Jg(a,b),b=Ge(b);Mg(a);Hg=Gg?Ge(a.stateNode):null;return!0}function Og(){Hg=Gg=null;Ig=!1}var Pg=Wb.ReactCurrentOwner,vg=!1;function Q(a,b,c,d){b.child=null===a?Jf(b,null,c,d):If(b,a.child,c,d)} function Qg(a,b,c,d,e){c=c.render;var f=b.ref;Rg(b,e);d=mg(a,b,c,d,f,e);if(null!==a&&!vg)return b.updateQueue=a.updateQueue,b.effectTag&=-517,a.expirationTime<=e&&(a.expirationTime=0),Sg(a,b,e);b.effectTag|=1;Q(a,b,d,e);return b.child} function Tg(a,b,c,d,e,f){if(null===a){var g=c.type;if("function"===typeof g&&!Ze(g)&&void 0===g.defaultProps&&null===c.compare&&void 0===c.defaultProps)return b.tag=15,b.type=g,Ug(a,b,g,d,e,f);a=bf(c.type,null,d,null,b.mode,f);a.ref=b.ref;a.return=b;return b.child=a}g=a.child;if(e<f&&(e=g.memoizedProps,c=c.compare,c=null!==c?c:gd,c(e,d)&&a.ref===b.ref))return Sg(a,b,f);b.effectTag|=1;a=af(g,d,f);a.ref=b.ref;a.return=b;return b.child=a} function Ug(a,b,c,d,e,f){return null!==a&&gd(a.memoizedProps,d)&&a.ref===b.ref&&(vg=!1,e<f)?Sg(a,b,f):Vg(a,b,c,d,f)}function Wg(a,b){var c=b.ref;if(null===a&&null!==c||null!==a&&a.ref!==c)b.effectTag|=128}function Vg(a,b,c,d,e){var f=I(c)?Le:G.current;f=Me(b,f);Rg(b,e);c=mg(a,b,c,d,f,e);if(null!==a&&!vg)return b.updateQueue=a.updateQueue,b.effectTag&=-517,a.expirationTime<=e&&(a.expirationTime=0),Sg(a,b,e);b.effectTag|=1;Q(a,b,c,e);return b.child} function Xg(a,b,c,d,e){if(I(c)){var f=!0;Re(b)}else f=!1;Rg(b,e);if(null===b.stateNode)null!==a&&(a.alternate=null,b.alternate=null,b.effectTag|=2),Af(b,c,d,e),Cf(b,c,d,e),d=!0;else if(null===a){var g=b.stateNode,h=b.memoizedProps;g.props=h;var k=g.context,l=c.contextType;"object"===typeof l&&null!==l?l=L(l):(l=I(c)?Le:G.current,l=Me(b,l));var m=c.getDerivedStateFromProps,p="function"===typeof m||"function"===typeof g.getSnapshotBeforeUpdate;p||"function"!==typeof g.UNSAFE_componentWillReceiveProps&& "function"!==typeof g.componentWillReceiveProps||(h!==d||k!==l)&&Bf(b,g,d,l);Yg=!1;var w=b.memoizedState;k=g.state=w;var U=b.updateQueue;null!==U&&(Df(b,U,d,g,e),k=b.memoizedState);h!==d||w!==k||H.current||Yg?("function"===typeof m&&(pf(b,c,m,d),k=b.memoizedState),(h=Yg||zf(b,c,h,d,w,k,l))?(p||"function"!==typeof g.UNSAFE_componentWillMount&&"function"!==typeof g.componentWillMount||("function"===typeof g.componentWillMount&&g.componentWillMount(),"function"===typeof g.UNSAFE_componentWillMount&& g.UNSAFE_componentWillMount()),"function"===typeof g.componentDidMount&&(b.effectTag|=4)):("function"===typeof g.componentDidMount&&(b.effectTag|=4),b.memoizedProps=d,b.memoizedState=k),g.props=d,g.state=k,g.context=l,d=h):("function"===typeof g.componentDidMount&&(b.effectTag|=4),d=!1)}else g=b.stateNode,h=b.memoizedProps,g.props=b.type===b.elementType?h:K(b.type,h),k=g.context,l=c.contextType,"object"===typeof l&&null!==l?l=L(l):(l=I(c)?Le:G.current,l=Me(b,l)),m=c.getDerivedStateFromProps,(p="function"=== typeof m||"function"===typeof g.getSnapshotBeforeUpdate)||"function"!==typeof g.UNSAFE_componentWillReceiveProps&&"function"!==typeof g.componentWillReceiveProps||(h!==d||k!==l)&&Bf(b,g,d,l),Yg=!1,k=b.memoizedState,w=g.state=k,U=b.updateQueue,null!==U&&(Df(b,U,d,g,e),w=b.memoizedState),h!==d||k!==w||H.current||Yg?("function"===typeof m&&(pf(b,c,m,d),w=b.memoizedState),(m=Yg||zf(b,c,h,d,k,w,l))?(p||"function"!==typeof g.UNSAFE_componentWillUpdate&&"function"!==typeof g.componentWillUpdate||("function"=== typeof g.componentWillUpdate&&g.componentWillUpdate(d,w,l),"function"===typeof g.UNSAFE_componentWillUpdate&&g.UNSAFE_componentWillUpdate(d,w,l)),"function"===typeof g.componentDidUpdate&&(b.effectTag|=4),"function"===typeof g.getSnapshotBeforeUpdate&&(b.effectTag|=256)):("function"!==typeof g.componentDidUpdate||h===a.memoizedProps&&k===a.memoizedState||(b.effectTag|=4),"function"!==typeof g.getSnapshotBeforeUpdate||h===a.memoizedProps&&k===a.memoizedState||(b.effectTag|=256),b.memoizedProps=d,b.memoizedState= w),g.props=d,g.state=w,g.context=l,d=m):("function"!==typeof g.componentDidUpdate||h===a.memoizedProps&&k===a.memoizedState||(b.effectTag|=4),"function"!==typeof g.getSnapshotBeforeUpdate||h===a.memoizedProps&&k===a.memoizedState||(b.effectTag|=256),d=!1);return Zg(a,b,c,d,f,e)} function Zg(a,b,c,d,e,f){Wg(a,b);var g=0!==(b.effectTag&64);if(!d&&!g)return e&&Se(b,c,!1),Sg(a,b,f);d=b.stateNode;Pg.current=b;if(g&&"function"!==typeof c.getDerivedStateFromError){var h=null;Dg=-1}else h=d.render();b.effectTag|=1;null!==a&&g?(g=h,b.child=If(b,a.child,null,f),b.child=If(b,null,g,f)):Q(a,b,h,f);b.memoizedState=d.state;e&&Se(b,c,!0);return b.child} function $g(a){var b=a.stateNode;b.pendingContext?Pe(a,b.pendingContext,b.pendingContext!==b.context):b.context&&Pe(a,b.context,!1);Of(a,b.containerInfo)} function ah(a,b,c){var d=b.mode,e=b.pendingProps,f=b.memoizedState;if(0===(b.effectTag&64)){f=null;var g=!1}else f={timedOutAt:null!==f?f.timedOutAt:0},g=!0,b.effectTag&=-65;if(null===a)if(g){var h=e.fallback;a=cf(null,d,0,null);0===(b.mode&1)&&(a.child=null!==b.memoizedState?b.child.child:b.child);c=cf(h,d,c,null);a.sibling=c;d=a;d.return=c.return=b}else d=c=Jf(b,null,e.children,c);else{if(null!==a.memoizedState)if(h=a.child,d=h.sibling,g){e=e.fallback;c=af(h,h.pendingProps,0);0===(b.mode&1)&&(g= null!==b.memoizedState?b.child.child:b.child,g!==h.child&&(c.child=g));if(b.mode&4){h=0;for(g=c.child;null!==g;)h+=g.treeBaseDuration,g=g.sibling;c.treeBaseDuration=h}h=c.sibling=af(d,e,d.expirationTime);d=c;c.childExpirationTime=0;c=h;d.return=c.return=b}else d=c=If(b,h.child,e.children,c);else{var k=a.child;if(g){e=e.fallback;h=cf(null,d,0,null);h.child=k;0===(b.mode&1)&&(h.child=null!==b.memoizedState?b.child.child:b.child);if(b.mode&4){g=0;for(k=h.child;null!==k;)g+=k.treeBaseDuration,k=k.sibling; h.treeBaseDuration=g}c=h.sibling=cf(e,d,c,null);c.effectTag|=2;d=h;h.childExpirationTime=0;d.return=c.return=b}else c=d=If(b,k,e.children,c)}b.stateNode=a.stateNode}b.memoizedState=f;b.child=d;return c} function Sg(a,b,c){null!==a&&(b.contextDependencies=a.contextDependencies);Dg=-1;if(b.childExpirationTime<c)return null;null!==a&&b.child!==a.child?x("153"):void 0;if(null!==b.child){a=b.child;c=af(a,a.pendingProps,a.expirationTime);b.child=c;for(c.return=b;null!==a.sibling;)a=a.sibling,c=c.sibling=af(a,a.pendingProps,a.expirationTime),c.return=b;c.sibling=null}return b.child} function bh(a,b,c){var d=b.expirationTime;if(null!==a)if(a.memoizedProps!==b.pendingProps||H.current)vg=!0;else{if(d<c){vg=!1;switch(b.tag){case 3:$g(b);Og();break;case 5:Qf(b);break;case 1:I(b.type)&&Re(b);break;case 4:Of(b,b.stateNode.containerInfo);break;case 10:ch(b,b.memoizedProps.value);break;case 12:b.effectTag|=4;break;case 13:if(null!==b.memoizedState){d=b.child.childExpirationTime;if(0!==d&&d>=c)return ah(a,b,c);b=Sg(a,b,c);return null!==b?b.sibling:null}}return Sg(a,b,c)}}else vg=!1;b.expirationTime= 0;switch(b.tag){case 2:d=b.elementType;null!==a&&(a.alternate=null,b.alternate=null,b.effectTag|=2);a=b.pendingProps;var e=Me(b,G.current);Rg(b,c);e=mg(null,b,d,a,e,c);b.effectTag|=1;if("object"===typeof e&&null!==e&&"function"===typeof e.render&&void 0===e.$$typeof){b.tag=1;qg();if(I(d)){var f=!0;Re(b)}else f=!1;b.memoizedState=null!==e.state&&void 0!==e.state?e.state:null;var g=d.getDerivedStateFromProps;"function"===typeof g&&pf(b,d,g,a);e.updater=yf;b.stateNode=e;e._reactInternalFiber=b;Cf(b, d,a,c);b=Zg(null,b,d,!0,f,c)}else b.tag=0,Q(null,b,e,c),b=b.child;return b;case 16:e=b.elementType;null!==a&&(a.alternate=null,b.alternate=null,b.effectTag|=2);f=b.pendingProps;a=nf(e);b.type=a;e=b.tag=$e(a);f=K(a,f);g=void 0;switch(e){case 0:g=Vg(null,b,a,f,c);break;case 1:g=Xg(null,b,a,f,c);break;case 11:g=Qg(null,b,a,f,c);break;case 14:g=Tg(null,b,a,K(a.type,f),d,c);break;default:x("306",a,"")}return g;case 0:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:K(d,e),Vg(a,b,d,e,c);case 1:return d= b.type,e=b.pendingProps,e=b.elementType===d?e:K(d,e),Xg(a,b,d,e,c);case 3:$g(b);d=b.updateQueue;null===d?x("282"):void 0;e=b.memoizedState;e=null!==e?e.element:null;Df(b,d,b.pendingProps,null,c);d=b.memoizedState.element;if(d===e)Og(),b=Sg(a,b,c);else{e=b.stateNode;if(e=(null===a||null===a.child)&&e.hydrate)Hg=He(b.stateNode.containerInfo),Gg=b,e=Ig=!0;e?(b.effectTag|=2,b.child=Jf(b,null,d,c)):(Q(a,b,d,c),Og());b=b.child}return b;case 5:return Qf(b),null===a&&Lg(b),d=b.type,e=b.pendingProps,f=null!== a?a.memoizedProps:null,g=e.children,Ae(d,e)?g=null:null!==f&&Ae(d,f)&&(b.effectTag|=16),Wg(a,b),1!==c&&b.mode&1&&e.hidden?(b.expirationTime=b.childExpirationTime=1,b=null):(Q(a,b,g,c),b=b.child),b;case 6:return null===a&&Lg(b),null;case 13:return ah(a,b,c);case 4:return Of(b,b.stateNode.containerInfo),d=b.pendingProps,null===a?b.child=If(b,null,d,c):Q(a,b,d,c),b.child;case 11:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:K(d,e),Qg(a,b,d,e,c);case 7:return Q(a,b,b.pendingProps,c),b.child; case 8:return Q(a,b,b.pendingProps.children,c),b.child;case 12:return b.effectTag|=4,Q(a,b,b.pendingProps.children,c),b.child;case 10:a:{d=b.type._context;e=b.pendingProps;g=b.memoizedProps;f=e.value;ch(b,f);if(null!==g){var h=g.value;f=ed(h,f)?0:("function"===typeof d._calculateChangedBits?d._calculateChangedBits(h,f):1073741823)|0;if(0===f){if(g.children===e.children&&!H.current){b=Sg(a,b,c);break a}}else for(h=b.child,null!==h&&(h.return=b);null!==h;){var k=h.contextDependencies;if(null!==k){g= h.child;for(var l=k.first;null!==l;){if(l.context===d&&0!==(l.observedBits&f)){1===h.tag&&(l=sf(c),l.tag=xf,uf(h,l));h.expirationTime<c&&(h.expirationTime=c);l=h.alternate;null!==l&&l.expirationTime<c&&(l.expirationTime=c);l=c;for(var m=h.return;null!==m;){var p=m.alternate;if(m.childExpirationTime<l)m.childExpirationTime=l,null!==p&&p.childExpirationTime<l&&(p.childExpirationTime=l);else if(null!==p&&p.childExpirationTime<l)p.childExpirationTime=l;else break;m=m.return}k.expirationTime<c&&(k.expirationTime= c);break}l=l.next}}else g=10===h.tag?h.type===b.type?null:h.child:h.child;if(null!==g)g.return=h;else for(g=h;null!==g;){if(g===b){g=null;break}h=g.sibling;if(null!==h){h.return=g.return;g=h;break}g=g.return}h=g}}Q(a,b,e.children,c);b=b.child}return b;case 9:return e=b.type,f=b.pendingProps,d=f.children,Rg(b,c),e=L(e,f.unstable_observedBits),d=d(e),b.effectTag|=1,Q(a,b,d,c),b.child;case 14:return e=b.type,f=K(e,b.pendingProps),f=K(e.type,f),Tg(a,b,e,f,d,c);case 15:return Ug(a,b,b.type,b.pendingProps, d,c);case 17:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:K(d,e),null!==a&&(a.alternate=null,b.alternate=null,b.effectTag|=2),b.tag=1,I(d)?(a=!0,Re(b)):a=!1,Rg(b,c),Af(b,d,e,c),Cf(b,d,e,c),Zg(null,b,d,!0,a,c)}x("156")}var dh={current:null},eh=null,fh=null,gh=null;function ch(a,b){var c=a.type._context;F(dh,c._currentValue,a);c._currentValue=b}function hh(a){var b=dh.current;E(dh,a);a.type._context._currentValue=b} function Rg(a,b){eh=a;gh=fh=null;var c=a.contextDependencies;null!==c&&c.expirationTime>=b&&(vg=!0);a.contextDependencies=null}function L(a,b){if(gh!==a&&!1!==b&&0!==b){if("number"!==typeof b||1073741823===b)gh=a,b=1073741823;b={context:a,observedBits:b,next:null};null===fh?(null===eh?x("308"):void 0,fh=b,eh.contextDependencies={first:b,expirationTime:0}):fh=fh.next=b}return a._currentValue}var ih=0,wf=1,xf=2,jh=3,Yg=!1; function kh(a){return{baseState:a,firstUpdate:null,lastUpdate:null,firstCapturedUpdate:null,lastCapturedUpdate:null,firstEffect:null,lastEffect:null,firstCapturedEffect:null,lastCapturedEffect:null}}function lh(a){return{baseState:a.baseState,firstUpdate:a.firstUpdate,lastUpdate:a.lastUpdate,firstCapturedUpdate:null,lastCapturedUpdate:null,firstEffect:null,lastEffect:null,firstCapturedEffect:null,lastCapturedEffect:null}} function sf(a){return{expirationTime:a,tag:ih,payload:null,callback:null,next:null,nextEffect:null}}function mh(a,b){null===a.lastUpdate?a.firstUpdate=a.lastUpdate=b:(a.lastUpdate.next=b,a.lastUpdate=b)} function uf(a,b){var c=a.alternate;if(null===c){var d=a.updateQueue;var e=null;null===d&&(d=a.updateQueue=kh(a.memoizedState))}else d=a.updateQueue,e=c.updateQueue,null===d?null===e?(d=a.updateQueue=kh(a.memoizedState),e=c.updateQueue=kh(c.memoizedState)):d=a.updateQueue=lh(e):null===e&&(e=c.updateQueue=lh(d));null===e||d===e?mh(d,b):null===d.lastUpdate||null===e.lastUpdate?(mh(d,b),mh(e,b)):(mh(d,b),e.lastUpdate=b)} function nh(a,b){var c=a.updateQueue;c=null===c?a.updateQueue=kh(a.memoizedState):oh(a,c);null===c.lastCapturedUpdate?c.firstCapturedUpdate=c.lastCapturedUpdate=b:(c.lastCapturedUpdate.next=b,c.lastCapturedUpdate=b)}function oh(a,b){var c=a.alternate;null!==c&&b===c.updateQueue&&(b=a.updateQueue=lh(b));return b} function ph(a,b,c,d,e,f){switch(c.tag){case wf:return a=c.payload,"function"===typeof a?a.call(f,d,e):a;case jh:a.effectTag=a.effectTag&-2049|64;case ih:a=c.payload;e="function"===typeof a?a.call(f,d,e):a;if(null===e||void 0===e)break;return n({},d,e);case xf:Yg=!0}return d} function Df(a,b,c,d,e){Yg=!1;b=oh(a,b);for(var f=b.baseState,g=null,h=0,k=b.firstUpdate,l=f;null!==k;){var m=k.expirationTime;m<e?(null===g&&(g=k,f=l),h<m&&(h=m)):(l=ph(a,b,k,l,c,d),null!==k.callback&&(a.effectTag|=32,k.nextEffect=null,null===b.lastEffect?b.firstEffect=b.lastEffect=k:(b.lastEffect.nextEffect=k,b.lastEffect=k)));k=k.next}m=null;for(k=b.firstCapturedUpdate;null!==k;){var p=k.expirationTime;p<e?(null===m&&(m=k,null===g&&(f=l)),h<p&&(h=p)):(l=ph(a,b,k,l,c,d),null!==k.callback&&(a.effectTag|= 32,k.nextEffect=null,null===b.lastCapturedEffect?b.firstCapturedEffect=b.lastCapturedEffect=k:(b.lastCapturedEffect.nextEffect=k,b.lastCapturedEffect=k)));k=k.next}null===g&&(b.lastUpdate=null);null===m?b.lastCapturedUpdate=null:a.effectTag|=32;null===g&&null===m&&(f=l);b.baseState=f;b.firstUpdate=g;b.firstCapturedUpdate=m;a.expirationTime=h;a.memoizedState=l} function qh(a,b,c){null!==b.firstCapturedUpdate&&(null!==b.lastUpdate&&(b.lastUpdate.next=b.firstCapturedUpdate,b.lastUpdate=b.lastCapturedUpdate),b.firstCapturedUpdate=b.lastCapturedUpdate=null);rh(b.firstEffect,c);b.firstEffect=b.lastEffect=null;rh(b.firstCapturedEffect,c);b.firstCapturedEffect=b.lastCapturedEffect=null}function rh(a,b){for(;null!==a;){var c=a.callback;if(null!==c){a.callback=null;var d=b;"function"!==typeof c?x("191",c):void 0;c.call(d)}a=a.nextEffect}} function sh(a,b){return{value:a,source:b,stack:mc(b)}}function th(a){a.effectTag|=4}var uh=void 0,vh=void 0,wh=void 0,xh=void 0;uh=function(a,b){for(var c=b.child;null!==c;){if(5===c.tag||6===c.tag)a.appendChild(c.stateNode);else if(4!==c.tag&&null!==c.child){c.child.return=c;c=c.child;continue}if(c===b)break;for(;null===c.sibling;){if(null===c.return||c.return===b)return;c=c.return}c.sibling.return=c.return;c=c.sibling}};vh=function(){}; wh=function(a,b,c,d,e){var f=a.memoizedProps;if(f!==d){var g=b.stateNode;Nf(M.current);a=null;switch(c){case "input":f=yc(g,f);d=yc(g,d);a=[];break;case "option":f=ce(g,f);d=ce(g,d);a=[];break;case "select":f=n({},f,{value:void 0});d=n({},d,{value:void 0});a=[];break;case "textarea":f=ee(g,f);d=ee(g,d);a=[];break;default:"function"!==typeof f.onClick&&"function"===typeof d.onClick&&(g.onclick=we)}te(c,d);g=c=void 0;var h=null;for(c in f)if(!d.hasOwnProperty(c)&&f.hasOwnProperty(c)&&null!=f[c])if("style"=== c){var k=f[c];for(g in k)k.hasOwnProperty(g)&&(h||(h={}),h[g]="")}else"dangerouslySetInnerHTML"!==c&&"children"!==c&&"suppressContentEditableWarning"!==c&&"suppressHydrationWarning"!==c&&"autoFocus"!==c&&(ra.hasOwnProperty(c)?a||(a=[]):(a=a||[]).push(c,null));for(c in d){var l=d[c];k=null!=f?f[c]:void 0;if(d.hasOwnProperty(c)&&l!==k&&(null!=l||null!=k))if("style"===c)if(k){for(g in k)!k.hasOwnProperty(g)||l&&l.hasOwnProperty(g)||(h||(h={}),h[g]="");for(g in l)l.hasOwnProperty(g)&&k[g]!==l[g]&&(h|| (h={}),h[g]=l[g])}else h||(a||(a=[]),a.push(c,h)),h=l;else"dangerouslySetInnerHTML"===c?(l=l?l.__html:void 0,k=k?k.__html:void 0,null!=l&&k!==l&&(a=a||[]).push(c,""+l)):"children"===c?k===l||"string"!==typeof l&&"number"!==typeof l||(a=a||[]).push(c,""+l):"suppressContentEditableWarning"!==c&&"suppressHydrationWarning"!==c&&(ra.hasOwnProperty(c)?(null!=l&&ve(e,c),a||k===l||(a=[])):(a=a||[]).push(c,l))}h&&(a=a||[]).push("style",h);e=a;(b.updateQueue=e)&&th(b)}};xh=function(a,b,c,d){c!==d&&th(b)}; var yh="function"===typeof WeakSet?WeakSet:Set;function zh(a,b){var c=b.source,d=b.stack;null===d&&null!==c&&(d=mc(c));null!==c&&lc(c.type);b=b.value;null!==a&&1===a.tag&&lc(a.type);try{console.error(b)}catch(e){setTimeout(function(){throw e;})}}function Ah(a){var b=a.ref;if(null!==b)if("function"===typeof b)try{b(null)}catch(c){Bh(a,c)}else b.current=null} function Ch(a,b,c){c=c.updateQueue;c=null!==c?c.lastEffect:null;if(null!==c){var d=c=c.next;do{if((d.tag&a)!==Sf){var e=d.destroy;d.destroy=void 0;void 0!==e&&e()}(d.tag&b)!==Sf&&(e=d.create,d.destroy=e());d=d.next}while(d!==c)}} function Dh(a,b){for(var c=a;;){if(5===c.tag){var d=c.stateNode;if(b)d.style.display="none";else{d=c.stateNode;var e=c.memoizedProps.style;e=void 0!==e&&null!==e&&e.hasOwnProperty("display")?e.display:null;d.style.display=qe("display",e)}}else if(6===c.tag)c.stateNode.nodeValue=b?"":c.memoizedProps;else if(13===c.tag&&null!==c.memoizedState){d=c.child.sibling;d.return=c;c=d;continue}else if(null!==c.child){c.child.return=c;c=c.child;continue}if(c===a)break;for(;null===c.sibling;){if(null===c.return|| c.return===a)return;c=c.return}c.sibling.return=c.return;c=c.sibling}} function Eh(a){"function"===typeof Ue&&Ue(a);switch(a.tag){case 0:case 11:case 14:case 15:var b=a.updateQueue;if(null!==b&&(b=b.lastEffect,null!==b)){var c=b=b.next;do{var d=c.destroy;if(void 0!==d){var e=a;try{d()}catch(f){Bh(e,f)}}c=c.next}while(c!==b)}break;case 1:Ah(a);b=a.stateNode;if("function"===typeof b.componentWillUnmount)try{b.props=a.memoizedProps,b.state=a.memoizedState,b.componentWillUnmount()}catch(f){Bh(a,f)}break;case 5:Ah(a);break;case 4:Fh(a)}} function Gh(a){return 5===a.tag||3===a.tag||4===a.tag} function Hh(a){a:{for(var b=a.return;null!==b;){if(Gh(b)){var c=b;break a}b=b.return}x("160");c=void 0}var d=b=void 0;switch(c.tag){case 5:b=c.stateNode;d=!1;break;case 3:b=c.stateNode.containerInfo;d=!0;break;case 4:b=c.stateNode.containerInfo;d=!0;break;default:x("161")}c.effectTag&16&&(ne(b,""),c.effectTag&=-17);a:b:for(c=a;;){for(;null===c.sibling;){if(null===c.return||Gh(c.return)){c=null;break a}c=c.return}c.sibling.return=c.return;for(c=c.sibling;5!==c.tag&&6!==c.tag&&18!==c.tag;){if(c.effectTag& 2)continue b;if(null===c.child||4===c.tag)continue b;else c.child.return=c,c=c.child}if(!(c.effectTag&2)){c=c.stateNode;break a}}for(var e=a;;){if(5===e.tag||6===e.tag)if(c)if(d){var f=b,g=e.stateNode,h=c;8===f.nodeType?f.parentNode.insertBefore(g,h):f.insertBefore(g,h)}else b.insertBefore(e.stateNode,c);else d?(g=b,h=e.stateNode,8===g.nodeType?(f=g.parentNode,f.insertBefore(h,g)):(f=g,f.appendChild(h)),g=g._reactRootContainer,null!==g&&void 0!==g||null!==f.onclick||(f.onclick=we)):b.appendChild(e.stateNode); else if(4!==e.tag&&null!==e.child){e.child.return=e;e=e.child;continue}if(e===a)break;for(;null===e.sibling;){if(null===e.return||e.return===a)return;e=e.return}e.sibling.return=e.return;e=e.sibling}} function Fh(a){for(var b=a,c=!1,d=void 0,e=void 0;;){if(!c){c=b.return;a:for(;;){null===c?x("160"):void 0;switch(c.tag){case 5:d=c.stateNode;e=!1;break a;case 3:d=c.stateNode.containerInfo;e=!0;break a;case 4:d=c.stateNode.containerInfo;e=!0;break a}c=c.return}c=!0}if(5===b.tag||6===b.tag){a:for(var f=b,g=f;;)if(Eh(g),null!==g.child&&4!==g.tag)g.child.return=g,g=g.child;else{if(g===f)break;for(;null===g.sibling;){if(null===g.return||g.return===f)break a;g=g.return}g.sibling.return=g.return;g=g.sibling}e? (f=d,g=b.stateNode,8===f.nodeType?f.parentNode.removeChild(g):f.removeChild(g)):d.removeChild(b.stateNode)}else if(4===b.tag){if(null!==b.child){d=b.stateNode.containerInfo;e=!0;b.child.return=b;b=b.child;continue}}else if(Eh(b),null!==b.child){b.child.return=b;b=b.child;continue}if(b===a)break;for(;null===b.sibling;){if(null===b.return||b.return===a)return;b=b.return;4===b.tag&&(c=!1)}b.sibling.return=b.return;b=b.sibling}} function Ih(a,b){switch(b.tag){case 0:case 11:case 14:case 15:Ch(Uf,Vf,b);break;case 1:break;case 5:var c=b.stateNode;if(null!=c){var d=b.memoizedProps;a=null!==a?a.memoizedProps:d;var e=b.type,f=b.updateQueue;b.updateQueue=null;null!==f&&Fe(c,f,e,a,d,b)}break;case 6:null===b.stateNode?x("162"):void 0;b.stateNode.nodeValue=b.memoizedProps;break;case 3:break;case 12:break;case 13:c=b.memoizedState;d=void 0;a=b;null===c?d=!1:(d=!0,a=b.child,0===c.timedOutAt&&(c.timedOutAt=qf()));null!==a&&Dh(a,d);c= b.updateQueue;if(null!==c){b.updateQueue=null;var g=b.stateNode;null===g&&(g=b.stateNode=new yh);c.forEach(function(a){var c=Jh.bind(null,b,a);c=v.unstable_wrap(c);g.has(a)||(g.add(a),a.then(c,c))})}break;case 17:break;default:x("163")}}var Kh="function"===typeof WeakMap?WeakMap:Map;function Lh(a,b,c){c=sf(c);c.tag=jh;c.payload={element:null};var d=b.value;c.callback=function(){Mh(d);zh(a,b)};return c} function Nh(a,b,c){c=sf(c);c.tag=jh;var d=a.type.getDerivedStateFromError;if("function"===typeof d){var e=b.value;c.payload=function(){return d(e)}}var f=a.stateNode;null!==f&&"function"===typeof f.componentDidCatch&&(c.callback=function(){"function"!==typeof d&&(null===Oh?Oh=new Set([this]):Oh.add(this));var c=b.value,e=b.stack;zh(a,b);this.componentDidCatch(c,{componentStack:null!==e?e:""})});return c} function Ph(a,b,c,d,e){c.effectTag|=1024;c.firstEffect=c.lastEffect=null;if(null!==d&&"object"===typeof d&&"function"===typeof d.then){var f=d;d=b;var g=-1,h=-1;do{if(13===d.tag){var k=d.alternate;if(null!==k&&(k=k.memoizedState,null!==k)){h=10*(1073741822-k.timedOutAt);break}k=d.pendingProps.maxDuration;if("number"===typeof k)if(0>=k)g=0;else if(-1===g||k<g)g=k}d=d.return}while(null!==d);d=b;do{if(k=13===d.tag)k=void 0===d.memoizedProps.fallback?!1:null===d.memoizedState;if(k){b=d.updateQueue;null=== b?(b=new Set,b.add(f),d.updateQueue=b):b.add(f);if(0===(d.mode&1)){d.effectTag|=64;c.effectTag&=-1957;1===c.tag&&(null===c.alternate?c.tag=17:(e=sf(1073741823),e.tag=xf,uf(c,e)));c.expirationTime=1073741823;return}c=a;b=e;var l=c.pingCache;null===l?(l=c.pingCache=new Kh,k=new Set,l.set(f,k)):(k=l.get(f),void 0===k&&(k=new Set,l.set(f,k)));k.has(b)||(k.add(b),c=Qh.bind(null,c,f,b),c=v.unstable_wrap(c),f.then(c,c));-1===g?a=1073741823:(-1===h&&(h=10*(1073741822-mf(a,e))-5E3),a=h+g);0<=a&&Rh<a&&(Rh= a);d.effectTag|=2048;d.expirationTime=e;return}d=d.return}while(null!==d);d=Error((lc(c.type)||"A React component")+" suspended while rendering, but no fallback UI was specified.\n\nAdd a <Suspense fallback=...> component higher in the tree to provide a loading indicator or placeholder to display."+mc(c))}Sh=!0;d=sh(d,c);a=b;do{switch(a.tag){case 3:a.effectTag|=2048;a.expirationTime=e;e=Lh(a,d,e);nh(a,e);return;case 1:if(g=d,h=a.type,c=a.stateNode,0===(a.effectTag&64)&&("function"===typeof h.getDerivedStateFromError|| null!==c&&"function"===typeof c.componentDidCatch&&(null===Oh||!Oh.has(c)))){a.effectTag|=2048;a.expirationTime=e;e=Nh(a,g,e);nh(a,e);return}}a=a.return}while(null!==a)} function Th(a){switch(a.tag){case 1:I(a.type)&&Ne(a);var b=a.effectTag;return b&2048?(a.effectTag=b&-2049|64,a):null;case 3:return Pf(a),Oe(a),b=a.effectTag,0!==(b&64)?x("285"):void 0,a.effectTag=b&-2049|64,a;case 5:return Rf(a),null;case 13:return b=a.effectTag,b&2048?(a.effectTag=b&-2049|64,a):null;case 18:return null;case 4:return Pf(a),null;case 10:return hh(a),null;default:return null}}var Uh=Wb.ReactCurrentDispatcher,Vh=Wb.ReactCurrentOwner; null==v.__interactionsRef||null==v.__interactionsRef.current?x("302"):void 0;var Wh=1073741822,Xh=!1,R=null,Yh=null,S=0,Rh=-1,Sh=!1,T=null,Zh=!1,$h=null,ai=null,bi=null,Oh=null;function ci(){if(null!==R)for(var a=R.return;null!==a;){var b=a;switch(b.tag){case 1:var c=b.type.childContextTypes;null!==c&&void 0!==c&&Ne(b);break;case 3:Pf(b);Oe(b);break;case 5:Rf(b);break;case 4:Pf(b);break;case 10:hh(b)}a=a.return}Yh=null;S=0;Rh=-1;Sh=!1;R=null} function di(){for(;null!==T;){var a=T.effectTag;a&16&&ne(T.stateNode,"");if(a&128){var b=T.alternate;null!==b&&(b=b.ref,null!==b&&("function"===typeof b?b(null):b.current=null))}switch(a&14){case 2:Hh(T);T.effectTag&=-3;break;case 6:Hh(T);T.effectTag&=-3;Ih(T.alternate,T);break;case 4:Ih(T.alternate,T);break;case 8:a=T,Fh(a),a.return=null,a.child=null,a.memoizedState=null,a.updateQueue=null,a=a.alternate,null!==a&&(a.return=null,a.child=null,a.memoizedState=null,a.updateQueue=null)}T=T.nextEffect}} function ei(){for(;null!==T;){if(T.effectTag&256)a:{var a=T.alternate,b=T;switch(b.tag){case 0:case 11:case 15:Ch(Tf,Sf,b);break a;case 1:if(b.effectTag&256&&null!==a){var c=a.memoizedProps,d=a.memoizedState;a=b.stateNode;b=a.getSnapshotBeforeUpdate(b.elementType===b.type?c:K(b.type,c),d);a.__reactInternalSnapshotBeforeUpdate=b}break a;case 3:case 5:case 6:case 4:case 17:break a;default:x("163")}}T=T.nextEffect}} function fi(a,b){for(;null!==T;){var c=T.effectTag;if(c&36){var d=a,e=T.alternate,f=T,g=b;switch(f.tag){case 0:case 11:case 15:Ch(Wf,Xf,f);break;case 1:d=f.stateNode;if(f.effectTag&4)if(null===e)d.componentDidMount();else{var h=f.elementType===f.type?e.memoizedProps:K(f.type,e.memoizedProps);d.componentDidUpdate(h,e.memoizedState,d.__reactInternalSnapshotBeforeUpdate)}e=f.updateQueue;null!==e&&qh(f,e,d,g);break;case 3:e=f.updateQueue;if(null!==e){d=null;if(null!==f.child)switch(f.child.tag){case 5:d= f.child.stateNode;break;case 1:d=f.child.stateNode}qh(f,e,d,g)}break;case 5:g=f.stateNode;null===e&&f.effectTag&4&&ze(f.type,f.memoizedProps)&&g.focus();break;case 6:break;case 4:break;case 12:g=f.memoizedProps.onRender;g(f.memoizedProps.id,null===e?"mount":"update",f.actualDuration,f.treeBaseDuration,f.actualStartTime,Cg,d.memoizedInteractions);break;case 13:break;case 17:break;default:x("163")}}c&128&&(f=T.ref,null!==f&&(g=T.stateNode,"function"===typeof f?f(g):f.current=g));c&512&&($h=a);T=T.nextEffect}} function gi(a,b){bi=ai=$h=null;var c=V;V=!0;do{if(b.effectTag&512){var d=!1,e=void 0;try{var f=b;Ch(Zf,Sf,f);Ch(Sf,Yf,f)}catch(g){d=!0,e=g}d&&Bh(b,e)}b=b.nextEffect}while(null!==b);V=c;c=a.expirationTime;0!==c&&hi(a,c);W||V||ii(1073741823,!1)}function tf(){null!==ai&&Ee(ai);null!==bi&&bi()} function ji(a,b){Zh=Xh=!0;a.current===b?x("177"):void 0;var c=a.pendingCommitExpirationTime;0===c?x("261"):void 0;a.pendingCommitExpirationTime=0;var d=b.expirationTime,e=b.childExpirationTime;jf(a,e>d?e:d);d=null;d=v.__interactionsRef.current;v.__interactionsRef.current=a.memoizedInteractions;Vh.current=null;e=void 0;1<b.effectTag?null!==b.lastEffect?(b.lastEffect.nextEffect=b,e=b.firstEffect):e=b:e=b.firstEffect;xe=Ed;ye=Sd();Ed=!1;for(T=e;null!==T;){var f=!1,g=void 0;try{ei()}catch(p){f=!0,g=p}f&& (null===T?x("178"):void 0,Bh(T,g),null!==T&&(T=T.nextEffect))}Cg=r.unstable_now();for(T=e;null!==T;){f=!1;g=void 0;try{di()}catch(p){f=!0,g=p}f&&(null===T?x("178"):void 0,Bh(T,g),null!==T&&(T=T.nextEffect))}Td(ye);ye=null;Ed=!!xe;xe=null;a.current=b;for(T=e;null!==T;){f=!1;g=void 0;try{fi(a,c)}catch(p){f=!0,g=p}f&&(null===T?x("178"):void 0,Bh(T,g),null!==T&&(T=T.nextEffect))}if(null!==e&&null!==$h){var h=gi.bind(null,a,e);h=v.unstable_wrap(h);ai=r.unstable_runWithPriority(r.unstable_NormalPriority, function(){return De(h)});bi=h}Xh=Zh=!1;"function"===typeof Te&&Te(b.stateNode);e=b.expirationTime;b=b.childExpirationTime;var k=b>e?b:e;0===k&&(Oh=null);ki(a,k);v.__interactionsRef.current=d;var l=void 0;try{if(l=v.__subscriberRef.current,null!==l&&0<a.memoizedInteractions.size)l.onWorkStopped(a.memoizedInteractions,1E3*c+a.interactionThreadID)}catch(p){X||(X=!0,li=p)}finally{var m=a.pendingInteractionMap;m.forEach(function(a,b){b>k&&(m.delete(b),a.forEach(function(a){a.__count--;if(null!==l&&0=== a.__count)try{l.onInteractionScheduledWorkCompleted(a)}catch(Nb){X||(X=!0,li=Nb)}}))})}} function mi(a){for(;;){var b=a.alternate,c=a.return,d=a.sibling;if(0===(a.effectTag&1024)){R=a;a.mode&4&&Eg(a);a:{var e=b;b=a;var f=S;var g=b.pendingProps;switch(b.tag){case 2:break;case 16:break;case 15:case 0:break;case 1:I(b.type)&&Ne(b);break;case 3:Pf(b);Oe(b);g=b.stateNode;g.pendingContext&&(g.context=g.pendingContext,g.pendingContext=null);if(null===e||null===e.child)Ng(b),b.effectTag&=-3;vh(b);break;case 5:Rf(b);var h=Nf(Mf.current);f=b.type;if(null!==e&&null!=b.stateNode)wh(e,b,f,g,h),e.ref!== b.ref&&(b.effectTag|=128);else if(g){var k=Nf(M.current);if(Ng(b)){g=b;e=g.stateNode;var l=g.type,m=g.memoizedProps,p=h;e[Fa]=g;e[Ga]=m;f=void 0;h=l;switch(h){case "iframe":case "object":D("load",e);break;case "video":case "audio":for(l=0;l<bb.length;l++)D(bb[l],e);break;case "source":D("error",e);break;case "img":case "image":case "link":D("error",e);D("load",e);break;case "form":D("reset",e);D("submit",e);break;case "details":D("toggle",e);break;case "input":zc(e,m);D("invalid",e);ve(p,"onChange"); break;case "select":e._wrapperState={wasMultiple:!!m.multiple};D("invalid",e);ve(p,"onChange");break;case "textarea":fe(e,m),D("invalid",e),ve(p,"onChange")}te(h,m);l=null;for(f in m)m.hasOwnProperty(f)&&(k=m[f],"children"===f?"string"===typeof k?e.textContent!==k&&(l=["children",k]):"number"===typeof k&&e.textContent!==""+k&&(l=["children",""+k]):ra.hasOwnProperty(f)&&null!=k&&ve(p,f));switch(h){case "input":Ub(e);Dc(e,m,!0);break;case "textarea":Ub(e);he(e,m);break;case "select":case "option":break; default:"function"===typeof m.onClick&&(e.onclick=we)}f=l;g.updateQueue=f;g=null!==f?!0:!1;g&&th(b)}else{m=b;p=f;e=g;l=9===h.nodeType?h:h.ownerDocument;k===ie.html&&(k=je(p));k===ie.html?"script"===p?(e=l.createElement("div"),e.innerHTML="<script>\x3c/script>",l=e.removeChild(e.firstChild)):"string"===typeof e.is?l=l.createElement(p,{is:e.is}):(l=l.createElement(p),"select"===p&&(p=l,e.multiple?p.multiple=!0:e.size&&(p.size=e.size))):l=l.createElementNS(k,p);e=l;e[Fa]=m;e[Ga]=g;uh(e,b,!1,!1);p=e; l=f;m=g;var w=h,U=ue(l,m);switch(l){case "iframe":case "object":D("load",p);h=m;break;case "video":case "audio":for(h=0;h<bb.length;h++)D(bb[h],p);h=m;break;case "source":D("error",p);h=m;break;case "img":case "image":case "link":D("error",p);D("load",p);h=m;break;case "form":D("reset",p);D("submit",p);h=m;break;case "details":D("toggle",p);h=m;break;case "input":zc(p,m);h=yc(p,m);D("invalid",p);ve(w,"onChange");break;case "option":h=ce(p,m);break;case "select":p._wrapperState={wasMultiple:!!m.multiple}; h=n({},m,{value:void 0});D("invalid",p);ve(w,"onChange");break;case "textarea":fe(p,m);h=ee(p,m);D("invalid",p);ve(w,"onChange");break;default:h=m}te(l,h);k=void 0;var Nb=l,La=p,u=h;for(k in u)if(u.hasOwnProperty(k)){var q=u[k];"style"===k?re(La,q):"dangerouslySetInnerHTML"===k?(q=q?q.__html:void 0,null!=q&&me(La,q)):"children"===k?"string"===typeof q?("textarea"!==Nb||""!==q)&&ne(La,q):"number"===typeof q&&ne(La,""+q):"suppressContentEditableWarning"!==k&&"suppressHydrationWarning"!==k&&"autoFocus"!== k&&(ra.hasOwnProperty(k)?null!=q&&ve(w,k):null!=q&&wc(La,k,q,U))}switch(l){case "input":Ub(p);Dc(p,m,!1);break;case "textarea":Ub(p);he(p,m);break;case "option":null!=m.value&&p.setAttribute("value",""+xc(m.value));break;case "select":h=p;h.multiple=!!m.multiple;p=m.value;null!=p?de(h,!!m.multiple,p,!1):null!=m.defaultValue&&de(h,!!m.multiple,m.defaultValue,!0);break;default:"function"===typeof h.onClick&&(p.onclick=we)}(g=ze(f,g))&&th(b);b.stateNode=e}null!==b.ref&&(b.effectTag|=128)}else null=== b.stateNode?x("166"):void 0;break;case 6:e&&null!=b.stateNode?xh(e,b,e.memoizedProps,g):("string"!==typeof g&&(null===b.stateNode?x("166"):void 0),e=Nf(Mf.current),Nf(M.current),Ng(b)?(g=b,f=g.stateNode,e=g.memoizedProps,f[Fa]=g,(g=f.nodeValue!==e)&&th(b)):(f=b,g=(9===e.nodeType?e:e.ownerDocument).createTextNode(g),g[Fa]=b,f.stateNode=g));break;case 11:break;case 13:g=b.memoizedState;if(0!==(b.effectTag&64)){b.expirationTime=f;R=b;break a}g=null!==g;f=null!==e&&null!==e.memoizedState;null!==e&&!g&& f&&(e=e.child.sibling,null!==e&&(h=b.firstEffect,null!==h?(b.firstEffect=e,e.nextEffect=h):(b.firstEffect=b.lastEffect=e,e.nextEffect=null),e.effectTag=8));if(g||f)b.effectTag|=4;break;case 7:break;case 8:break;case 12:break;case 4:Pf(b);vh(b);break;case 10:hh(b);break;case 9:break;case 14:break;case 17:I(b.type)&&Ne(b);break;case 18:break;default:x("156")}R=null}a.mode&4&&Fg(a,!1);b=a;if(1===S||1!==b.childExpirationTime){g=0;if(b.mode&4){f=b.actualDuration;e=b.selfBaseDuration;h=null===b.alternate|| b.child!==b.alternate.child;for(m=b.child;null!==m;)p=m.expirationTime,l=m.childExpirationTime,p>g&&(g=p),l>g&&(g=l),h&&(f+=m.actualDuration),e+=m.treeBaseDuration,m=m.sibling;b.actualDuration=f;b.treeBaseDuration=e}else for(f=b.child;null!==f;)e=f.expirationTime,h=f.childExpirationTime,e>g&&(g=e),h>g&&(g=h),f=f.sibling;b.childExpirationTime=g}if(null!==R)return R;null!==c&&0===(c.effectTag&1024)&&(null===c.firstEffect&&(c.firstEffect=a.firstEffect),null!==a.lastEffect&&(null!==c.lastEffect&&(c.lastEffect.nextEffect= a.firstEffect),c.lastEffect=a.lastEffect),1<a.effectTag&&(null!==c.lastEffect?c.lastEffect.nextEffect=a:c.firstEffect=a,c.lastEffect=a))}else{if(a.mode&4){Fg(a,!1);b=a.actualDuration;for(g=a.child;null!==g;)b+=g.actualDuration,g=g.sibling;a.actualDuration=b}a=Th(a,S);if(null!==a)return a.effectTag&=1023,a;null!==c&&(c.firstEffect=c.lastEffect=null,c.effectTag|=1024)}if(null!==d)return d;if(null!==c)a=c;else break}return null} function ni(a){var b=a.alternate;a.mode&4&&Eg(a);b=bh(b,a,S);a.memoizedProps=a.pendingProps;a.mode&4&&Fg(a,!0);null===b&&(b=mi(a));Vh.current=null;return b} function oi(a,b){Xh?x("243"):void 0;tf();Xh=!0;var c=Uh.current;Uh.current=pg;var d=a.nextExpirationTimeToWorkOn;if(d!==S||a!==Yh||null===R){ci();Yh=a;S=d;R=af(Yh.current,null,S);a.pendingCommitExpirationTime=0;var e=new Set;a.pendingInteractionMap.forEach(function(a,b){b>=d&&a.forEach(function(a){return e.add(a)})});a.memoizedInteractions=e;if(0<e.size){var f=v.__subscriberRef.current;if(null!==f){var g=1E3*d+a.interactionThreadID;try{f.onWorkStarted(e,g)}catch(l){X||(X=!0,li=l)}}}}f=null;f=v.__interactionsRef.current; v.__interactionsRef.current=a.memoizedInteractions;g=!1;do{try{if(b)for(;null!==R&&!pi();)R=ni(R);else for(;null!==R;)R=ni(R)}catch(l){if(gh=fh=eh=null,qg(),null===R)g=!0,Mh(l);else{R.mode&4&&Fg(R,!0);null===R?x("271"):void 0;var h=R,k=h.return;if(null===k)g=!0,Mh(l);else{Ph(a,k,h,l,S);R=mi(h);continue}}}break}while(1);v.__interactionsRef.current=f;Xh=!1;Uh.current=c;gh=fh=eh=null;qg();if(g)Yh=null,a.finishedWork=null;else if(null!==R)a.finishedWork=null;else{c=a.current.alternate;null===c?x("281"): void 0;Yh=null;if(Sh){if(kf(a,d)){lf(a,d);qi(a,c,d,a.expirationTime,-1);return}if(!a.didError&&b){a.didError=!0;b=a.nextExpirationTimeToWorkOn=d;f=a.expirationTime=1073741823;qi(a,c,b,f,-1);return}}b&&-1!==Rh?(lf(a,d),b=10*(1073741822-mf(a,d)),b<Rh&&(Rh=b),b=10*(1073741822-qf()),b=Rh-b,qi(a,c,d,a.expirationTime,0>b?0:b)):ri(a,c,d)}} function Bh(a,b){for(var c=a.return;null!==c;){switch(c.tag){case 1:var d=c.stateNode;if("function"===typeof c.type.getDerivedStateFromError||"function"===typeof d.componentDidCatch&&(null===Oh||!Oh.has(d))){a=sh(b,a);a=Nh(c,a,1073741823);uf(c,a);vf(c,1073741823);return}break;case 3:a=sh(b,a);a=Lh(c,a,1073741823);uf(c,a);vf(c,1073741823);return}c=c.return}3===a.tag&&(c=sh(b,a),c=Lh(a,c,1073741823),uf(a,c),vf(a,1073741823))} function rf(a,b){var c=r.unstable_getCurrentPriorityLevel(),d=void 0;if(0===(b.mode&1))d=1073741823;else if(Xh&&!Zh)d=S;else{switch(c){case r.unstable_ImmediatePriority:d=1073741823;break;case r.unstable_UserBlockingPriority:d=1073741822-10*(((1073741822-a+15)/10|0)+1);break;case r.unstable_NormalPriority:d=1073741822-25*(((1073741822-a+500)/25|0)+1);break;case r.unstable_LowPriority:case r.unstable_IdlePriority:d=1;break;default:x("313")}null!==Yh&&d===S&&--d}c===r.unstable_UserBlockingPriority&& (0===si||d<si)&&(si=d);return d}function Qh(a,b,c){var d=a.pingCache;null!==d&&d.delete(b);if(null!==Yh&&S===c)Yh=null;else if(b=a.earliestSuspendedTime,d=a.latestSuspendedTime,0!==b&&c<=b&&c>=d){a.didError=!1;b=a.latestPingedTime;if(0===b||b>c)a.latestPingedTime=c;hf(c,a);c=a.expirationTime;0!==c&&hi(a,c)}}function Jh(a,b){var c=a.stateNode;null!==c&&c.delete(b);b=qf();b=rf(b,a);a=ti(a,b);null!==a&&(gf(a,b),b=a.expirationTime,0!==b&&hi(a,b))} function ti(a,b){a.expirationTime<b&&(a.expirationTime=b);var c=a.alternate;null!==c&&c.expirationTime<b&&(c.expirationTime=b);var d=a.return,e=null;if(null===d&&3===a.tag)e=a.stateNode;else for(;null!==d;){c=d.alternate;d.childExpirationTime<b&&(d.childExpirationTime=b);null!==c&&c.childExpirationTime<b&&(c.childExpirationTime=b);if(null===d.return&&3===d.tag){e=d.stateNode;break}d=d.return}if(null!==e&&(a=v.__interactionsRef.current,0<a.size)){c=e.pendingInteractionMap;var f=c.get(b);null!=f?a.forEach(function(a){f.has(a)|| a.__count++;f.add(a)}):(c.set(b,new Set(a)),a.forEach(function(a){a.__count++}));c=v.__subscriberRef.current;if(null!==c)c.onWorkScheduled(a,1E3*b+e.interactionThreadID)}return e}function vf(a,b){a=ti(a,b);null!==a&&(!Xh&&0!==S&&b>S&&ci(),gf(a,b),Xh&&!Zh&&Yh===a||hi(a,a.expirationTime),ui>vi&&(ui=0,x("185")))}function wi(a,b,c,d,e){return r.unstable_runWithPriority(r.unstable_ImmediatePriority,function(){return a(b,c,d,e)})} var xi=null,Y=null,yi=0,zi=void 0,V=!1,Ai=null,Z=0,si=0,X=!1,li=null,W=!1,Bi=!1,Ci=null,Di=r.unstable_now(),Ei=1073741822-(Di/10|0),Fi=Ei,vi=50,ui=0,Gi=null;function Hi(){Ei=1073741822-((r.unstable_now()-Di)/10|0)}function Ii(a,b){if(0!==yi){if(b<yi)return;null!==zi&&r.unstable_cancelCallback(zi)}yi=b;a=r.unstable_now()-Di;zi=r.unstable_scheduleCallback(Ji,{timeout:10*(1073741822-b)-a})}function ri(a,b,c){a.pendingCommitExpirationTime=c;a.finishedWork=b} function qi(a,b,c,d,e){a.expirationTime=d;0!==e||pi()?0<e&&(a.timeoutHandle=Be(Ki.bind(null,a,b,c),e)):(a.pendingCommitExpirationTime=c,a.finishedWork=b)}function Ki(a,b,c){a.pendingCommitExpirationTime=c;a.finishedWork=b;Hi();Fi=Ei;Li(a,c)}function ki(a,b){a.expirationTime=b;a.finishedWork=null}function qf(){if(V)return Fi;Mi();if(0===Z||1===Z)Hi(),Fi=Ei;return Fi} function hi(a,b){null===a.nextScheduledRoot?(a.expirationTime=b,null===Y?(xi=Y=a,a.nextScheduledRoot=a):(Y=Y.nextScheduledRoot=a,Y.nextScheduledRoot=xi)):b>a.expirationTime&&(a.expirationTime=b);V||(W?Bi&&(Ai=a,Z=1073741823,Ni(a,1073741823,!1)):1073741823===b?ii(1073741823,!1):Ii(a,b))} function Mi(){var a=0,b=null;if(null!==Y)for(var c=Y,d=xi;null!==d;){var e=d.expirationTime;if(0===e){null===c||null===Y?x("244"):void 0;if(d===d.nextScheduledRoot){xi=Y=d.nextScheduledRoot=null;break}else if(d===xi)xi=e=d.nextScheduledRoot,Y.nextScheduledRoot=e,d.nextScheduledRoot=null;else if(d===Y){Y=c;Y.nextScheduledRoot=xi;d.nextScheduledRoot=null;break}else c.nextScheduledRoot=d.nextScheduledRoot,d.nextScheduledRoot=null;d=c.nextScheduledRoot}else{e>a&&(a=e,b=d);if(d===Y)break;if(1073741823=== a)break;c=d;d=d.nextScheduledRoot}}Ai=b;Z=a}var Oi=!1;function pi(){return Oi?!0:r.unstable_shouldYield()?Oi=!0:!1}function Ji(){try{if(!pi()&&null!==xi){Hi();var a=xi;do{var b=a.expirationTime;0!==b&&Ei<=b&&(a.nextExpirationTimeToWorkOn=Ei);a=a.nextScheduledRoot}while(a!==xi)}ii(0,!0)}finally{Oi=!1}} function ii(a,b){Mi();if(b)for(Hi(),Fi=Ei;null!==Ai&&0!==Z&&a<=Z&&!(Oi&&Ei>Z);)Ni(Ai,Z,Ei>Z),Mi(),Hi(),Fi=Ei;else for(;null!==Ai&&0!==Z&&a<=Z;)Ni(Ai,Z,!1),Mi();b&&(yi=0,zi=null);0!==Z&&Ii(Ai,Z);ui=0;Gi=null;if(null!==Ci)for(a=Ci,Ci=null,b=0;b<a.length;b++){var c=a[b];try{c._onComplete()}catch(d){X||(X=!0,li=d)}}if(X)throw a=li,li=null,X=!1,a;}function Li(a,b){V?x("253"):void 0;Ai=a;Z=b;Ni(a,b,!1);ii(1073741823,!1)} function Ni(a,b,c){V?x("245"):void 0;V=!0;if(c){var d=a.finishedWork;null!==d?Pi(a,d,b):(a.finishedWork=null,d=a.timeoutHandle,-1!==d&&(a.timeoutHandle=-1,Ce(d)),oi(a,c),d=a.finishedWork,null!==d&&(pi()?a.finishedWork=d:Pi(a,d,b)))}else d=a.finishedWork,null!==d?Pi(a,d,b):(a.finishedWork=null,d=a.timeoutHandle,-1!==d&&(a.timeoutHandle=-1,Ce(d)),oi(a,c),d=a.finishedWork,null!==d&&Pi(a,d,b));V=!1} function Pi(a,b,c){var d=a.firstBatch;if(null!==d&&d._expirationTime>=c&&(null===Ci?Ci=[d]:Ci.push(d),d._defer)){a.finishedWork=b;a.expirationTime=0;return}a.finishedWork=null;a===Gi?ui++:(Gi=a,ui=0);r.unstable_runWithPriority(r.unstable_ImmediatePriority,function(){ji(a,b)})}function Mh(a){null===Ai?x("246"):void 0;Ai.expirationTime=0;X||(X=!0,li=a)}function Qi(a,b){var c=W;W=!0;try{return a(b)}finally{(W=c)||V||ii(1073741823,!1)}} function Ri(a,b){if(W&&!Bi){Bi=!0;try{return a(b)}finally{Bi=!1}}return a(b)}function Si(a,b,c){W||V||0===si||(ii(si,!1),si=0);var d=W;W=!0;try{return r.unstable_runWithPriority(r.unstable_UserBlockingPriority,function(){return a(b,c)})}finally{(W=d)||V||ii(1073741823,!1)}} function Ti(a,b,c,d,e){var f=b.current;a:if(c){c=c._reactInternalFiber;b:{2===hd(c)&&1===c.tag?void 0:x("170");var g=c;do{switch(g.tag){case 3:g=g.stateNode.context;break b;case 1:if(I(g.type)){g=g.stateNode.__reactInternalMemoizedMergedChildContext;break b}}g=g.return}while(null!==g);x("171");g=void 0}if(1===c.tag){var h=c.type;if(I(h)){c=Qe(c,h,g);break a}}c=g}else c=Ke;null===b.context?b.context=c:b.pendingContext=c;b=e;e=sf(d);e.payload={element:a};b=void 0===b?null:b;null!==b&&(e.callback=b); tf();uf(f,e);vf(f,d);return d}function Ui(a,b,c,d){var e=b.current,f=qf();e=rf(f,e);return Ti(a,b,c,e,d)}function Vi(a){a=a.current;if(!a.child)return null;switch(a.child.tag){case 5:return a.child.stateNode;default:return a.child.stateNode}}function Wi(a,b,c){var d=3<arguments.length&&void 0!==arguments[3]?arguments[3]:null;return{$$typeof:Zb,key:null==d?null:""+d,children:a,containerInfo:b,implementation:c}} Cb=function(a,b,c){switch(b){case "input":Bc(a,c);b=c.name;if("radio"===c.type&&null!=b){for(c=a;c.parentNode;)c=c.parentNode;c=c.querySelectorAll("input[name="+JSON.stringify(""+b)+'][type="radio"]');for(b=0;b<c.length;b++){var d=c[b];if(d!==a&&d.form===a.form){var e=Ka(d);e?void 0:x("90");Vb(d);Bc(d,e)}}}break;case "textarea":ge(a,c);break;case "select":b=c.value,null!=b&&de(a,!!c.multiple,b,!1)}}; function Xi(a){var b=1073741822-25*(((1073741822-qf()+500)/25|0)+1);b>=Wh&&(b=Wh-1);this._expirationTime=Wh=b;this._root=a;this._callbacks=this._next=null;this._hasChildren=this._didComplete=!1;this._children=null;this._defer=!0}Xi.prototype.render=function(a){this._defer?void 0:x("250");this._hasChildren=!0;this._children=a;var b=this._root._internalRoot,c=this._expirationTime,d=new Yi;Ti(a,b,null,c,d._onCommit);return d}; Xi.prototype.then=function(a){if(this._didComplete)a();else{var b=this._callbacks;null===b&&(b=this._callbacks=[]);b.push(a)}}; Xi.prototype.commit=function(){var a=this._root._internalRoot,b=a.firstBatch;this._defer&&null!==b?void 0:x("251");if(this._hasChildren){var c=this._expirationTime;if(b!==this){this._hasChildren&&(c=this._expirationTime=b._expirationTime,this.render(this._children));for(var d=null,e=b;e!==this;)d=e,e=e._next;null===d?x("251"):void 0;d._next=e._next;this._next=b;a.firstBatch=this}this._defer=!1;Li(a,c);b=this._next;this._next=null;b=a.firstBatch=b;null!==b&&b._hasChildren&&b.render(b._children)}else this._next= null,this._defer=!1};Xi.prototype._onComplete=function(){if(!this._didComplete){this._didComplete=!0;var a=this._callbacks;if(null!==a)for(var b=0;b<a.length;b++)(0,a[b])()}};function Yi(){this._callbacks=null;this._didCommit=!1;this._onCommit=this._onCommit.bind(this)}Yi.prototype.then=function(a){if(this._didCommit)a();else{var b=this._callbacks;null===b&&(b=this._callbacks=[]);b.push(a)}}; Yi.prototype._onCommit=function(){if(!this._didCommit){this._didCommit=!0;var a=this._callbacks;if(null!==a)for(var b=0;b<a.length;b++){var c=a[b];"function"!==typeof c?x("191",c):void 0;c()}}}; function Zi(a,b,c){b=b?3:0;We&&(b|=4);b=J(3,null,null,b);a={current:b,containerInfo:a,pendingChildren:null,earliestPendingTime:0,latestPendingTime:0,earliestSuspendedTime:0,latestSuspendedTime:0,latestPingedTime:0,pingCache:null,didError:!1,pendingCommitExpirationTime:0,finishedWork:null,timeoutHandle:-1,context:null,pendingContext:null,hydrate:c,nextExpirationTimeToWorkOn:0,expirationTime:0,firstBatch:null,nextScheduledRoot:null,interactionThreadID:v.unstable_getThreadID(),memoizedInteractions:new Set, pendingInteractionMap:new Map};this._internalRoot=b.stateNode=a}Zi.prototype.render=function(a,b){var c=this._internalRoot,d=new Yi;b=void 0===b?null:b;null!==b&&d.then(b);Ui(a,c,null,d._onCommit);return d};Zi.prototype.unmount=function(a){var b=this._internalRoot,c=new Yi;a=void 0===a?null:a;null!==a&&c.then(a);Ui(null,b,null,c._onCommit);return c}; Zi.prototype.legacy_renderSubtreeIntoContainer=function(a,b,c){var d=this._internalRoot,e=new Yi;c=void 0===c?null:c;null!==c&&e.then(c);Ui(b,d,a,e._onCommit);return e};Zi.prototype.createBatch=function(){var a=new Xi(this),b=a._expirationTime,c=this._internalRoot,d=c.firstBatch;if(null===d)c.firstBatch=a,a._next=null;else{for(c=null;null!==d&&d._expirationTime>=b;)c=d,d=d._next;a._next=d;null!==c&&(c._next=a)}return a}; function $i(a){return!(!a||1!==a.nodeType&&9!==a.nodeType&&11!==a.nodeType&&(8!==a.nodeType||" react-mount-point-unstable "!==a.nodeValue))}Ib=Qi;Jb=Si;Kb=function(){V||0===si||(ii(si,!1),si=0)};function aj(a,b){b||(b=a?9===a.nodeType?a.documentElement:a.firstChild:null,b=!(!b||1!==b.nodeType||!b.hasAttribute("data-reactroot")));if(!b)for(var c;c=a.lastChild;)a.removeChild(c);return new Zi(a,!1,b)} function bj(a,b,c,d,e){var f=c._reactRootContainer;if(f){if("function"===typeof e){var g=e;e=function(){var a=Vi(f._internalRoot);g.call(a)}}null!=a?f.legacy_renderSubtreeIntoContainer(a,b,e):f.render(b,e)}else{f=c._reactRootContainer=aj(c,d);if("function"===typeof e){var h=e;e=function(){var a=Vi(f._internalRoot);h.call(a)}}Ri(function(){null!=a?f.legacy_renderSubtreeIntoContainer(a,b,e):f.render(b,e)})}return Vi(f._internalRoot)} function cj(a,b){var c=2<arguments.length&&void 0!==arguments[2]?arguments[2]:null;$i(b)?void 0:x("200");return Wi(a,b,null,c)} var ej={createPortal:cj,findDOMNode:function(a){if(null==a)return null;if(1===a.nodeType)return a;var b=a._reactInternalFiber;void 0===b&&("function"===typeof a.render?x("188"):x("268",Object.keys(a)));a=kd(b);a=null===a?null:a.stateNode;return a},hydrate:function(a,b,c){$i(b)?void 0:x("200");return bj(null,a,b,!0,c)},render:function(a,b,c){$i(b)?void 0:x("200");return bj(null,a,b,!1,c)},unstable_renderSubtreeIntoContainer:function(a,b,c,d){$i(c)?void 0:x("200");null==a||void 0===a._reactInternalFiber? x("38"):void 0;return bj(a,b,c,!1,d)},unmountComponentAtNode:function(a){$i(a)?void 0:x("40");return a._reactRootContainer?(Ri(function(){bj(null,null,a,!1,function(){a._reactRootContainer=null})}),!0):!1},unstable_createPortal:function(){return cj.apply(void 0,arguments)},unstable_batchedUpdates:Qi,unstable_interactiveUpdates:Si,flushSync:function(a,b){V?x("187"):void 0;var c=W;W=!0;try{return wi(a,b)}finally{W=c,ii(1073741823,!1)}},unstable_createRoot:dj,unstable_flushControlled:function(a){var b= W;W=!0;try{wi(a)}finally{(W=b)||V||ii(1073741823,!1)}},__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:{Events:[Ia,Ja,Ka,Ba.injectEventPluginsByName,pa,Ra,function(a){ya(a,Qa)},Gb,Hb,Gd,Da]}};function dj(a,b){$i(a)?void 0:x("299","unstable_createRoot");return new Zi(a,!0,null!=b&&!0===b.hydrate)} (function(a){var b=a.findFiberByHostInstance;return Xe(n({},a,{overrideProps:null,currentDispatcherRef:Wb.ReactCurrentDispatcher,findHostInstanceByFiber:function(a){a=kd(a);return null===a?null:a.stateNode},findFiberByHostInstance:function(a){return b?b(a):null}}))})({findFiberByHostInstance:Ha,bundleType:0,version:"16.8.6",rendererPackageName:"react-dom"});var fj={default:ej},gj=fj&&ej||fj;module.exports=gj.default||gj;
src/shared/Article/Article.js
kashisau/enroute
/** * Home.js * */ import React from 'react'; import ArticleHero from '../ArticleHero/ArticleHero'; import classnames from 'classnames'; import './Home.scss'; class Article extends React.Component { constructor(props) { super(props); this.state = { active: false, activeArticle: 0, nextArticle: undefined, sliding: false }; this.initHeroTransition = this.initHeroTransition.bind(this); } initHeroTransition(e) { if ( ! e.target.classList.contains("ArticleHero")) return; this.setState({ sliding: false }); } render() { var article = this.props.article; return <div className={ classnames( "Article", "Article-article-" + this.state.activeArticle, { "is-sliding" : this.state.sliding } ) } onTransitionEnd={this.initHeroTransition} ref={ homeContainer => this.homeContainer = homeContainer }> <ArticleHero article={article} /> </div> } } export default Article;
wp-includes/js/jquery/jquery.js
dzochowski89/WPRampUp
/*! jQuery v1.11.1 | (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={},l="1.11.1",m=function(a,b){return new m.fn.init(a,b)},n=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,o=/^-ms-/,p=/-([\da-z])/gi,q=function(a,b){return b.toUpperCase()};m.fn=m.prototype={jquery:l,constructor:m,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=m.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return m.each(this,a,b)},map:function(a){return this.pushStack(m.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},m.extend=m.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||m.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(m.isPlainObject(c)||(b=m.isArray(c)))?(b?(b=!1,f=a&&m.isArray(a)?a:[]):f=a&&m.isPlainObject(a)?a:{},g[d]=m.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},m.extend({expando:"jQuery"+(l+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===m.type(a)},isArray:Array.isArray||function(a){return"array"===m.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return!m.isArray(a)&&a-parseFloat(a)>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==m.type(a)||a.nodeType||m.isWindow(a))return!1;try{if(a.constructor&&!j.call(a,"constructor")&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(k.ownLast)for(b in a)return j.call(a,b);for(b in a);return void 0===b||j.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(b){b&&m.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(o,"ms-").replace(p,q)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=r(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(n,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(r(Object(a))?m.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(g)return g.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=r(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(f=a[b],b=a,a=f),m.isFunction(a)?(c=d.call(arguments,2),e=function(){return a.apply(b||this,c.concat(d.call(arguments)))},e.guid=a.guid=a.guid||m.guid++,e):void 0},now:function(){return+new Date},support:k}),m.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function r(a){var b=a.length,c=m.type(a);return"function"===c||m.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var s=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+-new Date,v=a.document,w=0,x=0,y=gb(),z=gb(),A=gb(),B=function(a,b){return a===b&&(l=!0),0},C="undefined",D=1<<31,E={}.hasOwnProperty,F=[],G=F.pop,H=F.push,I=F.push,J=F.slice,K=F.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},L="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",M="[\\x20\\t\\r\\n\\f]",N="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",O=N.replace("w","w#"),P="\\["+M+"*("+N+")(?:"+M+"*([*^$|!~]?=)"+M+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+O+"))|)"+M+"*\\]",Q=":("+N+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+P+")*)|.*)\\)|)",R=new RegExp("^"+M+"+|((?:^|[^\\\\])(?:\\\\.)*)"+M+"+$","g"),S=new RegExp("^"+M+"*,"+M+"*"),T=new RegExp("^"+M+"*([>+~]|"+M+")"+M+"*"),U=new RegExp("="+M+"*([^\\]'\"]*?)"+M+"*\\]","g"),V=new RegExp(Q),W=new RegExp("^"+O+"$"),X={ID:new RegExp("^#("+N+")"),CLASS:new RegExp("^\\.("+N+")"),TAG:new RegExp("^("+N.replace("w","w*")+")"),ATTR:new RegExp("^"+P),PSEUDO:new RegExp("^"+Q),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+L+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,$=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ab=/[+~]/,bb=/'|\\/g,cb=new RegExp("\\\\([\\da-f]{1,6}"+M+"?|("+M+")|.)","ig"),db=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{I.apply(F=J.call(v.childNodes),v.childNodes),F[v.childNodes.length].nodeType}catch(eb){I={apply:F.length?function(a,b){H.apply(a,J.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function fb(a,b,d,e){var f,h,j,k,l,o,r,s,w,x;if((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,d=d||[],!a||"string"!=typeof a)return d;if(1!==(k=b.nodeType)&&9!==k)return[];if(p&&!e){if(f=_.exec(a))if(j=f[1]){if(9===k){if(h=b.getElementById(j),!h||!h.parentNode)return d;if(h.id===j)return d.push(h),d}else if(b.ownerDocument&&(h=b.ownerDocument.getElementById(j))&&t(b,h)&&h.id===j)return d.push(h),d}else{if(f[2])return I.apply(d,b.getElementsByTagName(a)),d;if((j=f[3])&&c.getElementsByClassName&&b.getElementsByClassName)return I.apply(d,b.getElementsByClassName(j)),d}if(c.qsa&&(!q||!q.test(a))){if(s=r=u,w=b,x=9===k&&a,1===k&&"object"!==b.nodeName.toLowerCase()){o=g(a),(r=b.getAttribute("id"))?s=r.replace(bb,"\\$&"):b.setAttribute("id",s),s="[id='"+s+"'] ",l=o.length;while(l--)o[l]=s+qb(o[l]);w=ab.test(a)&&ob(b.parentNode)||b,x=o.join(",")}if(x)try{return I.apply(d,w.querySelectorAll(x)),d}catch(y){}finally{r||b.removeAttribute("id")}}}return i(a.replace(R,"$1"),b,d,e)}function gb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function hb(a){return a[u]=!0,a}function ib(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function jb(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function kb(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||D)-(~a.sourceIndex||D);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function lb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function mb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function nb(a){return hb(function(b){return b=+b,hb(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 ob(a){return a&&typeof a.getElementsByTagName!==C&&a}c=fb.support={},f=fb.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=fb.setDocument=function(a){var b,e=a?a.ownerDocument||a:v,g=e.defaultView;return e!==n&&9===e.nodeType&&e.documentElement?(n=e,o=e.documentElement,p=!f(e),g&&g!==g.top&&(g.addEventListener?g.addEventListener("unload",function(){m()},!1):g.attachEvent&&g.attachEvent("onunload",function(){m()})),c.attributes=ib(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ib(function(a){return a.appendChild(e.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=$.test(e.getElementsByClassName)&&ib(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=ib(function(a){return o.appendChild(a).id=u,!e.getElementsByName||!e.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if(typeof b.getElementById!==C&&p){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){var c=typeof a.getAttributeNode!==C&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==C?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!==C&&p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=$.test(e.querySelectorAll))&&(ib(function(a){a.innerHTML="<select msallowclip=''><option selected=''></option></select>",a.querySelectorAll("[msallowclip^='']").length&&q.push("[*^$]="+M+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+M+"*(?:value|"+L+")"),a.querySelectorAll(":checked").length||q.push(":checked")}),ib(function(a){var b=e.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+M+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=$.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ib(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",Q)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=$.test(o.compareDocumentPosition),t=b||$.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===e||a.ownerDocument===v&&t(v,a)?-1:b===e||b.ownerDocument===v&&t(v,b)?1:k?K.call(k,a)-K.call(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,f=a.parentNode,g=b.parentNode,h=[a],i=[b];if(!f||!g)return a===e?-1:b===e?1:f?-1:g?1:k?K.call(k,a)-K.call(k,b):0;if(f===g)return kb(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)i.unshift(c);while(h[d]===i[d])d++;return d?kb(h[d],i[d]):h[d]===v?-1:i[d]===v?1:0},e):n},fb.matches=function(a,b){return fb(a,null,null,b)},fb.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(U,"='$1']"),!(!c.matchesSelector||!p||r&&r.test(b)||q&&q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return fb(b,n,null,[a]).length>0},fb.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},fb.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&E.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},fb.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},fb.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=fb.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=fb.selectors={cacheLength:50,createPseudo:hb,match:X,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(cb,db),a[3]=(a[3]||a[4]||a[5]||"").replace(cb,db),"~="===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]||fb.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]&&fb.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return X.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&V.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(cb,db).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+M+")"+a+"("+M+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==C&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=fb.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(),s=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){k=q[u]||(q[u]={}),j=k[a]||[],n=j[0]===w&&j[1],m=j[0]===w&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[w,n,m];break}}else if(s&&(j=(b[u]||(b[u]={}))[a])&&j[0]===w)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(s&&((l[u]||(l[u]={}))[a]=[w,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||fb.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?hb(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=K.call(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:hb(function(a){var b=[],c=[],d=h(a.replace(R,"$1"));return d[u]?hb(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:hb(function(a){return function(b){return fb(a,b).length>0}}),contains:hb(function(a){return function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:hb(function(a){return W.test(a||"")||fb.error("unsupported lang: "+a),a=a.replace(cb,db).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Z.test(a.nodeName)},input:function(a){return Y.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:nb(function(){return[0]}),last:nb(function(a,b){return[b-1]}),eq:nb(function(a,b,c){return[0>c?c+b:c]}),even:nb(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:nb(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:nb(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:nb(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]=lb(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=mb(b);function pb(){}pb.prototype=d.filters=d.pseudos,d.setFilters=new pb,g=fb.tokenize=function(a,b){var c,e,f,g,h,i,j,k=z[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){(!c||(e=S.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=T.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(R," ")}),h=h.slice(c.length));for(g in d.filter)!(e=X[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?fb.error(a):z(a,i).slice(0)};function qb(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function rb(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[u]||(b[u]={}),(h=i[d])&&h[0]===w&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function sb(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 tb(a,b,c){for(var d=0,e=b.length;e>d;d++)fb(a,b[d],c);return c}function ub(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 vb(a,b,c,d,e,f){return d&&!d[u]&&(d=vb(d)),e&&!e[u]&&(e=vb(e,f)),hb(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||tb(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:ub(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=ub(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?K.call(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=ub(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):I.apply(g,r)})}function wb(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=rb(function(a){return a===b},h,!0),l=rb(function(a){return K.call(b,a)>-1},h,!0),m=[function(a,c,d){return!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d))}];f>i;i++)if(c=d.relative[a[i].type])m=[rb(sb(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return vb(i>1&&sb(m),i>1&&qb(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(R,"$1"),c,e>i&&wb(a.slice(i,e)),f>e&&wb(a=a.slice(e)),f>e&&qb(a))}m.push(c)}return sb(m)}function xb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,m,o,p=0,q="0",r=f&&[],s=[],t=j,u=f||e&&d.find.TAG("*",k),v=w+=null==t?1:Math.random()||.1,x=u.length;for(k&&(j=g!==n&&g);q!==x&&null!=(l=u[q]);q++){if(e&&l){m=0;while(o=a[m++])if(o(l,g,h)){i.push(l);break}k&&(w=v)}c&&((l=!o&&l)&&p--,f&&r.push(l))}if(p+=q,c&&q!==p){m=0;while(o=b[m++])o(r,s,g,h);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=G.call(i));s=ub(s)}I.apply(i,s),k&&!f&&s.length>0&&p+b.length>1&&fb.uniqueSort(i)}return k&&(w=v,j=t),r};return c?hb(f):f}return h=fb.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=wb(b[c]),f[u]?d.push(f):e.push(f);f=A(a,xb(e,d)),f.selector=a}return f},i=fb.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(cb,db),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=X.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(cb,db),ab.test(j[0].type)&&ob(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&qb(j),!a)return I.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,ab.test(a)&&ob(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ib(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ib(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||jb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ib(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||jb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ib(function(a){return null==a.getAttribute("disabled")})||jb(L,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),fb}(a);m.find=s,m.expr=s.selectors,m.expr[":"]=m.expr.pseudos,m.unique=s.uniqueSort,m.text=s.getText,m.isXMLDoc=s.isXML,m.contains=s.contains;var t=m.expr.match.needsContext,u=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,v=/^.[^:#\[\.,]*$/;function w(a,b,c){if(m.isFunction(b))return m.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return m.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(v.test(b))return m.filter(b,a,c);b=m.filter(b,a)}return m.grep(a,function(a){return m.inArray(a,b)>=0!==c})}m.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?m.find.matchesSelector(d,a)?[d]:[]:m.find.matches(a,m.grep(b,function(a){return 1===a.nodeType}))},m.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(m(a).filter(function(){for(b=0;e>b;b++)if(m.contains(d[b],this))return!0}));for(b=0;e>b;b++)m.find(a,d[b],c);return c=this.pushStack(e>1?m.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(w(this,a||[],!1))},not:function(a){return this.pushStack(w(this,a||[],!0))},is:function(a){return!!w(this,"string"==typeof a&&t.test(a)?m(a):a||[],!1).length}});var x,y=a.document,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=m.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||x).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof m?b[0]:b,m.merge(this,m.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:y,!0)),u.test(c[1])&&m.isPlainObject(b))for(c in b)m.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=y.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return x.find(a);this.length=1,this[0]=d}return this.context=y,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):m.isFunction(a)?"undefined"!=typeof x.ready?x.ready(a):a(m):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),m.makeArray(a,this))};A.prototype=m.fn,x=m(y);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};m.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!m(e).is(c)))1===e.nodeType&&d.push(e),e=e[b];return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),m.fn.extend({has:function(a){var b,c=m(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(m.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=t.test(a)||"string"!=typeof a?m(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&m.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?m.unique(f):f)},index:function(a){return a?"string"==typeof a?m.inArray(this[0],m(a)):m.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(m.unique(m.merge(this.get(),m(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}m.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return m.dir(a,"parentNode")},parentsUntil:function(a,b,c){return m.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return m.dir(a,"nextSibling")},prevAll:function(a){return m.dir(a,"previousSibling")},nextUntil:function(a,b,c){return m.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return m.dir(a,"previousSibling",c)},siblings:function(a){return m.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return m.sibling(a.firstChild)},contents:function(a){return m.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:m.merge([],a.childNodes)}},function(a,b){m.fn[a]=function(c,d){var e=m.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=m.filter(d,e)),this.length>1&&(C[a]||(e=m.unique(e)),B.test(a)&&(e=e.reverse())),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return m.each(a.match(E)||[],function(a,c){b[c]=!0}),b}m.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):m.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(c=a.memory&&l,d=!0,f=g||0,g=0,e=h.length,b=!0;h&&e>f;f++)if(h[f].apply(l[0],l[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,h&&(i?i.length&&j(i.shift()):c?h=[]:k.disable())},k={add:function(){if(h){var d=h.length;!function f(b){m.each(b,function(b,c){var d=m.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this},remove:function(){return h&&m.each(arguments,function(a,c){var d;while((d=m.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?m.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],e=0,this},disable:function(){return h=i=c=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,c||k.disable(),this},locked:function(){return!i},fireWith:function(a,c){return!h||d&&!i||(c=c||[],c=[a,c.slice?c.slice():c],b?i.push(c):j(c)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!d}};return k},m.extend({Deferred:function(a){var b=[["resolve","done",m.Callbacks("once memory"),"resolved"],["reject","fail",m.Callbacks("once memory"),"rejected"],["notify","progress",m.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return m.Deferred(function(c){m.each(b,function(b,f){var g=m.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&m.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?m.extend(a,d):d}},e={};return d.pipe=d.then,m.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&m.isFunction(a.promise)?e:0,g=1===f?a:m.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&m.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;m.fn.ready=function(a){return m.ready.promise().done(a),this},m.extend({isReady:!1,readyWait:1,holdReady:function(a){a?m.readyWait++:m.ready(!0)},ready:function(a){if(a===!0?!--m.readyWait:!m.isReady){if(!y.body)return setTimeout(m.ready);m.isReady=!0,a!==!0&&--m.readyWait>0||(H.resolveWith(y,[m]),m.fn.triggerHandler&&(m(y).triggerHandler("ready"),m(y).off("ready")))}}});function I(){y.addEventListener?(y.removeEventListener("DOMContentLoaded",J,!1),a.removeEventListener("load",J,!1)):(y.detachEvent("onreadystatechange",J),a.detachEvent("onload",J))}function J(){(y.addEventListener||"load"===event.type||"complete"===y.readyState)&&(I(),m.ready())}m.ready.promise=function(b){if(!H)if(H=m.Deferred(),"complete"===y.readyState)setTimeout(m.ready);else if(y.addEventListener)y.addEventListener("DOMContentLoaded",J,!1),a.addEventListener("load",J,!1);else{y.attachEvent("onreadystatechange",J),a.attachEvent("onload",J);var c=!1;try{c=null==a.frameElement&&y.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!m.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}I(),m.ready()}}()}return H.promise(b)};var K="undefined",L;for(L in m(k))break;k.ownLast="0"!==L,k.inlineBlockNeedsLayout=!1,m(function(){var a,b,c,d;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",k.inlineBlockNeedsLayout=a=3===b.offsetWidth,a&&(c.style.zoom=1)),c.removeChild(d))}),function(){var a=y.createElement("div");if(null==k.deleteExpando){k.deleteExpando=!0;try{delete a.test}catch(b){k.deleteExpando=!1}}a=null}(),m.acceptData=function(a){var b=m.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var M=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,N=/([A-Z])/g;function O(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(N,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:M.test(c)?m.parseJSON(c):c}catch(e){}m.data(a,b,c)}else c=void 0}return c}function P(a){var b;for(b in a)if(("data"!==b||!m.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;return!0}function Q(a,b,d,e){if(m.acceptData(a)){var f,g,h=m.expando,i=a.nodeType,j=i?m.cache:a,k=i?a[h]:a[h]&&h; if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||m.guid++:h),j[k]||(j[k]=i?{}:{toJSON:m.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=m.extend(j[k],b):j[k].data=m.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[m.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[m.camelCase(b)])):f=g,f}}function R(a,b,c){if(m.acceptData(a)){var d,e,f=a.nodeType,g=f?m.cache:a,h=f?a[m.expando]:m.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){m.isArray(b)?b=b.concat(m.map(b,m.camelCase)):b in d?b=[b]:(b=m.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!P(d):!m.isEmptyObject(d))return}(c||(delete g[h].data,P(g[h])))&&(f?m.cleanData([a],!0):k.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}m.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?m.cache[a[m.expando]]:a[m.expando],!!a&&!P(a)},data:function(a,b,c){return Q(a,b,c)},removeData:function(a,b){return R(a,b)},_data:function(a,b,c){return Q(a,b,c,!0)},_removeData:function(a,b){return R(a,b,!0)}}),m.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=m.data(f),1===f.nodeType&&!m._data(f,"parsedAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=m.camelCase(d.slice(5)),O(f,d,e[d])));m._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){m.data(this,a)}):arguments.length>1?this.each(function(){m.data(this,a,b)}):f?O(f,a,m.data(f,a)):void 0},removeData:function(a){return this.each(function(){m.removeData(this,a)})}}),m.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=m._data(a,b),c&&(!d||m.isArray(c)?d=m._data(a,b,m.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=m.queue(a,b),d=c.length,e=c.shift(),f=m._queueHooks(a,b),g=function(){m.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return m._data(a,c)||m._data(a,c,{empty:m.Callbacks("once memory").add(function(){m._removeData(a,b+"queue"),m._removeData(a,c)})})}}),m.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?m.queue(this[0],a):void 0===b?this:this.each(function(){var c=m.queue(this,a,b);m._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&m.dequeue(this,a)})},dequeue:function(a){return this.each(function(){m.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=m.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=m._data(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var S=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,T=["Top","Right","Bottom","Left"],U=function(a,b){return a=b||a,"none"===m.css(a,"display")||!m.contains(a.ownerDocument,a)},V=m.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===m.type(c)){e=!0;for(h in c)m.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,m.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(m(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},W=/^(?:checkbox|radio)$/i;!function(){var a=y.createElement("input"),b=y.createElement("div"),c=y.createDocumentFragment();if(b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",k.leadingWhitespace=3===b.firstChild.nodeType,k.tbody=!b.getElementsByTagName("tbody").length,k.htmlSerialize=!!b.getElementsByTagName("link").length,k.html5Clone="<:nav></:nav>"!==y.createElement("nav").cloneNode(!0).outerHTML,a.type="checkbox",a.checked=!0,c.appendChild(a),k.appendChecked=a.checked,b.innerHTML="<textarea>x</textarea>",k.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,c.appendChild(b),b.innerHTML="<input type='radio' checked='checked' name='t'/>",k.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,k.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){k.noCloneEvent=!1}),b.cloneNode(!0).click()),null==k.deleteExpando){k.deleteExpando=!0;try{delete b.test}catch(d){k.deleteExpando=!1}}}(),function(){var b,c,d=y.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(k[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),k[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var X=/^(?:input|select|textarea)$/i,Y=/^key/,Z=/^(?:mouse|pointer|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=/^([^.]*)(?:\.(.+)|)$/;function ab(){return!0}function bb(){return!1}function cb(){try{return y.activeElement}catch(a){}}m.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=m.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof m===K||a&&m.event.triggered===a.type?void 0:m.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(E)||[""],h=b.length;while(h--)f=_.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=m.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=m.event.special[o]||{},l=m.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&m.expr.match.needsContext.test(e),namespace:p.join(".")},i),(n=g[o])||(n=g[o]=[],n.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?n.splice(n.delegateCount++,0,l):n.push(l),m.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m.hasData(a)&&m._data(a);if(r&&(k=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=_.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=m.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,n=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=n.length;while(f--)g=n[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(n.splice(f,1),g.selector&&n.delegateCount--,l.remove&&l.remove.call(a,g));i&&!n.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||m.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)m.event.remove(a,o+b[j],c,d,!0);m.isEmptyObject(k)&&(delete r.handle,m._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,n,o=[d||y],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||y,3!==d.nodeType&&8!==d.nodeType&&!$.test(p+m.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[m.expando]?b:new m.Event(p,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=q.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:m.makeArray(c,[b]),k=m.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!m.isWindow(d)){for(i=k.delegateType||p,$.test(i+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||y)&&o.push(l.defaultView||l.parentWindow||a)}n=0;while((h=o[n++])&&!b.isPropagationStopped())b.type=n>1?i:k.bindType||p,f=(m._data(h,"events")||{})[b.type]&&m._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&m.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=p,!e&&!b.isDefaultPrevented()&&(!k._default||k._default.apply(o.pop(),c)===!1)&&m.acceptData(d)&&g&&d[p]&&!m.isWindow(d)){l=d[g],l&&(d[g]=null),m.event.triggered=p;try{d[p]()}catch(r){}m.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=m.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(m._data(this,"events")||{})[a.type]||[],k=m.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=m.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,g=0;while((e=f.handlers[g++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,c=((m.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),void 0!==c&&(a.result=c)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(e=[],f=0;h>f;f++)d=b[f],c=d.selector+" ",void 0===e[c]&&(e[c]=d.needsContext?m(c,this).index(i)>=0:m.find(c,this,null,[i]).length),e[c]&&e.push(d);e.length&&g.push({elem:i,handlers:e})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},fix:function(a){if(a[m.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=Z.test(e)?this.mouseHooks:Y.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new m.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=f.srcElement||y),3===a.target.nodeType&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,g.filter?g.filter(a,f):a},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,d,e,f=b.button,g=b.fromElement;return null==a.pageX&&null!=b.clientX&&(d=a.target.ownerDocument||y,e=d.documentElement,c=d.body,a.pageX=b.clientX+(e&&e.scrollLeft||c&&c.scrollLeft||0)-(e&&e.clientLeft||c&&c.clientLeft||0),a.pageY=b.clientY+(e&&e.scrollTop||c&&c.scrollTop||0)-(e&&e.clientTop||c&&c.clientTop||0)),!a.relatedTarget&&g&&(a.relatedTarget=g===a.target?b.toElement:g),a.which||void 0===f||(a.which=1&f?1:2&f?3:4&f?2:0),a}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==cb()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===cb()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return m.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(a){return m.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&a.originalEvent&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c,d){var e=m.extend(new m.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?m.event.trigger(e,null,b):m.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},m.removeEvent=y.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]===K&&(a[d]=null),a.detachEvent(d,c))},m.Event=function(a,b){return this instanceof m.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.returnValue===!1?ab:bb):this.type=a,b&&m.extend(this,b),this.timeStamp=a&&a.timeStamp||m.now(),void(this[m.expando]=!0)):new m.Event(a,b)},m.Event.prototype={isDefaultPrevented:bb,isPropagationStopped:bb,isImmediatePropagationStopped:bb,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=ab,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=ab,a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=ab,a&&a.stopImmediatePropagation&&a.stopImmediatePropagation(),this.stopPropagation()}},m.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(a,b){m.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!m.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),k.submitBubbles||(m.event.special.submit={setup:function(){return m.nodeName(this,"form")?!1:void m.event.add(this,"click._submit keypress._submit",function(a){var b=a.target,c=m.nodeName(b,"input")||m.nodeName(b,"button")?b.form:void 0;c&&!m._data(c,"submitBubbles")&&(m.event.add(c,"submit._submit",function(a){a._submit_bubble=!0}),m._data(c,"submitBubbles",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&m.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){return m.nodeName(this,"form")?!1:void m.event.remove(this,"._submit")}}),k.changeBubbles||(m.event.special.change={setup:function(){return X.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(m.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._just_changed=!0)}),m.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),m.event.simulate("change",this,a,!0)})),!1):void m.event.add(this,"beforeactivate._change",function(a){var b=a.target;X.test(b.nodeName)&&!m._data(b,"changeBubbles")&&(m.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||m.event.simulate("change",this.parentNode,a,!0)}),m._data(b,"changeBubbles",!0))})},handle:function(a){var b=a.target;return this!==b||a.isSimulated||a.isTrigger||"radio"!==b.type&&"checkbox"!==b.type?a.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return m.event.remove(this,"._change"),!X.test(this.nodeName)}}),k.focusinBubbles||m.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){m.event.simulate(b,a.target,m.event.fix(a),!0)};m.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=m._data(d,b);e||d.addEventListener(a,c,!0),m._data(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=m._data(d,b)-1;e?m._data(d,b,e):(d.removeEventListener(a,c,!0),m._removeData(d,b))}}}),m.fn.extend({on:function(a,b,c,d,e){var f,g;if("object"==typeof a){"string"!=typeof b&&(c=c||b,b=void 0);for(f in a)this.on(f,b,c,a[f],e);return this}if(null==c&&null==d?(d=b,c=b=void 0):null==d&&("string"==typeof b?(d=c,c=void 0):(d=c,c=b,b=void 0)),d===!1)d=bb;else if(!d)return this;return 1===e&&(g=d,d=function(a){return m().off(a),g.apply(this,arguments)},d.guid=g.guid||(g.guid=m.guid++)),this.each(function(){m.event.add(this,a,d,c,b)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,m(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return(b===!1||"function"==typeof b)&&(c=b,b=void 0),c===!1&&(c=bb),this.each(function(){m.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){m.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?m.event.trigger(a,b,c,!0):void 0}});function db(a){var b=eb.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}var eb="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",fb=/ jQuery\d+="(?:null|\d+)"/g,gb=new RegExp("<(?:"+eb+")[\\s/>]","i"),hb=/^\s+/,ib=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,jb=/<([\w:]+)/,kb=/<tbody/i,lb=/<|&#?\w+;/,mb=/<(?:script|style|link)/i,nb=/checked\s*(?:[^=]|=\s*.checked.)/i,ob=/^$|\/(?:java|ecma)script/i,pb=/^true\/(.*)/,qb=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,rb={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:k.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},sb=db(y),tb=sb.appendChild(y.createElement("div"));rb.optgroup=rb.option,rb.tbody=rb.tfoot=rb.colgroup=rb.caption=rb.thead,rb.th=rb.td;function ub(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==K?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==K?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||m.nodeName(d,b)?f.push(d):m.merge(f,ub(d,b));return void 0===b||b&&m.nodeName(a,b)?m.merge([a],f):f}function vb(a){W.test(a.type)&&(a.defaultChecked=a.checked)}function wb(a,b){return m.nodeName(a,"table")&&m.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function xb(a){return a.type=(null!==m.find.attr(a,"type"))+"/"+a.type,a}function yb(a){var b=pb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function zb(a,b){for(var c,d=0;null!=(c=a[d]);d++)m._data(c,"globalEval",!b||m._data(b[d],"globalEval"))}function Ab(a,b){if(1===b.nodeType&&m.hasData(a)){var c,d,e,f=m._data(a),g=m._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)m.event.add(b,c,h[c][d])}g.data&&(g.data=m.extend({},g.data))}}function Bb(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!k.noCloneEvent&&b[m.expando]){e=m._data(b);for(d in e.events)m.removeEvent(b,d,e.handle);b.removeAttribute(m.expando)}"script"===c&&b.text!==a.text?(xb(b).text=a.text,yb(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),k.html5Clone&&a.innerHTML&&!m.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&W.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}m.extend({clone:function(a,b,c){var d,e,f,g,h,i=m.contains(a.ownerDocument,a);if(k.html5Clone||m.isXMLDoc(a)||!gb.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(tb.innerHTML=a.outerHTML,tb.removeChild(f=tb.firstChild)),!(k.noCloneEvent&&k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||m.isXMLDoc(a)))for(d=ub(f),h=ub(a),g=0;null!=(e=h[g]);++g)d[g]&&Bb(e,d[g]);if(b)if(c)for(h=h||ub(a),d=d||ub(f),g=0;null!=(e=h[g]);g++)Ab(e,d[g]);else Ab(a,f);return d=ub(f,"script"),d.length>0&&zb(d,!i&&ub(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,l,n=a.length,o=db(b),p=[],q=0;n>q;q++)if(f=a[q],f||0===f)if("object"===m.type(f))m.merge(p,f.nodeType?[f]:f);else if(lb.test(f)){h=h||o.appendChild(b.createElement("div")),i=(jb.exec(f)||["",""])[1].toLowerCase(),l=rb[i]||rb._default,h.innerHTML=l[1]+f.replace(ib,"<$1></$2>")+l[2],e=l[0];while(e--)h=h.lastChild;if(!k.leadingWhitespace&&hb.test(f)&&p.push(b.createTextNode(hb.exec(f)[0])),!k.tbody){f="table"!==i||kb.test(f)?"<table>"!==l[1]||kb.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)m.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}m.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),k.appendChecked||m.grep(ub(p,"input"),vb),q=0;while(f=p[q++])if((!d||-1===m.inArray(f,d))&&(g=m.contains(f.ownerDocument,f),h=ub(o.appendChild(f),"script"),g&&zb(h),c)){e=0;while(f=h[e++])ob.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=m.expando,j=m.cache,l=k.deleteExpando,n=m.event.special;null!=(d=a[h]);h++)if((b||m.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)n[e]?m.event.remove(d,e):m.removeEvent(d,e,g.handle);j[f]&&(delete j[f],l?delete d[i]:typeof d.removeAttribute!==K?d.removeAttribute(i):d[i]=null,c.push(f))}}}),m.fn.extend({text:function(a){return V(this,function(a){return void 0===a?m.text(this):this.empty().append((this[0]&&this[0].ownerDocument||y).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wb(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=wb(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?m.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||m.cleanData(ub(c)),c.parentNode&&(b&&m.contains(c.ownerDocument,c)&&zb(ub(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&m.cleanData(ub(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&m.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return m.clone(this,a,b)})},html:function(a){return V(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(fb,""):void 0;if(!("string"!=typeof a||mb.test(a)||!k.htmlSerialize&&gb.test(a)||!k.leadingWhitespace&&hb.test(a)||rb[(jb.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(ib,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(m.cleanData(ub(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,m.cleanData(ub(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,l=this.length,n=this,o=l-1,p=a[0],q=m.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&nb.test(p))return this.each(function(c){var d=n.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(i=m.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=m.map(ub(i,"script"),xb),f=g.length;l>j;j++)d=i,j!==o&&(d=m.clone(d,!0,!0),f&&m.merge(g,ub(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,m.map(g,yb),j=0;f>j;j++)d=g[j],ob.test(d.type||"")&&!m._data(d,"globalEval")&&m.contains(h,d)&&(d.src?m._evalUrl&&m._evalUrl(d.src):m.globalEval((d.text||d.textContent||d.innerHTML||"").replace(qb,"")));i=c=null}return this}}),m.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){m.fn[a]=function(a){for(var c,d=0,e=[],g=m(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),m(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Cb,Db={};function Eb(b,c){var d,e=m(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:m.css(e[0],"display");return e.detach(),f}function Fb(a){var b=y,c=Db[a];return c||(c=Eb(a,b),"none"!==c&&c||(Cb=(Cb||m("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=(Cb[0].contentWindow||Cb[0].contentDocument).document,b.write(),b.close(),c=Eb(a,b),Cb.detach()),Db[a]=c),c}!function(){var a;k.shrinkWrapBlocks=function(){if(null!=a)return a;a=!1;var b,c,d;return c=y.getElementsByTagName("body")[0],c&&c.style?(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:1px;width:1px;zoom:1",b.appendChild(y.createElement("div")).style.width="5px",a=3!==b.offsetWidth),c.removeChild(d),a):void 0}}();var Gb=/^margin/,Hb=new RegExp("^("+S+")(?!px)[a-z%]+$","i"),Ib,Jb,Kb=/^(top|right|bottom|left)$/;a.getComputedStyle?(Ib=function(a){return a.ownerDocument.defaultView.getComputedStyle(a,null)},Jb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ib(a),g=c?c.getPropertyValue(b)||c[b]:void 0,c&&(""!==g||m.contains(a.ownerDocument,a)||(g=m.style(a,b)),Hb.test(g)&&Gb.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0===g?g:g+""}):y.documentElement.currentStyle&&(Ib=function(a){return a.currentStyle},Jb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ib(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),Hb.test(g)&&!Kb.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 Lb(a,b){return{get:function(){var c=a();if(null!=c)return c?void delete this.get:(this.get=b).apply(this,arguments)}}}!function(){var b,c,d,e,f,g,h;if(b=y.createElement("div"),b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=d&&d.style){c.cssText="float:left;opacity:.5",k.opacity="0.5"===c.opacity,k.cssFloat=!!c.cssFloat,b.style.backgroundClip="content-box",b.cloneNode(!0).style.backgroundClip="",k.clearCloneStyle="content-box"===b.style.backgroundClip,k.boxSizing=""===c.boxSizing||""===c.MozBoxSizing||""===c.WebkitBoxSizing,m.extend(k,{reliableHiddenOffsets:function(){return null==g&&i(),g},boxSizingReliable:function(){return null==f&&i(),f},pixelPosition:function(){return null==e&&i(),e},reliableMarginRight:function(){return null==h&&i(),h}});function i(){var b,c,d,i;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),b.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;display:block;margin-top:1%;top:1%;border:1px;padding:1px;width:4px;position:absolute",e=f=!1,h=!0,a.getComputedStyle&&(e="1%"!==(a.getComputedStyle(b,null)||{}).top,f="4px"===(a.getComputedStyle(b,null)||{width:"4px"}).width,i=b.appendChild(y.createElement("div")),i.style.cssText=b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",i.style.marginRight=i.style.width="0",b.style.width="1px",h=!parseFloat((a.getComputedStyle(i,null)||{}).marginRight)),b.innerHTML="<table><tr><td></td><td>t</td></tr></table>",i=b.getElementsByTagName("td"),i[0].style.cssText="margin:0;border:0;padding:0;display:none",g=0===i[0].offsetHeight,g&&(i[0].style.display="",i[1].style.display="none",g=0===i[0].offsetHeight),c.removeChild(d))}}}(),m.swap=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};var Mb=/alpha\([^)]*\)/i,Nb=/opacity\s*=\s*([^)]*)/,Ob=/^(none|table(?!-c[ea]).+)/,Pb=new RegExp("^("+S+")(.*)$","i"),Qb=new RegExp("^([+-])=("+S+")","i"),Rb={position:"absolute",visibility:"hidden",display:"block"},Sb={letterSpacing:"0",fontWeight:"400"},Tb=["Webkit","O","Moz","ms"];function Ub(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=Tb.length;while(e--)if(b=Tb[e]+c,b in a)return b;return d}function Vb(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=m._data(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&U(d)&&(f[g]=m._data(d,"olddisplay",Fb(d.nodeName)))):(e=U(d),(c&&"none"!==c||!e)&&m._data(d,"olddisplay",e?c:m.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}function Wb(a,b,c){var d=Pb.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Xb(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=m.css(a,c+T[f],!0,e)),d?("content"===c&&(g-=m.css(a,"padding"+T[f],!0,e)),"margin"!==c&&(g-=m.css(a,"border"+T[f]+"Width",!0,e))):(g+=m.css(a,"padding"+T[f],!0,e),"padding"!==c&&(g+=m.css(a,"border"+T[f]+"Width",!0,e)));return g}function Yb(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Ib(a),g=k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Jb(a,b,f),(0>e||null==e)&&(e=a.style[b]),Hb.test(e))return e;d=g&&(k.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Xb(a,b,c||(g?"border":"content"),d,f)+"px"}m.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Jb(a,"opacity");return""===c?"1":c}}}},cssNumber:{columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":k.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=m.camelCase(b),i=a.style;if(b=m.cssProps[h]||(m.cssProps[h]=Ub(i,h)),g=m.cssHooks[b]||m.cssHooks[h],void 0===c)return g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b];if(f=typeof c,"string"===f&&(e=Qb.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(m.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||m.cssNumber[h]||(c+="px"),k.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),!(g&&"set"in g&&void 0===(c=g.set(a,c,d)))))try{i[b]=c}catch(j){}}},css:function(a,b,c,d){var e,f,g,h=m.camelCase(b);return b=m.cssProps[h]||(m.cssProps[h]=Ub(a.style,h)),g=m.cssHooks[b]||m.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=Jb(a,b,d)),"normal"===f&&b in Sb&&(f=Sb[b]),""===c||c?(e=parseFloat(f),c===!0||m.isNumeric(e)?e||0:f):f}}),m.each(["height","width"],function(a,b){m.cssHooks[b]={get:function(a,c,d){return c?Ob.test(m.css(a,"display"))&&0===a.offsetWidth?m.swap(a,Rb,function(){return Yb(a,b,d)}):Yb(a,b,d):void 0},set:function(a,c,d){var e=d&&Ib(a);return Wb(a,c,d?Xb(a,b,d,k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,e),e):0)}}}),k.opacity||(m.cssHooks.opacity={get:function(a,b){return Nb.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=m.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,(b>=1||""===b)&&""===m.trim(f.replace(Mb,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Mb.test(f)?f.replace(Mb,e):f+" "+e)}}),m.cssHooks.marginRight=Lb(k.reliableMarginRight,function(a,b){return b?m.swap(a,{display:"inline-block"},Jb,[a,"marginRight"]):void 0}),m.each({margin:"",padding:"",border:"Width"},function(a,b){m.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+T[d]+b]=f[d]||f[d-2]||f[0];return e}},Gb.test(a)||(m.cssHooks[a+b].set=Wb)}),m.fn.extend({css:function(a,b){return V(this,function(a,b,c){var d,e,f={},g=0;if(m.isArray(b)){for(d=Ib(a),e=b.length;e>g;g++)f[b[g]]=m.css(a,b[g],!1,d);return f}return void 0!==c?m.style(a,b,c):m.css(a,b)},a,b,arguments.length>1)},show:function(){return Vb(this,!0)},hide:function(){return Vb(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){U(this)?m(this).show():m(this).hide()})}});function Zb(a,b,c,d,e){return new Zb.prototype.init(a,b,c,d,e)}m.Tween=Zb,Zb.prototype={constructor:Zb,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(m.cssNumber[c]?"":"px") },cur:function(){var a=Zb.propHooks[this.prop];return a&&a.get?a.get(this):Zb.propHooks._default.get(this)},run:function(a){var b,c=Zb.propHooks[this.prop];return this.pos=b=this.options.duration?m.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):Zb.propHooks._default.set(this),this}},Zb.prototype.init.prototype=Zb.prototype,Zb.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=m.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){m.fx.step[a.prop]?m.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[m.cssProps[a.prop]]||m.cssHooks[a.prop])?m.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},Zb.propHooks.scrollTop=Zb.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},m.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},m.fx=Zb.prototype.init,m.fx.step={};var $b,_b,ac=/^(?:toggle|show|hide)$/,bc=new RegExp("^(?:([+-])=|)("+S+")([a-z%]*)$","i"),cc=/queueHooks$/,dc=[ic],ec={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=bc.exec(b),f=e&&e[3]||(m.cssNumber[a]?"":"px"),g=(m.cssNumber[a]||"px"!==f&&+d)&&bc.exec(m.css(c.elem,a)),h=1,i=20;if(g&&g[3]!==f){f=f||g[3],e=e||[],g=+d||1;do h=h||".5",g/=h,m.style(c.elem,a,g+f);while(h!==(h=c.cur()/d)&&1!==h&&--i)}return e&&(g=c.start=+g||+d||0,c.unit=f,c.end=e[1]?g+(e[1]+1)*e[2]:+e[2]),c}]};function fc(){return setTimeout(function(){$b=void 0}),$b=m.now()}function gc(a,b){var c,d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b)c=T[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function hc(a,b,c){for(var d,e=(ec[b]||[]).concat(ec["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function ic(a,b,c){var d,e,f,g,h,i,j,l,n=this,o={},p=a.style,q=a.nodeType&&U(a),r=m._data(a,"fxshow");c.queue||(h=m._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,n.always(function(){n.always(function(){h.unqueued--,m.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[p.overflow,p.overflowX,p.overflowY],j=m.css(a,"display"),l="none"===j?m._data(a,"olddisplay")||Fb(a.nodeName):j,"inline"===l&&"none"===m.css(a,"float")&&(k.inlineBlockNeedsLayout&&"inline"!==Fb(a.nodeName)?p.zoom=1:p.display="inline-block")),c.overflow&&(p.overflow="hidden",k.shrinkWrapBlocks()||n.always(function(){p.overflow=c.overflow[0],p.overflowX=c.overflow[1],p.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],ac.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(q?"hide":"show")){if("show"!==e||!r||void 0===r[d])continue;q=!0}o[d]=r&&r[d]||m.style(a,d)}else j=void 0;if(m.isEmptyObject(o))"inline"===("none"===j?Fb(a.nodeName):j)&&(p.display=j);else{r?"hidden"in r&&(q=r.hidden):r=m._data(a,"fxshow",{}),f&&(r.hidden=!q),q?m(a).show():n.done(function(){m(a).hide()}),n.done(function(){var b;m._removeData(a,"fxshow");for(b in o)m.style(a,b,o[b])});for(d in o)g=hc(q?r[d]:0,d,n),d in r||(r[d]=g.start,q&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function jc(a,b){var c,d,e,f,g;for(c in a)if(d=m.camelCase(c),e=b[d],f=a[c],m.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=m.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function kc(a,b,c){var d,e,f=0,g=dc.length,h=m.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=$b||fc(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:m.extend({},b),opts:m.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:$b||fc(),duration:c.duration,tweens:[],createTween:function(b,c){var d=m.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;for(jc(k,j.opts.specialEasing);g>f;f++)if(d=dc[f].call(j,a,k,j.opts))return d;return m.map(k,hc,j),m.isFunction(j.opts.start)&&j.opts.start.call(a,j),m.fx.timer(m.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}m.Animation=m.extend(kc,{tweener:function(a,b){m.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],ec[c]=ec[c]||[],ec[c].unshift(b)},prefilter:function(a,b){b?dc.unshift(a):dc.push(a)}}),m.speed=function(a,b,c){var d=a&&"object"==typeof a?m.extend({},a):{complete:c||!c&&b||m.isFunction(a)&&a,duration:a,easing:c&&b||b&&!m.isFunction(b)&&b};return d.duration=m.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in m.fx.speeds?m.fx.speeds[d.duration]:m.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){m.isFunction(d.old)&&d.old.call(this),d.queue&&m.dequeue(this,d.queue)},d},m.fn.extend({fadeTo:function(a,b,c,d){return this.filter(U).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=m.isEmptyObject(a),f=m.speed(b,c,d),g=function(){var b=kc(this,m.extend({},a),f);(e||m._data(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=m.timers,g=m._data(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&cc.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));(b||!c)&&m.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=m._data(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=m.timers,g=d?d.length:0;for(c.finish=!0,m.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),m.each(["toggle","show","hide"],function(a,b){var c=m.fn[b];m.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(gc(b,!0),a,d,e)}}),m.each({slideDown:gc("show"),slideUp:gc("hide"),slideToggle:gc("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){m.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),m.timers=[],m.fx.tick=function(){var a,b=m.timers,c=0;for($b=m.now();c<b.length;c++)a=b[c],a()||b[c]!==a||b.splice(c--,1);b.length||m.fx.stop(),$b=void 0},m.fx.timer=function(a){m.timers.push(a),a()?m.fx.start():m.timers.pop()},m.fx.interval=13,m.fx.start=function(){_b||(_b=setInterval(m.fx.tick,m.fx.interval))},m.fx.stop=function(){clearInterval(_b),_b=null},m.fx.speeds={slow:600,fast:200,_default:400},m.fn.delay=function(a,b){return a=m.fx?m.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},function(){var a,b,c,d,e;b=y.createElement("div"),b.setAttribute("className","t"),b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=y.createElement("select"),e=c.appendChild(y.createElement("option")),a=b.getElementsByTagName("input")[0],d.style.cssText="top:1px",k.getSetAttribute="t"!==b.className,k.style=/top/.test(d.getAttribute("style")),k.hrefNormalized="/a"===d.getAttribute("href"),k.checkOn=!!a.value,k.optSelected=e.selected,k.enctype=!!y.createElement("form").enctype,c.disabled=!0,k.optDisabled=!e.disabled,a=y.createElement("input"),a.setAttribute("value",""),k.input=""===a.getAttribute("value"),a.value="t",a.setAttribute("type","radio"),k.radioValue="t"===a.value}();var lc=/\r/g;m.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=m.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,m(this).val()):a,null==e?e="":"number"==typeof e?e+="":m.isArray(e)&&(e=m.map(e,function(a){return null==a?"":a+""})),b=m.valHooks[this.type]||m.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=m.valHooks[e.type]||m.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(lc,""):null==c?"":c)}}}),m.extend({valHooks:{option:{get:function(a){var b=m.find.attr(a,"value");return null!=b?b:m.trim(m.text(a))}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],!(!c.selected&&i!==e||(k.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&m.nodeName(c.parentNode,"optgroup"))){if(b=m(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=m.makeArray(b),g=e.length;while(g--)if(d=e[g],m.inArray(m.valHooks.option.get(d),f)>=0)try{d.selected=c=!0}catch(h){d.scrollHeight}else d.selected=!1;return c||(a.selectedIndex=-1),e}}}}),m.each(["radio","checkbox"],function(){m.valHooks[this]={set:function(a,b){return m.isArray(b)?a.checked=m.inArray(m(a).val(),b)>=0:void 0}},k.checkOn||(m.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var mc,nc,oc=m.expr.attrHandle,pc=/^(?:checked|selected)$/i,qc=k.getSetAttribute,rc=k.input;m.fn.extend({attr:function(a,b){return V(this,m.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){m.removeAttr(this,a)})}}),m.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===K?m.prop(a,b,c):(1===f&&m.isXMLDoc(a)||(b=b.toLowerCase(),d=m.attrHooks[b]||(m.expr.match.bool.test(b)?nc:mc)),void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=m.find.attr(a,b),null==e?void 0:e):null!==c?d&&"set"in d&&void 0!==(e=d.set(a,c,b))?e:(a.setAttribute(b,c+""),c):void m.removeAttr(a,b))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(E);if(f&&1===a.nodeType)while(c=f[e++])d=m.propFix[c]||c,m.expr.match.bool.test(c)?rc&&qc||!pc.test(c)?a[d]=!1:a[m.camelCase("default-"+c)]=a[d]=!1:m.attr(a,c,""),a.removeAttribute(qc?c:d)},attrHooks:{type:{set:function(a,b){if(!k.radioValue&&"radio"===b&&m.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),nc={set:function(a,b,c){return b===!1?m.removeAttr(a,c):rc&&qc||!pc.test(c)?a.setAttribute(!qc&&m.propFix[c]||c,c):a[m.camelCase("default-"+c)]=a[c]=!0,c}},m.each(m.expr.match.bool.source.match(/\w+/g),function(a,b){var c=oc[b]||m.find.attr;oc[b]=rc&&qc||!pc.test(b)?function(a,b,d){var e,f;return d||(f=oc[b],oc[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,oc[b]=f),e}:function(a,b,c){return c?void 0:a[m.camelCase("default-"+b)]?b.toLowerCase():null}}),rc&&qc||(m.attrHooks.value={set:function(a,b,c){return m.nodeName(a,"input")?void(a.defaultValue=b):mc&&mc.set(a,b,c)}}),qc||(mc={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}},oc.id=oc.name=oc.coords=function(a,b,c){var d;return c?void 0:(d=a.getAttributeNode(b))&&""!==d.value?d.value:null},m.valHooks.button={get:function(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:void 0},set:mc.set},m.attrHooks.contenteditable={set:function(a,b,c){mc.set(a,""===b?!1:b,c)}},m.each(["width","height"],function(a,b){m.attrHooks[b]={set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}}})),k.style||(m.attrHooks.style={get:function(a){return a.style.cssText||void 0},set:function(a,b){return a.style.cssText=b+""}});var sc=/^(?:input|select|textarea|button|object)$/i,tc=/^(?:a|area)$/i;m.fn.extend({prop:function(a,b){return V(this,m.prop,a,b,arguments.length>1)},removeProp:function(a){return a=m.propFix[a]||a,this.each(function(){try{this[a]=void 0,delete this[a]}catch(b){}})}}),m.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(a,b,c){var d,e,f,g=a.nodeType;if(a&&3!==g&&8!==g&&2!==g)return f=1!==g||!m.isXMLDoc(a),f&&(b=m.propFix[b]||b,e=m.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=m.find.attr(a,"tabindex");return b?parseInt(b,10):sc.test(a.nodeName)||tc.test(a.nodeName)&&a.href?0:-1}}}}),k.hrefNormalized||m.each(["href","src"],function(a,b){m.propHooks[b]={get:function(a){return a.getAttribute(b,4)}}}),k.optSelected||(m.propHooks.selected={get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}}),m.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){m.propFix[this.toLowerCase()]=this}),k.enctype||(m.propFix.enctype="encoding");var uc=/[\t\r\n\f]/g;m.fn.extend({addClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j="string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).addClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(uc," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=m.trim(d),c.className!==g&&(c.className=g)}return this},removeClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j=0===arguments.length||"string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).removeClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(uc," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?m.trim(d):"",c.className!==g&&(c.className=g)}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):this.each(m.isFunction(a)?function(c){m(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=m(this),f=a.match(E)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===K||"boolean"===c)&&(this.className&&m._data(this,"__className__",this.className),this.className=this.className||a===!1?"":m._data(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(uc," ").indexOf(b)>=0)return!0;return!1}}),m.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){m.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),m.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}});var vc=m.now(),wc=/\?/,xc=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;m.parseJSON=function(b){if(a.JSON&&a.JSON.parse)return a.JSON.parse(b+"");var c,d=null,e=m.trim(b+"");return e&&!m.trim(e.replace(xc,function(a,b,e,f){return c&&b&&(d=0),0===d?a:(c=e||b,d+=!f-!e,"")}))?Function("return "+e)():m.error("Invalid JSON: "+b)},m.parseXML=function(b){var c,d;if(!b||"string"!=typeof b)return null;try{a.DOMParser?(d=new DOMParser,c=d.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b))}catch(e){c=void 0}return c&&c.documentElement&&!c.getElementsByTagName("parsererror").length||m.error("Invalid XML: "+b),c};var yc,zc,Ac=/#.*$/,Bc=/([?&])_=[^&]*/,Cc=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Dc=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Ec=/^(?:GET|HEAD)$/,Fc=/^\/\//,Gc=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Hc={},Ic={},Jc="*/".concat("*");try{zc=location.href}catch(Kc){zc=y.createElement("a"),zc.href="",zc=zc.href}yc=Gc.exec(zc.toLowerCase())||[];function Lc(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(E)||[];if(m.isFunction(c))while(d=f[e++])"+"===d.charAt(0)?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Mc(a,b,c,d){var e={},f=a===Ic;function g(h){var i;return e[h]=!0,m.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Nc(a,b){var c,d,e=m.ajaxSettings.flatOptions||{};for(d in b)void 0!==b[d]&&((e[d]?a:c||(c={}))[d]=b[d]);return c&&m.extend(!0,a,c),a}function Oc(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 Pc(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}m.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:zc,type:"GET",isLocal:Dc.test(yc[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Jc,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":m.parseJSON,"text xml":m.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Nc(Nc(a,m.ajaxSettings),b):Nc(m.ajaxSettings,a)},ajaxPrefilter:Lc(Hc),ajaxTransport:Lc(Ic),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=m.ajaxSetup({},b),l=k.context||k,n=k.context&&(l.nodeType||l.jquery)?m(l):m.event,o=m.Deferred(),p=m.Callbacks("once memory"),q=k.statusCode||{},r={},s={},t=0,u="canceled",v={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!j){j={};while(b=Cc.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||zc)+"").replace(Ac,"").replace(Fc,yc[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=m.trim(k.dataType||"*").toLowerCase().match(E)||[""],null==k.crossDomain&&(c=Gc.exec(k.url.toLowerCase()),k.crossDomain=!(!c||c[1]===yc[1]&&c[2]===yc[2]&&(c[3]||("http:"===c[1]?"80":"443"))===(yc[3]||("http:"===yc[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=m.param(k.data,k.traditional)),Mc(Hc,k,b,v),2===t)return v;h=k.global,h&&0===m.active++&&m.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!Ec.test(k.type),e=k.url,k.hasContent||(k.data&&(e=k.url+=(wc.test(e)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=Bc.test(e)?e.replace(Bc,"$1_="+vc++):e+(wc.test(e)?"&":"?")+"_="+vc++)),k.ifModified&&(m.lastModified[e]&&v.setRequestHeader("If-Modified-Since",m.lastModified[e]),m.etag[e]&&v.setRequestHeader("If-None-Match",m.etag[e])),(k.data&&k.hasContent&&k.contentType!==!1||b.contentType)&&v.setRequestHeader("Content-Type",k.contentType),v.setRequestHeader("Accept",k.dataTypes[0]&&k.accepts[k.dataTypes[0]]?k.accepts[k.dataTypes[0]]+("*"!==k.dataTypes[0]?", "+Jc+"; 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=Mc(Ic,k,b,v)){v.readyState=1,h&&n.trigger("ajaxSend",[v,k]),k.async&&k.timeout>0&&(g=setTimeout(function(){v.abort("timeout")},k.timeout));try{t=1,i.send(r,x)}catch(w){if(!(2>t))throw w;x(-1,w)}}else x(-1,"No Transport");function x(a,b,c,d){var j,r,s,u,w,x=b;2!==t&&(t=2,g&&clearTimeout(g),i=void 0,f=d||"",v.readyState=a>0?4:0,j=a>=200&&300>a||304===a,c&&(u=Oc(k,v,c)),u=Pc(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(m.lastModified[e]=w),w=v.getResponseHeader("etag"),w&&(m.etag[e]=w)),204===a||"HEAD"===k.type?x="nocontent":304===a?x="notmodified":(x=u.state,r=u.data,s=u.error,j=!s)):(s=x,(a||!x)&&(x="error",0>a&&(a=0))),v.status=a,v.statusText=(b||x)+"",j?o.resolveWith(l,[r,x,v]):o.rejectWith(l,[v,x,s]),v.statusCode(q),q=void 0,h&&n.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),h&&(n.trigger("ajaxComplete",[v,k]),--m.active||m.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return m.get(a,b,c,"json")},getScript:function(a,b){return m.get(a,void 0,b,"script")}}),m.each(["get","post"],function(a,b){m[b]=function(a,c,d,e){return m.isFunction(c)&&(e=e||d,d=c,c=void 0),m.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),m.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){m.fn[b]=function(a){return this.on(b,a)}}),m._evalUrl=function(a){return m.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},m.fn.extend({wrapAll:function(a){if(m.isFunction(a))return this.each(function(b){m(this).wrapAll(a.call(this,b))});if(this[0]){var b=m(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&1===a.firstChild.nodeType)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return this.each(m.isFunction(a)?function(b){m(this).wrapInner(a.call(this,b))}:function(){var b=m(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=m.isFunction(a);return this.each(function(c){m(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){m.nodeName(this,"body")||m(this).replaceWith(this.childNodes)}).end()}}),m.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0||!k.reliableHiddenOffsets()&&"none"===(a.style&&a.style.display||m.css(a,"display"))},m.expr.filters.visible=function(a){return!m.expr.filters.hidden(a)};var Qc=/%20/g,Rc=/\[\]$/,Sc=/\r?\n/g,Tc=/^(?:submit|button|image|reset|file)$/i,Uc=/^(?:input|select|textarea|keygen)/i;function Vc(a,b,c,d){var e;if(m.isArray(b))m.each(b,function(b,e){c||Rc.test(a)?d(a,e):Vc(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==m.type(b))d(a,b);else for(e in b)Vc(a+"["+e+"]",b[e],c,d)}m.param=function(a,b){var c,d=[],e=function(a,b){b=m.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=m.ajaxSettings&&m.ajaxSettings.traditional),m.isArray(a)||a.jquery&&!m.isPlainObject(a))m.each(a,function(){e(this.name,this.value)});else for(c in a)Vc(c,a[c],b,e);return d.join("&").replace(Qc,"+")},m.fn.extend({serialize:function(){return m.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=m.prop(this,"elements");return a?m.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!m(this).is(":disabled")&&Uc.test(this.nodeName)&&!Tc.test(a)&&(this.checked||!W.test(a))}).map(function(a,b){var c=m(this).val();return null==c?null:m.isArray(c)?m.map(c,function(a){return{name:b.name,value:a.replace(Sc,"\r\n")}}):{name:b.name,value:c.replace(Sc,"\r\n")}}).get()}}),m.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&Zc()||$c()}:Zc;var Wc=0,Xc={},Yc=m.ajaxSettings.xhr();a.ActiveXObject&&m(a).on("unload",function(){for(var a in Xc)Xc[a](void 0,!0)}),k.cors=!!Yc&&"withCredentials"in Yc,Yc=k.ajax=!!Yc,Yc&&m.ajaxTransport(function(a){if(!a.crossDomain||k.cors){var b;return{send:function(c,d){var e,f=a.xhr(),g=++Wc;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 Xc[g],b=void 0,f.onreadystatechange=m.noop,e)4!==f.readyState&&f.abort();else{j={},h=f.status,"string"==typeof f.responseText&&(j.text=f.responseText);try{i=f.statusText}catch(k){i=""}h||!a.isLocal||a.crossDomain?1223===h&&(h=204):h=j.text?200:404}j&&d(h,i,j,f.getAllResponseHeaders())},a.async?4===f.readyState?setTimeout(b):f.onreadystatechange=Xc[g]=b:b()},abort:function(){b&&b(void 0,!0)}}}});function Zc(){try{return new a.XMLHttpRequest}catch(b){}}function $c(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}m.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return m.globalEval(a),a}}}),m.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),m.ajaxTransport("script",function(a){if(a.crossDomain){var b,c=y.head||m("head")[0]||y.documentElement;return{send:function(d,e){b=y.createElement("script"),b.async=!0,a.scriptCharset&&(b.charset=a.scriptCharset),b.src=a.url,b.onload=b.onreadystatechange=function(a,c){(c||!b.readyState||/loaded|complete/.test(b.readyState))&&(b.onload=b.onreadystatechange=null,b.parentNode&&b.parentNode.removeChild(b),b=null,c||e(200,"success"))},c.insertBefore(b,c.firstChild)},abort:function(){b&&b.onload(void 0,!0)}}}});var _c=[],ad=/(=)\?(?=&|$)|\?\?/;m.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=_c.pop()||m.expando+"_"+vc++;return this[a]=!0,a}}),m.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(ad.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&ad.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=m.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(ad,"$1"+e):b.jsonp!==!1&&(b.url+=(wc.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||m.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,_c.push(e)),g&&m.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),m.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||y;var d=u.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=m.buildFragment([a],b,e),e&&e.length&&m(e).remove(),m.merge([],d.childNodes))};var bd=m.fn.load;m.fn.load=function(a,b,c){if("string"!=typeof a&&bd)return bd.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=m.trim(a.slice(h,a.length)),a=a.slice(0,h)),m.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(f="POST"),g.length>0&&m.ajax({url:a,type:f,dataType:"html",data:b}).done(function(a){e=arguments,g.html(d?m("<div>").append(m.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,e||[a.responseText,b,a])}),this},m.expr.filters.animated=function(a){return m.grep(m.timers,function(b){return a===b.elem}).length};var cd=a.document.documentElement;function dd(a){return m.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}m.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=m.css(a,"position"),l=m(a),n={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=m.css(a,"top"),i=m.css(a,"left"),j=("absolute"===k||"fixed"===k)&&m.inArray("auto",[f,i])>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),m.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(n.top=b.top-h.top+g),null!=b.left&&(n.left=b.left-h.left+e),"using"in b?b.using.call(a,n):l.css(n)}},m.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){m.offset.setOffset(this,a,b)});var b,c,d={top:0,left:0},e=this[0],f=e&&e.ownerDocument;if(f)return b=f.documentElement,m.contains(b,e)?(typeof e.getBoundingClientRect!==K&&(d=e.getBoundingClientRect()),c=dd(f),{top:d.top+(c.pageYOffset||b.scrollTop)-(b.clientTop||0),left:d.left+(c.pageXOffset||b.scrollLeft)-(b.clientLeft||0)}):d},position:function(){if(this[0]){var a,b,c={top:0,left:0},d=this[0];return"fixed"===m.css(d,"position")?b=d.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),m.nodeName(a[0],"html")||(c=a.offset()),c.top+=m.css(a[0],"borderTopWidth",!0),c.left+=m.css(a[0],"borderLeftWidth",!0)),{top:b.top-c.top-m.css(d,"marginTop",!0),left:b.left-c.left-m.css(d,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||cd;while(a&&!m.nodeName(a,"html")&&"static"===m.css(a,"position"))a=a.offsetParent;return a||cd})}}),m.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c=/Y/.test(b);m.fn[a]=function(d){return V(this,function(a,d,e){var f=dd(a);return void 0===e?f?b in f?f[b]:f.document.documentElement[d]:a[d]:void(f?f.scrollTo(c?m(f).scrollLeft():e,c?e:m(f).scrollTop()):a[d]=e)},a,d,arguments.length,null)}}),m.each(["top","left"],function(a,b){m.cssHooks[b]=Lb(k.pixelPosition,function(a,c){return c?(c=Jb(a,b),Hb.test(c)?m(a).position()[b]+"px":c):void 0})}),m.each({Height:"height",Width:"width"},function(a,b){m.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){m.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return V(this,function(b,c,d){var e;return m.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?m.css(b,c,g):m.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),m.fn.size=function(){return this.length},m.fn.andSelf=m.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return m});var ed=a.jQuery,fd=a.$;return m.noConflict=function(b){return a.$===m&&(a.$=fd),b&&a.jQuery===m&&(a.jQuery=ed),m},typeof b===K&&(a.jQuery=a.$=m),m}); jQuery.noConflict();
node_modules/react-bootstrap/es/Modal.js
lucketta/got-quote-generator
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import _extends from 'babel-runtime/helpers/extends'; import classNames from 'classnames'; import events from 'dom-helpers/events'; import ownerDocument from 'dom-helpers/ownerDocument'; import canUseDOM from 'dom-helpers/util/inDOM'; import getScrollbarSize from 'dom-helpers/util/scrollbarSize'; import React from 'react'; import PropTypes from 'prop-types'; import ReactDOM from 'react-dom'; import BaseModal from 'react-overlays/lib/Modal'; import isOverflowing from 'react-overlays/lib/utils/isOverflowing'; import elementType from 'prop-types-extra/lib/elementType'; import Fade from './Fade'; import Body from './ModalBody'; import ModalDialog from './ModalDialog'; import Footer from './ModalFooter'; import Header from './ModalHeader'; import Title from './ModalTitle'; import { bsClass, bsSizes, prefix } from './utils/bootstrapUtils'; import createChainedFunction from './utils/createChainedFunction'; import splitComponentProps from './utils/splitComponentProps'; import { Size } from './utils/StyleConfig'; var propTypes = _extends({}, BaseModal.propTypes, ModalDialog.propTypes, { /** * Include a backdrop component. Specify 'static' for a backdrop that doesn't * trigger an "onHide" when clicked. */ backdrop: PropTypes.oneOf(['static', true, false]), /** * Add an optional extra class name to .modal-backdrop * It could end up looking like class="modal-backdrop foo-modal-backdrop in". */ backdropClassName: PropTypes.string, /** * Close the modal when escape key is pressed */ keyboard: PropTypes.bool, /** * Open and close the Modal with a slide and fade animation. */ animation: PropTypes.bool, /** * A Component type that provides the modal content Markup. This is a useful * prop when you want to use your own styles and markup to create a custom * modal component. */ dialogComponentClass: elementType, /** * When `true` The modal will automatically shift focus to itself when it * opens, and replace it to the last focused element when it closes. * Generally this should never be set to false as it makes the Modal less * accessible to assistive technologies, like screen-readers. */ autoFocus: PropTypes.bool, /** * When `true` The modal will prevent focus from leaving the Modal while * open. Consider leaving the default value here, as it is necessary to make * the Modal work well with assistive technologies, such as screen readers. */ enforceFocus: PropTypes.bool, /** * When `true` The modal will restore focus to previously focused element once * modal is hidden */ restoreFocus: PropTypes.bool, /** * When `true` The modal will show itself. */ show: PropTypes.bool, /** * A callback fired when the header closeButton or non-static backdrop is * clicked. Required if either are specified. */ onHide: PropTypes.func, /** * Callback fired before the Modal transitions in */ onEnter: PropTypes.func, /** * Callback fired as the Modal begins to transition in */ onEntering: PropTypes.func, /** * Callback fired after the Modal finishes transitioning in */ onEntered: PropTypes.func, /** * Callback fired right before the Modal transitions out */ onExit: PropTypes.func, /** * Callback fired as the Modal begins to transition out */ onExiting: PropTypes.func, /** * Callback fired after the Modal finishes transitioning out */ onExited: PropTypes.func, /** * @private */ container: BaseModal.propTypes.container }); var defaultProps = _extends({}, BaseModal.defaultProps, { animation: true, dialogComponentClass: ModalDialog }); var childContextTypes = { $bs_modal: PropTypes.shape({ onHide: PropTypes.func }) }; var Modal = function (_React$Component) { _inherits(Modal, _React$Component); function Modal(props, context) { _classCallCheck(this, Modal); var _this = _possibleConstructorReturn(this, _React$Component.call(this, props, context)); _this.handleEntering = _this.handleEntering.bind(_this); _this.handleExited = _this.handleExited.bind(_this); _this.handleWindowResize = _this.handleWindowResize.bind(_this); _this.handleDialogClick = _this.handleDialogClick.bind(_this); _this.state = { style: {} }; return _this; } Modal.prototype.getChildContext = function getChildContext() { return { $bs_modal: { onHide: this.props.onHide } }; }; Modal.prototype.componentWillUnmount = function componentWillUnmount() { // Clean up the listener if we need to. this.handleExited(); }; Modal.prototype.handleEntering = function handleEntering() { // FIXME: This should work even when animation is disabled. events.on(window, 'resize', this.handleWindowResize); this.updateStyle(); }; Modal.prototype.handleExited = function handleExited() { // FIXME: This should work even when animation is disabled. events.off(window, 'resize', this.handleWindowResize); }; Modal.prototype.handleWindowResize = function handleWindowResize() { this.updateStyle(); }; Modal.prototype.handleDialogClick = function handleDialogClick(e) { if (e.target !== e.currentTarget) { return; } this.props.onHide(); }; Modal.prototype.updateStyle = function updateStyle() { if (!canUseDOM) { return; } var dialogNode = this._modal.getDialogElement(); var dialogHeight = dialogNode.scrollHeight; var document = ownerDocument(dialogNode); var bodyIsOverflowing = isOverflowing(ReactDOM.findDOMNode(this.props.container || document.body)); var modalIsOverflowing = dialogHeight > document.documentElement.clientHeight; this.setState({ style: { paddingRight: bodyIsOverflowing && !modalIsOverflowing ? getScrollbarSize() : undefined, paddingLeft: !bodyIsOverflowing && modalIsOverflowing ? getScrollbarSize() : undefined } }); }; Modal.prototype.render = function render() { var _this2 = this; var _props = this.props, backdrop = _props.backdrop, backdropClassName = _props.backdropClassName, animation = _props.animation, show = _props.show, Dialog = _props.dialogComponentClass, className = _props.className, style = _props.style, children = _props.children, onEntering = _props.onEntering, onExited = _props.onExited, props = _objectWithoutProperties(_props, ['backdrop', 'backdropClassName', 'animation', 'show', 'dialogComponentClass', 'className', 'style', 'children', 'onEntering', 'onExited']); var _splitComponentProps = splitComponentProps(props, BaseModal), baseModalProps = _splitComponentProps[0], dialogProps = _splitComponentProps[1]; var inClassName = show && !animation && 'in'; return React.createElement( BaseModal, _extends({}, baseModalProps, { ref: function ref(c) { _this2._modal = c; }, show: show, onEntering: createChainedFunction(onEntering, this.handleEntering), onExited: createChainedFunction(onExited, this.handleExited), backdrop: backdrop, backdropClassName: classNames(prefix(props, 'backdrop'), backdropClassName, inClassName), containerClassName: prefix(props, 'open'), transition: animation ? Fade : undefined, dialogTransitionTimeout: Modal.TRANSITION_DURATION, backdropTransitionTimeout: Modal.BACKDROP_TRANSITION_DURATION }), React.createElement( Dialog, _extends({}, dialogProps, { style: _extends({}, this.state.style, style), className: classNames(className, inClassName), onClick: backdrop === true ? this.handleDialogClick : null }), children ) ); }; return Modal; }(React.Component); Modal.propTypes = propTypes; Modal.defaultProps = defaultProps; Modal.childContextTypes = childContextTypes; Modal.Body = Body; Modal.Header = Header; Modal.Title = Title; Modal.Footer = Footer; Modal.Dialog = ModalDialog; Modal.TRANSITION_DURATION = 300; Modal.BACKDROP_TRANSITION_DURATION = 150; export default bsClass('modal', bsSizes([Size.LARGE, Size.SMALL], Modal));
go-betz/src/views/add-credits/index.js
FabioFischer/go-betz
import React from 'react'; import { TextField } from 'material-ui'; import { AuthenticatedButton } from './../../components'; import { wallet, ls } from './../../services'; class AddCredits extends React.Component { state = { value: '' }; handleOnChange = (e, newValue) => this.setState({ value: newValue }); handleCCChange = (e, newValue) => this.setState({ creditCard: newValue }); handleCancel = () => this.props.history.push('my-bets'); getPaymentRequest() { const supportedInstruments = [{ supportedMethods: ['basic-card'], data: { supportedNetworks: [ 'visa', 'mastercard', 'amex', 'discover', 'diners', 'jcb', 'unionpay' ] } }]; const details = { displayItems: [{ label: 'Credits', amount: { currency: 'BRL', value: parseFloat(this.state.value) || 0 } }], total: { label: 'Total due', amount: { currency: 'BRL', value: this.state.value } } }; return new window.PaymentRequest(supportedInstruments, details); } handleAdd() { const request = this.getPaymentRequest(); request.show() .then(result => { const currentUser = ls.get('current_user'); const requestBody = { userId: currentUser ? currentUser.id : 0, value: parseFloat(this.state.value), payment: result.toJSON() }; console.log('request', requestBody); return wallet.addCredits(requestBody) .then(response => result.complete('success')) .catch(e => result.complete('fail')) }); } render() { return ( <div className='add-credits page upner--page'> <div className='add-credits--content'> <h2>ADD CREDITS</h2> <div className='add-credits--form'> <form> <TextField name='value' value={this.state.value} onChange={this.handleOnChange} floatingLabelText='Value' /> </form> </div> <div className='add-credits--actions'> <AuthenticatedButton label='add' primary onTouchTap={this.handleAdd.bind(this)} /> <AuthenticatedButton label='cancel' primary onTouchTap={this.handleCancel} /> </div> </div> </div> ); } } export default AddCredits; // <Stepper activeStep={stepIndex}> // <Step> // <StepLabel>Select campaign settings</StepLabel> // </Step> // <Step> // <StepLabel>Create an ad group</StepLabel> // </Step> // <Step> // <StepLabel>Create an ad</StepLabel> // </Step> // </Stepper>
src/parser/shared/modules/DeathTracker.js
fyruna/WoWAnalyzer
import React from 'react'; import {Link} from 'react-router-dom'; import { formatNumber, formatPercentage } from 'common/format'; import Analyzer from 'parser/core/Analyzer'; import makeAnalyzerUrl from 'interface/common/makeAnalyzerUrl'; const WIPE_MAX_DEAD_TIME = 15 * 1000; // 15sec const debug = false; // Log where someone died: https://wowanalyzer.com/report/RjH6AnYdP8GWzX4h/2-Heroic+Aggramar+-+Kill+(6:23)/Kantasai class DeathTracker extends Analyzer { deaths = []; resurrections = []; lastDeathTimestamp = 0; lastResurrectionTimestamp = 0; _timeDead = 0; _didCast = false; isAlive = true; die(event) { this.lastDeathTimestamp = this.owner.currentTimestamp; debug && this.log("Player Died"); this.isAlive = false; this.deaths.push(event); } resurrect(event) { this.lastResurrectionTimestamp = this.owner.currentTimestamp; this._timeDead += this.lastResurrectionTimestamp - this.lastDeathTimestamp; debug && this.log("Player was Resurrected"); this.isAlive = true; this.resurrections.push(event); } on_toPlayer_death(event) { this.die(event); } on_toPlayer_resurrect(event) { this.resurrect(event); } on_byPlayer_cast(event) { this._didCast = true; if (!this.isAlive) { this.resurrect(event); } } on_byPlayer_begincast(event) { if (!this.isAlive) { this.resurrect(event); } } on_toPlayer_heal(event) { if (!this.isAlive) { this.resurrect(event); } } on_toPlayer_damage(event) { if (!this.isAlive) { this.resurrect(event); } } get totalTimeDead() { return this._timeDead + (this.isAlive ? 0 : this.owner.currentTimestamp - this.lastDeathTimestamp); } get timeDeadPercent() { return this.totalTimeDead / this.owner.fightDuration; } get deathSuggestionThresholds() { return { actual: this.timeDeadPercent, isGreaterThan: { major: 0.00, }, style: 'percentage', }; } suggestions(when) { const boss = this.owner.boss; const fight = this.owner.fight; const player = this.owner.player; const report = this.owner.report; const disableDeathSuggestion = boss && boss.fight.disableDeathSuggestion; const isWipe = !fight.kill; const isWipeDeath = isWipe && this.totalTimeDead < WIPE_MAX_DEAD_TIME; if (!disableDeathSuggestion && !isWipeDeath) { when(this.timeDeadPercent).isGreaterThan(0) .addSuggestion((suggest, actual, recommended) => { return suggest(<> You died during this fight and were dead for {formatPercentage(actual)}% of the fight duration ({formatNumber(this.totalTimeDead / 1000)} seconds). Dying has a significant performance cost. View the <Link to={makeAnalyzerUrl(report, fight.id, player.id, 'death-recap')}>Death Recap</Link> to see the damage taken and what defensives and potions were still available. </>) .icon('ability_fiegndead') .actual(`You were dead for ${formatPercentage(actual)}% of the fight`) .recommended('0% is recommended') .major(this.deathSuggestionThresholds.isGreaterThan.major); }); } when(this._didCast).isFalse() .addSuggestion((suggest, actual, recommended) => { return suggest('You did not cast a single spell this fight. You were either dead for the entire fight, or were AFK.') .icon('ability_fiegndead') .major(this.deathSuggestionThresholds.isGreaterThan.major); }); } } export default DeathTracker;
ajax/libs/antd/1.4.1/antd.min.js
hare1039/cdnjs
/*! * antd v1.4.1 * * 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=t(require("react"),require("react-dom")):e.antd=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(250)},function(t,n){t.exports=e},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 i in r)a.call(r,i)&&r[i]&&e.push(i)}}return e.join(" ")}var a={}.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){},function(e,n){e.exports=t},function(e,t,n){"use strict";function r(e,t){t.every(function(e){return"string"==typeof e})&&h(e,t)}function o(){for(var e=arguments.length,t=Array(e),n=0;e>n;n++)t[n]=arguments[n];var r=1,o=t[0],a=t.length;if("function"==typeof o)return o.apply(null,t.slice(1));if("string"==typeof o){for(var i=String(o).replace(d,function(e){if("%%"===e)return"%";if(r>=a)return e;switch(e){case"%s":return String(t[r++]);case"%d":return Number(t[r++]);case"%j":try{return JSON.stringify(t[r++])}catch(n){return"[Circular]"}break;default:return e}}),s=t[r];a>r;s=t[++r])i+=" "+s;return i}return o}function a(e){return"string"===e||"url"===e||"hex"===e||"email"===e}function i(e,t){return void 0===e||null===e?!0:"array"===t&&Array.isArray(e)&&!e.length?!0:!(!a(t)||"string"!=typeof e||e)}function s(e){return 0===Object.keys(e).length}function l(e,t,n){function r(e){o.push.apply(o,e),a++,a===i&&n(o)}var o=[],a=0,i=e.length;e.forEach(function(e){t(e,r)})}function u(e,t,n){function r(i){if(i.length)return void n(i);var s=o;o+=1,a>s?t(e[s],r):n([])}var o=0,a=e.length;r([])}function c(e){var t=[];return Object.keys(e).forEach(function(n){t.push.apply(t,e[n])}),t}function p(e,t,n,r){if(t.first){var o=c(e);return u(o,n,r)}var a=t.firstFields||[];a===!0&&(a=Object.keys(e));var i=Object.keys(e),s=i.length,p=0,f=[],d=function(e){f.push.apply(f,e),p++,p===s&&r(f)};i.forEach(function(t){var r=e[t];-1!==a.indexOf(t)?u(r,n,d):l(r,n,d)})}function f(e){return function(t){return t&&t.message?(t.field=t.field||e.fullField,t):{message:t,field:t.field||e.fullField}}}Object.defineProperty(t,"__esModule",{value:!0}),t.warning=r,t.format=o,t.isEmptyValue=i,t.isEmptyObject=s,t.asyncMap=p,t.complementError=f;var d=/%[sdj%]/g,h=function(){}},function(e,t,n){"use strict";e.exports={guid:n(401),classSet:n(399),joinClasses:n(402),KeyCode:n(114),PureRenderMixin:n(398),shallowEqual:n(119),createChainedFunction:n(400),Dom:{addEventListener:n(396),contains:n(397)},Children:{toArray:n(395),mapSelf:n(394)}}},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 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},i=n(1),s=r(i);t["default"]=function(e){var t=e.type,n=e.className,r=void 0===n?"":n,i=o(e,["type","className"]);return r+=" anticon anticon-"+t,s["default"].createElement("i",a({className:r},i))},e.exports=t["default"]},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t["default"]={required:n(47),whitespace:n(131),type:n(130),range:n(129),"enum":n(127),pattern:n(128)},e.exports=t["default"]},function(e,t,n){"use strict";e.exports=n(281)},function(e,t,n){"use strict";function r(e){var t=e||p;this.locale=t,this.fields=[],this.time=void 0,this.timezoneOffset=t.timezoneOffset,this.firstDayOfWeek=t.firstDayOfWeek,this.minimalDaysInFirstWeek=t.minimalDaysInFirstWeek,this.fieldsComputed=!1}function o(e,t){return L(e)?S[t]:E[t]}function a(e){return L(e)?366:365}function i(e){var t=e.fields,n=t[h],r=t[y],a=o(n,r),i=t[v];i>a&&e.set(v,a)}function s(e,t){return e-A(e-t,7)}function l(e,t,n){var r=s(t+6,e.firstDayOfWeek),o=r-t;o>=e.minimalDaysInFirstWeek&&(r-=7);var a=n-r;return V(a/7)+1}var u=parseInt,c=n(264),p=n(79),f=n(78);c.mix(r,f),c.mix(r,{Utils:c,defaultLocale:p,isLeapYear:c.isLeapYear,YEAR:1,MONTH:2,DAY_OF_MONTH:3,HOUR_OF_DAY:4,MINUTES:5,SECONDS:6,MILLISECONDS:7,WEEK_OF_YEAR:8,WEEK_OF_MONTH:9,DAY_OF_YEAR:10,DAY_OF_WEEK:11,DAY_OF_WEEK_IN_MONTH:12,AM:0,PM:1});var d=["","Year","Month","DayOfMonth","HourOfDay","Minutes","Seconds","Milliseconds","WeekOfYear","WeekOfMonth","DayOfYear","DayOfWeek","DayOfWeekInMonth"],h=r.YEAR,y=r.MONTH,v=r.DAY_OF_MONTH,m=r.HOUR_OF_DAY,g=r.MINUTES,b=r.SECONDS,P=r.MILLISECONDS,O=r.DAY_OF_WEEK_IN_MONTH,C=r.DAY_OF_YEAR,T=r.DAY_OF_WEEK,w=r.WEEK_OF_MONTH,x=r.WEEK_OF_YEAR,E=[31,28,31,30,31,30,31,31,30,31,30,31],S=[31,29,31,30,31,30,31,31,30,31,30,31],k=1e3,j=60*k,_=60*j,N=24*_,M=7*N,D=719163,A=c.mod,L=c.isLeapYear,V=Math.floor,F=[void 0,1,r.JANUARY,1,0,0,0,0,1,void 0,1,r.SUNDAY,1],I=[void 0,292278994,r.DECEMBER,void 0,23,59,59,999,void 0,void 0,void 0,r.SATURDAY,void 0];r.prototype={constructor:r,isGregorianCalendar:1,isLeapYear:function(){return L(this.getYear())},getLocale:function(){return this.locale},getActualMinimum:function(e){if(void 0!==F[e])return F[e];if(e===w){var t=this.clone();return t.clear(),t.set(this.fields[h],this.fields[y],1),t.get(w)}throw new Error("minimum value not defined!")},getActualMaximum:function(e){if(void 0!==I[e])return I[e];var t=void 0,n=this.fields;switch(e){case v:t=o(n[h],n[y]);break;case x:var i=this.clone();i.clear(),i.set(n[h],r.DECEMBER,31),t=i.get(x),1===t&&(t=52);break;case w:var s=this.clone();s.clear(),s.set(n[h],n[y],o(n[h],n[y])),t=s.get(w);break;case C:t=a(n[h]);break;case O:t=u((o(n[h],n[y])-1)/7)+1}if(void 0===t)throw new Error("maximum value not defined!");return t},isSet:function(e){return void 0!==this.fields[e]},computeFields:function(){var e=this.time,t=this.timezoneOffset*j,n=u(t/N),o=t%N;if(n+=u(e/N),o+=e%N,o>=N)o-=N,n++;else for(;0>o;)o+=N,n--;n+=D;var i=c.getGregorianDateFromFixedDate(n),p=i.year,f=this.fields;if(f[h]=p,f[y]=i.month,f[v]=i.dayOfMonth,f[T]=i.dayOfWeek,0!==o){f[m]=u(o/_);var d=o%_;f[g]=u(d/j),d%=j,f[b]=u(d/k),f[P]=d%k}else f[m]=f[g]=f[b]=f[P]=0;var E=c.getFixedDate(p,r.JANUARY,1),S=n-E+1,M=n-i.dayOfMonth+1;f[C]=S,f[O]=u((i.dayOfMonth-1)/7)+1;var A=l(this,E,n);if(0===A){var L=E-1,V=E-a(p-1);A=l(this,V,L)}else if(A>=52){var F=E+a(p),I=s(F+6,this.firstDayOfWeek),R=I-F;R>=this.minimalDaysInFirstWeek&&n>=I-7&&(A=1)}f[x]=A,f[w]=l(this,M,n),this.fieldsComputed=!0},computeTime:function(){var e=void 0,t=this.fields;e=this.isSet(h)?t[h]:(new Date).getFullYear();var n=0;this.isSet(m)&&(n+=t[m]),n*=60,n+=t[g]||0,n*=60,n+=t[b]||0,n*=1e3,n+=t[P]||0;var r=0;t[h]=e,r+=this.getFixedDate();var o=(r-D)*N+n;o-=this.timezoneOffset*j,this.time=o,this.computeFields()},complete:function(){void 0===this.time&&this.computeTime(),this.fieldsComputed||this.computeFields()},getFixedDate:function(){var e=this,t=e.fields,n=e.firstDayOfWeek,a=t[h],i=r.JANUARY;e.isSet(y)&&(i=t[y],i>r.DECEMBER?(a+=u(i/12),i%=12):i<r.JANUARY&&(a+=V(i/12),i=A(i,12)));var l=c.getFixedDate(a,i,1),p=void 0,f=e.firstDayOfWeek;if(e.isSet(T)&&(f=t[T]),e.isSet(y))if(e.isSet(v))l+=t[v]-1;else if(e.isSet(w))p=s(l+6,n),p-l>=e.minimalDaysInFirstWeek&&(p-=7),f!==n&&(p=s(p+6,f)),l=p+7*(t[w]-1);else{var d=void 0;d=e.isSet(O)?t[O]:1;var m=7*d;0>d&&(m=o(a,i)+7*(d+1)),l=s(l+m-1,f)}else e.isSet(C)?l+=t[C]-1:e.isSet(x)&&(p=s(l+6,n),p-l>=e.minimalDaysInFirstWeek&&(p-=7),f!==n&&(p=s(p+6,f)),l=p+7*(t[x]-1));return l},getTime:function(){return void 0===this.time&&this.computeTime(),this.time},setTime:function(e){this.time=e,this.fieldsComputed=!1,this.complete()},get:function(e){return this.complete(),this.fields[e]},set:function(e,t){var n=arguments.length;if(2===n)this.fields[e]=t;else{if(!(P+1>n))throw new Error("illegal arguments for GregorianCalendar set");for(var r=0;n>r;r++)this.fields[h+r]=arguments[r]}this.time=void 0},add:function(e,t){if(t){var n=t,r=this,o=r.fields,a=r.get(e);if(e===h)a+=n,r.set(h,a),i(r);else if(e===y){a+=n;var s=V(a/12);a=A(a,12),s&&r.set(h,o[h]+s),r.set(y,a),i(r)}else{switch(e){case m:n*=_;break;case g:n*=j;break;case b:n*=k;break;case P:break;case w:case x:case O:n*=M;break;case T:case C:case v:n*=N;break;default:throw new Error("illegal field for add")}r.setTime(r.time+n)}}},getRolledValue:function(e,t,n,r){var o=t,a=e-n,i=r-n+1;return o%=i,n+(a+o+i)%i},roll:function(e,t){if(t){var n=this,r=n.get(e),o=n.getActualMinimum(e),a=n.getActualMaximum(e);switch(r=n.getRolledValue(r,t,o,a),n.set(e,r),e){case y:i(n);break;default:n.updateFieldsBySet(e)}}},rollSet:function(e,t){switch(this.set(e,t),e){case y:i(this);break;default:this.updateFieldsBySet(e)}},updateFieldsBySet:function(e){var t=this.fields;switch(e){case w:t[v]=void 0;break;case C:t[y]=void 0;break;case T:t[v]=void 0;break;case x:t[C]=void 0,t[y]=void 0}},getTimezoneOffset:function(){return this.timezoneOffset},setTimezoneOffset:function(e){this.timezoneOffset!==e&&(this.fieldsComputed=void 0,this.timezoneOffset=e)},setFirstDayOfWeek:function(e){this.firstDayOfWeek!==e&&(this.firstDayOfWeek=e,this.fieldsComputed=!1)},getFirstDayOfWeek:function(){return this.firstDayOfWeek},setMinimalDaysInFirstWeek:function(e){this.minimalDaysInFirstWeek!==e&&(this.minimalDaysInFirstWeek=e,this.fieldsComputed=!1)},getMinimalDaysInFirstWeek:function(){return this.minimalDaysInFirstWeek},getWeeksInWeekYear:function(){var e=this.getWeekYear();if(e===this.get(h))return this.getActualMaximum(x);var t=this.clone();return t.clear(),t.setWeekDate(e,2,this.get(T)),t.getActualMaximum(x)},getWeekYear:function(){var e=this.get(h),t=this.get(x),n=this.get(y);return n===r.JANUARY?t>=52&&--e:n===r.DECEMBER&&1===t&&++e,e},setWeekDate:function(e,t,n){if(n<r.SUNDAY||n>r.SATURDAY)throw new Error("invalid dayOfWeek: "+n);var o=this.fields,a=this.clone();a.clear(),a.setTimezoneOffset(0),a.set(h,e),a.set(x,1),a.set(T,this.getFirstDayOfWeek());var i=n-this.getFirstDayOfWeek();0>i&&(i+=7),i+=7*(t-1),0!==i?a.add(C,i):a.complete(),o[h]=a.get(h),o[y]=a.get(y),o[v]=a.get(v),this.complete()},clone:function(){void 0===this.time&&this.computeTime();var e=new r(this.locale);return e.setTimezoneOffset(e.getTimezoneOffset()),e.setFirstDayOfWeek(e.getFirstDayOfWeek()),e.setMinimalDaysInFirstWeek(e.getMinimalDaysInFirstWeek()),e.setTime(this.time),e},equals:function(e){return this.getTime()===e.getTime()&&this.firstDayOfWeek===e.firstDayOfWeek&&this.timezoneOffset===e.timezoneOffset&&this.minimalDaysInFirstWeek===e.minimalDaysInFirstWeek},compareToDay:function(e){var t=this.getYear(),n=e.getYear(),r=this.getMonth(),o=e.getMonth(),a=this.getDayOfMonth(),i=e.getDayOfMonth();return t!==n?t-n:r!==o?r-o:a-i},clear:function(e){void 0===e?this.field=[]:this.fields[e]=void 0,this.time=void 0,this.fieldsComputed=!1},toString:function(){var e=this;return"[GregorianCalendar]: "+e.getYear()+"/"+e.getMonth()+"/"+e.getDayOfMonth()+" "+e.getHourOfDay()+":"+e.getMinutes()+":"+e.getSeconds()}};var R=r.prototype;c.each(d,function(e,t){e&&(R["get"+e]=function(){return this.get(t)},R["isSet"+e]=function(){return this.isSet(t)},R["set"+e]=function(e){return this.set(t,e)},R["add"+e]=function(e){return this.add(t,e)},R["roll"+e]=function(e){return this.roll(t,e)},R["rollSet"+e]=function(e){return this.rollSet(t,e)})}),e.exports=r},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;10>n;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(a){return!1}}var o=Object.prototype.hasOwnProperty,a=Object.prototype.propertyIsEnumerable;e.exports=r()?Object.assign:function(e,t){for(var r,i,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){i=Object.getOwnPropertySymbols(r);for(var c=0;c<i.length;c++)a.call(r,i[c])&&(s[i[c]]=r[i[c]])}}return s}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){var t=e.clone();return t.setTime(Date.now()),t}function a(e){return e.getYear()+"-"+(e.getMonth()+1)+"-"+e.getDayOfMonth()}function i(e){var t=o(e);return a(t)}function s(e,t){return"string"==typeof e?new y["default"](e,t.format):e}function l(e,t){t.setHourOfDay(e.getHourOfDay()),t.setMinutes(e.getMinutes()),t.setSeconds(e.getSeconds())}function u(e,t){var n=t?t(e):{};return n=d({},v,n)}function c(e,t){var n=!1;if(e){var r=e.getHourOfDay(),o=e.getMinutes(),a=e.getSeconds(),i=t.disabledHours();if(-1===i.indexOf(r)){var s=t.disabledMinutes(r);if(-1===s.indexOf(o)){var l=t.disabledSeconds(r,o);n=-1!==l.indexOf(a)}else n=!0}else n=!0}return!n}function p(e,t){var n=u(e,t);return c(e,n)}function f(e,t,n){return t&&t(e)?!1:!n||p(e,n)}Object.defineProperty(t,"__esModule",{value:!0});var d=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.getTodayTime=o,t.getTitleString=a,t.getTodayTimeStr=i,t.getFormatter=s,t.syncTime=l,t.getTimeConfig=u,t.isTimeValidByConfig=c,t.isTimeValid=p,t.isAllowedDate=f;var h=n(27),y=r(h),v={disabledHours:function(){return[]},disabledMinutes:function(){return[]},disabledSeconds:function(){return[]}}},[459,433],function(e,t,n){"use strict";e.exports=n(386)},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(156),a=r(o),i=n(155),s=r(i);a["default"].Group=s["default"],t["default"]=a["default"],e.exports=t["default"]},function(e,t,n){e.exports=n(412)},function(e,t,n){"use strict";var r=function(){};e.exports=r},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],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(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 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}),t["default"]=void 0;var c,p,f=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(95),h=r(d),y=n(1),v=r(y),m=n(167),g=r(m),b=n(2),P=r(b),O=n(16),C=r(O),T=(p=c=function(e){function t(){return s(this,t),l(this,e.apply(this,arguments))}return u(t,e),t.prototype.shouldComponentUpdate=function(){for(var e=arguments.length,t=Array(e),n=0;e>n;n++)t[n]=arguments[n];return C["default"].shouldComponentUpdate.apply(this,t)},t.prototype.render=function(){var e,t=this.props,n=t.prefixCls,r=t.style,o=t.children,s=t.className,l=i(t,["prefixCls","style","children","className"]),u=(0,P["default"])((e={},a(e,s,!!s),a(e,n+"-wrapper",!0),e));return v["default"].createElement("label",{className:u,style:r},v["default"].createElement(h["default"],f({},l,{prefixCls:n,children:null})),void 0!==o?v["default"].createElement("span",null,o):null)},t}(v["default"].Component),c.Group=g["default"],c.defaultProps={prefixCls:"ant-checkbox"},p);t["default"]=T,e.exports=t["default"]},[459,427],function(e,t){"use strict";function n(e,t,r){var o=r;{if("object"!=typeof t)return"undefined"!=typeof o?("number"==typeof o&&(o+="px"),void(e.style[t]=o)):C(e,t);for(var a in t)t.hasOwnProperty(a)&&n(e,a,t[a])}}function r(e){var t=void 0,n=void 0,r=void 0,o=e.ownerDocument,a=o.body,i=o&&o.documentElement;return t=e.getBoundingClientRect(),n=t.left,r=t.top,n-=i.clientLeft||a.clientLeft||0,r-=i.clientTop||a.clientTop||0,{left:n,top:r}}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 a(e){return o(e)}function i(e){return o(e,!0)}function s(e){var t=r(e),n=e.ownerDocument,o=n.defaultView||n.parentWindow;return t.left+=a(o),t.top+=i(o),t}function l(e,t,n){var r=n,o="",a=e.ownerDocument;return r=r||a.defaultView.getComputedStyle(e,null),r&&(o=r.getPropertyValue(t)||r[t]),o}function u(e,t){var n=e[x]&&e[x][t];if(T.test(n)&&!w.test(t)){var r=e.style,o=r[S],a=e[E][S];e[E][S]=e[x][S],r[S]="fontSize"===t?"1em":n||0,n=r.pixelLeft+k,r[S]=o,e[E][S]=a}return""===n?"auto":n}function c(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 f(e,t,r){"static"===n(e,"position")&&(e.style.position="relative");var o=-999,a=-999,i=c("left",r),l=c("top",r),u=p(i),f=p(l);"left"!==i&&(o=999),"top"!==l&&(a=999),"left"in t&&(e.style[u]="",e.style[i]=o+"px"),"top"in t&&(e.style[f]="",e.style[l]=a+"px");var d=s(e),h={},y=void 0;for(y in t)if(t.hasOwnProperty(y)){var v=c(y,r),m="left"===y?o:a;v===y?h[v]=m+t[y]-d[y]:h[v]=m+d[y]-t[y]}n(e,h)}function d(e,t){for(var n=0;n<e.length;n++)t(e[n])}function h(e){return"border-box"===C(e,"boxSizing")}function y(e,t,n){var r={},o=e.style,a=void 0;for(a in t)t.hasOwnProperty(a)&&(r[a]=o[a],o[a]=t[a]);n.call(e);for(a in t)t.hasOwnProperty(a)&&(o[a]=r[a])}function v(e,t,n){var r=0,o=void 0,a=void 0,i=void 0;for(a=0;a<t.length;a++)if(o=t[a])for(i=0;i<n.length;i++){var s=void 0;s="border"===o?o+n[i]+"Width":o+n[i],r+=parseFloat(C(e,s))||0}return r}function m(e){return null!==e&&void 0!==e&&e==e.window}function g(e,t,n){var r=n;if(m(e))return"width"===t?A.viewportWidth(e):A.viewportHeight(e);if(9===e.nodeType)return"width"===t?A.docWidth(e):A.docHeight(e);var o="width"===t?["Left","Right"]:["Top","Bottom"],a="width"===t?e.offsetWidth:e.offsetHeight,i=C(e),s=h(e,i),l=0;(null===a||void 0===a||0>=a)&&(a=void 0,l=C(e,t),(null===l||void 0===l||Number(l)<0)&&(l=e.style[t]||0),l=parseFloat(l)||0),void 0===r&&(r=s?M:_);var u=void 0!==a||s,c=a||l;return r===_?u?c-v(e,["border","padding"],o,i):l:u?r===M?c:c+(r===N?-v(e,["border"],o,i):v(e,["margin"],o,i)):l+v(e,j.slice(r),o,i)}function b(){for(var e=arguments.length,t=Array(e),n=0;e>n;n++)t[n]=arguments[n];var r=void 0,o=t[0];return 0!==o.offsetWidth?r=g.apply(void 0,t):y(o,L,function(){r=g.apply(void 0,t)}),r}function P(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);return e}Object.defineProperty(t,"__esModule",{value:!0});var O=/[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,C=void 0,T=new RegExp("^("+O+")(?!px)[a-z%]+$","i"),w=/^(top|right|bottom|left)$/,x="currentStyle",E="runtimeStyle",S="left",k="px";"undefined"!=typeof window&&(C=window.getComputedStyle?l:u);var j=["margin","border","padding"],_=-1,N=2,M=1,D=0,A={};d(["Width","Height"],function(e){A["doc"+e]=function(t){var n=t.document;return Math.max(n.documentElement["scroll"+e],n.body["scroll"+e],A["viewport"+e](n))},A["viewport"+e]=function(t){var n="client"+e,r=t.document,o=r.body,a=r.documentElement,i=a[n];return"CSS1Compat"===r.compatMode&&i||o&&o[n]||i}});var L={position:"absolute",visibility:"hidden",display:"block"};d(["width","height"],function(e){var t=e.charAt(0).toUpperCase()+e.slice(1);A["outer"+t]=function(t,n){return t&&b(t,e,n?D:M)};var r="width"===e?["Left","Right"]:["Top","Bottom"];A[e]=function(t,o){var a=o;{if(void 0===a)return t&&b(t,e,_);if(t){var i=C(t),s=h(t);return s&&(a+=v(t,["padding","border"],r,i)),n(t,e,a)}}}});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?s(e):void f(e,t,n||{})},isWindow:m,each:d,css:n,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:P,getWindowScrollLeft:function(e){return a(e)},getWindowScrollTop:function(e){return i(e)},merge:function(){for(var e={},t=arguments.length,n=Array(t),r=0;t>r;r++)n[r]=arguments[r];for(var o=0;o<n.length;o++)V.mix(e,n[o]);return e},viewportWidth:0,viewportHeight:0};P(V,A),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}),t.Divider=t.ItemGroup=t.MenuItemGroup=t.MenuItem=t.Item=t.SubMenu=void 0;var o=n(317),a=r(o),i=n(320),s=r(i),l=n(318),u=r(l),c=n(319),p=r(c),f=n(316),d=r(f);t.SubMenu=s["default"],t.Item=u["default"],t.MenuItem=u["default"],t.MenuItemGroup=p["default"],t.ItemGroup=p["default"],t.Divider=d["default"],t["default"]=a["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){}function a(e,t,n){var r=t||"";return e.key||r+"item_"+u+"_"+n}function i(e,t){var n=-1;l["default"].Children.forEach(e,function(e){n++,e&&e.type.isMenuItemGroup?l["default"].Children.forEach(e.props.children,function(e){n++,t(e,n)}):t(e,n)})}Object.defineProperty(t,"__esModule",{value:!0}),t.noop=o,t.getKeyFromChildrenIndex=a,t.loopMenuItem=i;var s=n(1),l=r(s),u=Date.now()},[459,422],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(33),a=r(o),i=n(212),s=r(i),l=n(65),u=r(l);a["default"].Button=u["default"],a["default"].Group=s["default"],t["default"]=a["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){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(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){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}),t["default"]=void 0;var u,c,p=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},f=n(1),d=r(f),h=n(345),y=r(h),v=n(2),m=r(v),g=(c=u=function(e){function t(){return i(this,t),s(this,e.apply(this,arguments))}return l(t,e),t.prototype.render=function(){var e,t=this.props,n=t.size,r=t.className,o=t.combobox,i=t.notFoundContent,s=t.prefixCls,l=t.showSearch,u=t.optionLabelProp,c=(0,m["default"])((e={},a(e,s+"-lg","large"===n),a(e,s+"-sm","small"===n),a(e,r,!!r),a(e,s+"-show-search",l),e)),f=this.context.antLocale;return f&&f.Select&&(i=i||f.Select.notFoundContent),o&&(i=null,u=u||"value"),d["default"].createElement(y["default"],p({},this.props,{className:c,optionLabelProp:u||"children",notFoundContent:i}))},t}(d["default"].Component),u.Option=h.Option,u.OptGroup=h.OptGroup,u.defaultProps={prefixCls:"ant-select",transitionName:"slide-up",choiceTransitionName:"zoom",showSearch:!1},u.contextTypes={antLocale:d["default"].PropTypes.object},c);t["default"]=g,e.exports=t["default"]},[460,443],function(e,t,n){"use strict";function r(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])}function o(e,t,n){return"string"==typeof e&&t?e.replace(n||T,function(e,n){return"\\"===e.charAt(0)?e.slice(1):void 0===t[n]?w:t[n]}):e}function a(e,t,n){n.push({field:e,count:t})}function i(e){for(var t=e.length,n=!1,r=[],o=null,i=0,s=-1,l=0;t>l;l++){var u=e.charAt(l);if("'"!==u)if(n)o+=u;else if(u>="a"&&"z">=u||u>="A"&&"Z">=u){if(-1===P.indexOf(u))throw new Error('Illegal pattern character "'+u+'"');-1!==s&&s!==u?(a(s,i,r),s=u,i=1):(s=u,i++)}else 0!==i&&(a(s,i,r),s=-1,i=0),r.push({text:u});else{if(t>l+1&&(u=e.charAt(l+1),"'"===u)){l++,0!==i&&(a(s,i,r),s=-1,i=0),n&&(o+=u);continue}n?(r.push({text:o}),n=!1):(0!==i&&(a(s,i,r),s=-1,i=0),o="",n=!0)}}if(n)throw new Error("Unterminated quote");return 0!==i&&a(s,i,r),r}function s(e,t,n,r){var o=!0;e:for(;o;){var a=e,i=t,s=n,l=r;o=!1;var u=l||[],c=s||m;if(a>=0){if(100>a&&i>=1&&2>=i)return 10>a&&2===i&&u.push(x),u.push(a),u.join("");if(a>=1e3&&1e4>a){if(4===i)return u.push(a),u.join("");if(2===i&&2===c){e=a%100,t=2,n=2,r=u,o=!0,u=c=void 0;continue e}}}return u.push(a+""),u.join("")}}function l(e,t){this.locale=t||v,this.originalPattern=e,this.pattern=i(e)}function u(e,t,n,r){var o=void 0,a=void 0;switch(e){case"G":a=r.getYear()>0?1:0,o=n.eras[a];break;case"Y":a=r.getWeekYear(),0>=a&&(a=1-a),o=s(a,2,2!==t?m:2);break;case"y":a=r.getYear(),0>=a&&(a=1-a),o=s(a,2,2!==t?m:2);break;case"M":a=r.getMonth(),o=t>=4?n.months[a]:3===t?n.shortMonths[a]:s(a+1,t);break;case"k":o=s(r.getHourOfDay()||24,t);break;case"E":a=r.getDayOfWeek(),o=t>=4?n.weekdays[a]:n.shortWeekdays[a];break;case"a":o=n.ampms[r.getHourOfDay()>=12?1:0];break;case"h":o=s(r.getHourOfDay()%12||12,t);break;case"K":o=s(r.getHourOfDay()%12,t);break;case"Z":var i=r.getTimezoneOffset(),l=[0>i?"-":"+"];i=Math.abs(i),l.push(s(Math.floor(i/60)%100,2),s(i%60,2)),o=l.join("");break;default:var u=C[e];a=r.get(u),o=s(a,t)}return o}function c(e,t,n,r){for(var o=0;r>o;o++)if(e.charAt(t+o)!==n.charAt(o))return!1;return!0}function p(e,t,n){var r=-1,o=-1,a=void 0,i=n.length;for(a=0;i>a;a++){var s=n[a],l=s.length;l>r&&c(e,t,s,l)&&(r=l,o=a)}return o>=0?{value:o,startIndex:t+r}:null}function f(e){var t=void 0,n=void 0,r=e.length;for(t=0;r>t&&(n=e.charAt(t),!("0">n||n>"9"));t++);return t}function d(e,t,n,r){var o=e,a=void 0;if(r){if(e.length<t+n)return null;if(o=e.slice(t,t+n),!o.match(/^\d+$/))throw new Error("GregorianCalendarFormat parse error, dateStr: "+e+", patter: "+this.originalPattern)}else o=o.slice(t);if(a=parseInt(o,10),isNaN(a))throw new Error("GregorianCalendarFormat parse error, dateStr: "+e+", patter: "+this.originalPattern);return{value:a,startIndex:t+f(o)}}function h(e,t,n,r,o,a,i){var s=void 0,l=void 0,u=void 0,c=n;if(t.length<=c)return c;var f=this.locale;switch(r){case"G":s=p(t,c,f.eras),s&&(e.isSetYear()?0===s.value&&(l=e.getYear(),e.setYear(1-l)):i.era=s.value);break;case"y":s=d.call(this,t,c,o,a),s&&(l=s.value,"era"in i&&0===i.era&&(l=1-l),e.setYear(l));break;case"M":var h=void 0;o>=3?(s=p(t,c,f[3===o?"shortMonths":"months"]),s&&(h=s.value)):(s=d.call(this,t,c,o,a),s&&(h=s.value-1)),s&&e.setMonth(h);break;case"k":s=d.call(this,t,c,o,a),s&&e.setHourOfDay(s.value%24);break;case"E":s=p(t,c,f[o>3?"weekdays":"shortWeekdays"]),s&&e.setDayOfWeek(s.value);break;case"a":s=p(t,c,f.ampms),s&&(e.isSetHourOfDay()?s.value&&(u=e.getHourOfDay(),12>u&&e.setHourOfDay((u+12)%24)):i.ampm=s.value);break;case"h":s=d.call(this,t,c,o,a),s&&(u=s.value%=12,i.ampm&&(u+=12),e.setHourOfDay(u));break;case"K":s=d.call(this,t,c,o,a),s&&(u=s.value,i.ampm&&(u+=12),e.setHourOfDay(u));break;case"Z":var y=t.charAt(c);if("-"===y)c++;else{if("+"!==y)break;c++}if(s=d.call(this,t,c,2,!0)){var v=60*s.value;c=s.startIndex,s=d.call(this,t,c,2,!0),s&&(v+=s.value),e.setTimezoneOffset(v)}break;default:if(s=d.call(this,t,c,o,a)){var m=C[r];e.set(m,s.value)}}return s&&(c=s.startIndex),c}var y=n(10),v=n(38),m=Number.MAX_VALUE,g=n(263),b={FULL:0,LONG:1,MEDIUM:2,SHORT:3},P=new Array(y.DAY_OF_WEEK_IN_MONTH+2).join("1"),O=0,C={};P=P.split(""),P[O]="G",P[y.YEAR]="y",P[y.MONTH]="M",P[y.DAY_OF_MONTH]="d",P[y.HOUR_OF_DAY]="H",P[y.MINUTES]="m",P[y.SECONDS]="s",P[y.MILLISECONDS]="S",P[y.WEEK_OF_YEAR]="w",P[y.WEEK_OF_MONTH]="W",P[y.DAY_OF_YEAR]="D",P[y.DAY_OF_WEEK_IN_MONTH]="F",P.push("Y"),P.forEach(function(e,t){var n=t;"Y"===e&&(n=y.YEAR),e&&(C[e]=n)});var T=/\\?\{([^{}]+)\}/g,w="";P=P.join("")+"ahkKZE";var x="0";r(l.prototype,{format:function(e){if(!e.isGregorianCalendar)throw new Error("calendar must be type of GregorianCalendar");var t=void 0,n=[],r=this.pattern,o=r.length;for(t=0;o>t;t++){var a=r[t];a.text?n.push(a.text):"field"in a&&n.push(u(a.field,a.count,this.locale,e))}return n.join("")},parse:function(e,t){var n=t||{},r=n.locale,o=new y(r),a=void 0,i=void 0,s={},l=n.obeyCount||!1,u=e.length,c=-1,p=0,f=0,d=this.pattern,v=d.length;e:for(a=0;0>c&&v>a;a++){var m=d[a],b=void 0,P=void 0;if(f=p,b=m.text)if(P=b.length,P+p>u)c=p;else{for(i=0;P>i;i++)if(b.charAt(i)!==e.charAt(i+p)){c=p;break e}p+=P}else if("field"in m){if(!n.obeyCount){var O=d[a+1];if(l=!1,O)if("field"in O)l=!0;else{var C=O.text.charAt(0);C>="0"&&"9">=C&&(l=!0)}}p=h.call(this,o,e,p,m.field,m.count,l,s),p===f&&(c=p)}}return c>=0?void g(!1,"error when parsing date: "+e+", position: "+e.slice(0,c)+"^"):o}}),r(l,{Style:b,getInstance:function(e){return this.getDateTimeInstance(b.SHORT,b.SHORT,e)},getDateInstance:function(e,t){return this.getDateTimeInstance(e,void 0,t)},getDateTimeInstance:function(e,t,n){var r=n||v,a="";void 0!==e&&(a=r.datePatterns[e]);var i="";void 0!==t&&(i=r.timePatterns[t]);var s=a;return i&&(s=a?o(r.dateTimePattern,{date:a,time:i}):i),new l(s,r)},getTimeInstance:function(e,t){return this.getDateTimeInstance(void 0,e,t)}}),e.exports=l,l.version="@VERSION@"},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){}Object.defineProperty(t,"__esModule",{value:!0});var a=n(1),i=n(292),s=r(i),l=n(12);t["default"]={propTypes:{className:a.PropTypes.string,locale:a.PropTypes.object,style:a.PropTypes.object,visible:a.PropTypes.bool,onSelect:a.PropTypes.func,prefixCls:a.PropTypes.string,onChange:a.PropTypes.func,onOk:a.PropTypes.func},getDefaultProps:function(){return{locale:s["default"],style:{},visible:!0,prefixCls:"rc-calendar",formatter:"yyyy-MM-dd",className:"",onSelect:o,onChange:o,onClear:o}},shouldComponentUpdate:function(e){return this.props.visible||e.visible},getFormatter:function(){var e=this.props.formatter,t=this.props.locale;return this.normalFormatter&&e===this.lastFormatter?this.normalFormatter:(this.normalFormatter=(0,l.getFormatter)(e,t),this.lastFormatter=e,this.normalFormatter)}},e.exports=t["default"]},function(e,t){"use strict";function n(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,a=n(e),i=1;i<arguments.length;i++){r=arguments[i],o=Object.keys(Object(r));for(var s=0;s<o.length;s++)a[o[s]]=r[o[s]]}return a}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n,r,o){var a=e.type,l=[],u=e.required||!e.required&&r.hasOwnProperty(e.field);if(u){if((0,s.isEmptyValue)(t,a)&&!e.required)return n();i["default"].required(e,t,r,l,o,a),(0,s.isEmptyValue)(t,a)||i["default"].type(e,t,r,l,o)}n(l)}Object.defineProperty(t,"__esModule",{value:!0});var a=n(8),i=r(a),s=n(5);t["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.Col=t.Row=void 0;var o=n(191),a=r(o),i=n(190),s=r(i);t.Row=a["default"],t.Col=s["default"]},function(e,t){"use strict";function n(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=e.arrowWidth,n=void 0===t?5:t,a=e.horizontalArrowShift,i=void 0===a?16:a,s=e.verticalArrowShift,l=void 0===s?12:s; return{left:{points:["cr","cl"],overflow:r,offset:[-4,0],targetOffset:o},right:{points:["cl","cr"],overflow:r,offset:[4,0],targetOffset:o},top:{points:["bc","tc"],overflow:r,offset:[0,-4],targetOffset:o},bottom:{points:["tc","bc"],overflow:r,offset:[0,4],targetOffset:o},topLeft:{points:["bl","tc"],overflow:r,offset:[-(i+n),-4],targetOffset:o},leftTop:{points:["tr","cl"],overflow:r,offset:[-4,-(l+n)],targetOffset:o},topRight:{points:["br","tc"],overflow:r,offset:[i+n,-4],targetOffset:o},rightTop:{points:["tl","cr"],overflow:r,offset:[4,-(l+n)],targetOffset:o},bottomRight:{points:["tr","bc"],overflow:r,offset:[i+n,4],targetOffset:o},rightBottom:{points:["bl","cr"],overflow:r,offset:[4,l+n],targetOffset:o},bottomLeft:{points:["tl","bc"],overflow:r,offset:[-(i+n),4],targetOffset:o},leftBottom:{points:["br","cl"],overflow:r,offset:[-4,l+n],targetOffset:o}}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=n;var r={adjustX:1,adjustY:1},o=[0,0];e.exports=t["default"]},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],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(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){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}),t["default"]=void 0;var u,c,p=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},f=n(336),d=r(f),h=n(1),y=r(h),v=n(2),m=r(v),g=n(16),b=r(g),P=(c=u=function(e){function t(){return i(this,t),s(this,e.apply(this,arguments))}return l(t,e),t.prototype.shouldComponentUpdate=function(){for(var e=arguments.length,t=Array(e),n=0;e>n;n++)t[n]=arguments[n];return b["default"].shouldComponentUpdate.apply(this,t)},t.prototype.render=function(){var e,t=this.props,n=t.prefixCls,r=t.children,o=t.checked,i=t.disabled,s=t.className,l=t.style,u=(0,m["default"])((e={},a(e,""+n,!0),a(e,n+"-checked",o),a(e,n+"-disabled",i),a(e,s,!!s),e));return y["default"].createElement("label",{className:u,style:l},y["default"].createElement(d["default"],p({},this.props,{style:null,children:null})),r?y["default"].createElement("span",null,r):null)},t}(y["default"].Component),u.defaultProps={prefixCls:"ant-radio"},c);t["default"]=P,e.exports=t["default"]},[459,441],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],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(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 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):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var l,u,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(107),h=r(d),y=n(32),v=r(y),m=(0,v["default"])({verticalArrowShift:8}),g=(u=l=function(e){function t(n){a(this,t);var r=i(this,e.call(this,n));return r.onVisibleChange=function(e){r.setState({visible:e})},r.onPopupAlign=function(e,t){var n=Object.keys(m).filter(function(e){return m[e].points[0]===t.points[0]&&m[e].points[1]===t.points[1]})[0];if(n){var r=e.getBoundingClientRect(),o={top:"50%",left:"50%"};n.indexOf("top")>=0||n.indexOf("Bottom")>=0?o.top=r.height-t.offset[1]+"px":(n.indexOf("Top")>=0||n.indexOf("bottom")>=0)&&(o.top=-t.offset[1]+"px"),n.indexOf("left")>=0||n.indexOf("Right")>=0?o.left=r.width-t.offset[0]+"px":(n.indexOf("right")>=0||n.indexOf("Left")>=0)&&(o.left=-t.offset[0]+"px"),e.style.transformOrigin=o.left+" "+o.top}},r.state={visible:!1},r}return s(t,e),t.prototype.getPopupDomNode=function(){return this.refs.tooltip.getPopupDomNode()},t.prototype.render=function(){var e=this.props,t=e.prefixCls,n=e.title,r=e.overlay,o=e.children,a=e.transitionName,i=this.state.visible;n||r||(i=!1),"visible"in this.props&&(i=this.props.visible);var s=this.props.openClassName||t+"-open",l=o&&o.props&&o.props.className?o.props.className+" "+s:s;return f["default"].createElement(h["default"],c({transitionName:a,builtinPlacements:m,overlay:n,visible:i,onVisibleChange:this.onVisibleChange,onPopupAlign:this.onPopupAlign,ref:"tooltip"},this.props),i?(0,p.cloneElement)(o,{className:l}):o)},t}(f["default"].Component),l.defaultProps={prefixCls:"ant-tooltip",placement:"top",transitionName:"zoom-big",mouseEnterDelay:.1,mouseLeaveDelay:.1},u);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){for(var n=window.getComputedStyle(e),r="",o=0;o<d.length&&!(r=n.getPropertyValue(d[o]+t));o++);return r}function a(e){if(p){var t=parseFloat(o(e,"transition-duration"))||0,n=parseFloat(o(e,"animation-duration"))||0,r=Math.max(t,n);e.rcEndAnimTimeout=setTimeout(function(){e.rcEndAnimTimeout=null,e.rcEndListener&&e.rcEndListener()},1e3*r+200)}}function i(e){e.rcEndAnimTimeout&&(clearTimeout(e.rcEndAnimTimeout),e.rcEndAnimTimeout=null)}Object.defineProperty(t,"__esModule",{value:!0});var s=n(252),l=r(s),u=n(73),c=r(u),p=0!==l["default"].endEvents.length,f=["Webkit","Moz","O","ms"],d=["-webkit-","-moz-","-o-","ms-",""],h=function(e,t,n){var r=t,o=r+"-active",s=n,u=void 0,p=void 0,f=(0,c["default"])(e);return n&&"[object Object]"===Object.prototype.toString.call(n)&&(s=n.end,u=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),i(e),f.remove(r),f.remove(o),l["default"].removeEndEventListener(e,e.rcEndListener),e.rcEndListener=null,s&&s())},l["default"].addEndEventListener(e,e.rcEndListener),u&&u(),f.add(r),e.rcAnimTimeout=setTimeout(function(){e.rcAnimTimeout=null,f.add(o),p&&setTimeout(p,0),a(e)},30),{stop:function(){e.rcEndListener&&e.rcEndListener()}}};h.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),i(e),l["default"].removeEndEventListener(e,e.rcEndListener),e.rcEndListener=null,n&&n())},l["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,a(e)},0)},h.setTransition=function(e,t,n){var r=t,o=n;void 0===n&&(o=r,r=""),r=r||"",f.forEach(function(t){e.style[t+"Transition"+r]=o})},h.isCssAnimationSupported=p,t["default"]=h,e.exports=t["default"]},function(e,t,n){"use strict";e.exports=n(259)},function(e,t){"use strict";e.exports={eras:["BC","AD"],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"],weekdays:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortWeekdays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],veryShortWeekdays:["Su","Mo","Tu","We","Th","Fr","Sa"],ampms:["AM","PM"],datePatterns:["EEEE, MMMM d, yyyy","MMMM d, yyyy","MMM d, yyyy","M/d/yy"],timePatterns:["h:mm:ss a 'GMT'Z","h:mm:ss a","h:mm:ss a","h:mm a"],dateTimePattern:"{date} {time}"}},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 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 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)}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(289),p=r(c),f=n(288),d=r(f),h=function(e){function t(){return o(this,t),a(this,Object.getPrototypeOf(t).apply(this,arguments))}return i(t,e),s(t,[{key:"render",value:function(){var e=this.props,t=e.prefixCls;return u["default"].createElement("table",{className:t+"-table",cellSpacing:"0",role:"grid"},u["default"].createElement(p["default"],e),u["default"].createElement(d["default"],e))}}]),t}(u["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}}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 a(){}function i(){var e=new d["default"];return e.setTime(Date.now()),e}function s(e){var t=void 0;return e?(t=e.clone(),t.setTime(Date.now())):t=i(),t}Object.defineProperty(t,"__esModule",{value:!0});var l=n(1),u=r(l),c=n(2),p=r(c),f=n(10),d=r(f),h=n(12),y={propTypes:{value:l.PropTypes.object,defaultValue:l.PropTypes.object,onKeyDown:l.PropTypes.func},getDefaultProps:function(){return{onKeyDown:a}},getInitialState:function(){var e=this.props,t=e.value||e.defaultValue||i();return{value:t,selectedValue:e.selectedValue||e.defaultSelectedValue}},componentWillReceiveProps:function(e){var t=e.value,n=e.selectedValue;"value"in e&&(t=t||e.defaultValue||s(this.state.value),this.setState({value:t})),"selectedValue"in e&&this.setState({selectedValue:n})},onSelect:function(e,t){e&&this.setValue(e),this.setSelectedValue(e,t)},renderRoot:function(e){var t,n=this.props,r=n.prefixCls,a=(t={},o(t,r,1),o(t,r+"-hidden",!n.visible),o(t,n.className,!!n.className),o(t,e.className,!!e.className),t);return u["default"].createElement("div",{className:""+(0,p["default"])(a),style:this.props.style,tabIndex:"0",onKeyDown:this.onKeyDown},e.children)},setSelectedValue:function(e,t){this.isAllowedDate(e)&&("selectedValue"in this.props||this.setState({selectedValue:e}),this.props.onSelect(e,t))},setValue:function(e){var t=this.state.value;"value"in this.props||this.setState({value:e}),(t&&e&&t.getTime()!==e.getTime()||!t&&e||t&&!e)&&this.props.onChange(e)},isAllowedDate:function(e){var t=this.props.disabledDate,n=this.props.disabledTime;return(0,h.isAllowedDate)(e,t,n)}};t["default"]=y,e.exports=t["default"]},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],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(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 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):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0});var l=n(1),u=r(l),c=function(e){function t(){return a(this,t),i(this,e.apply(this,arguments))}return s(t,e),t}(u["default"].Component);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){var t=e.props;if("value"in t)return t.value;if(e.key)return e.key;throw new Error("no key or value for "+e)}function a(e,t){return"value"===t?o(e):e.props[t]}function i(e){return e.combobox}function s(e){return e.multiple||e.tags}function l(e){return s(e)||i(e)}function u(e){return!l(e)}function c(e){var t=e;return void 0===e?t=[]:Array.isArray(e)||(t=[e]),t}function p(e){e.preventDefault()}function f(e,t){for(var n=-1,r=0;r<e.length;r++)if(e[r].key===t){n=r;break}return n}function d(e,t){if(null===t||void 0===t)return[];var n=[];return m["default"].Children.forEach(e,function(e){if(e.type===y.ItemGroup)n=n.concat(d(e.props.children,t));else{var r=o(e),a=e.key;-1!==f(t,r)&&a&&n.push(a)}}),n}function h(e){for(var t=0;t<e.length;t++){var n=e[t];if(n.type===y.ItemGroup){var r=h(n.props.children);if(r)return r}else if(!n.props.disabled)return n}return null}Object.defineProperty(t,"__esModule",{value:!0}),t.UNSELECTABLE_ATTRIBUTE=t.UNSELECTABLE_STYLE=void 0,t.getValuePropValue=o,t.getPropValue=a,t.isCombobox=i,t.isMultipleOrTags=s,t.isMultipleOrTagsOrCombobox=l,t.isSingleMode=u,t.toArray=c,t.preventDefaultEvent=p,t.findIndexInValueByKey=f,t.getSelectKeys=d,t.findFirstMenuItem=h;var y=n(21),v=n(1),m=r(v);t.UNSELECTABLE_STYLE={userSelect:"none",WebkitUserSelect:"none"},t.UNSELECTABLE_ATTRIBUTE={unselectable:"unselectable"}},function(e,t,n){(function(e,r){function o(e,t){this._id=e,this._clearFn=t}var a=n(277).nextTick,i=Function.prototype.apply,s=Array.prototype.slice,l={},u=0;t.setTimeout=function(){return new o(i.call(setTimeout,window,arguments),clearTimeout)},t.setInterval=function(){return new o(i.call(setInterval,window,arguments),clearInterval)},t.clearTimeout=t.clearInterval=function(e){e.close()},o.prototype.unref=o.prototype.ref=function(){},o.prototype.close=function(){this._clearFn.call(window,this._id)},t.enroll=function(e,t){clearTimeout(e._idleTimeoutId),e._idleTimeout=t},t.unenroll=function(e){clearTimeout(e._idleTimeoutId),e._idleTimeout=-1},t._unrefActive=t.active=function(e){clearTimeout(e._idleTimeoutId);var t=e._idleTimeout;t>=0&&(e._idleTimeoutId=setTimeout(function(){e._onTimeout&&e._onTimeout()},t))},t.setImmediate="function"==typeof e?e:function(e){var n=u++,r=arguments.length<2?!1:s.call(arguments,1);return l[n]=!0,a(function(){l[n]&&(r?e.apply(null,r):e.call(null),t.clearImmediate(n))}),n},t.clearImmediate="function"==typeof r?r:function(e){delete l[e]}}).call(t,n(43).setImmediate,n(43).clearImmediate)},function(e,t){e.exports=function(e){return e.webpackPolyfill||(e.deprecate=function(){},e.paths=[],e.children=[],e.webpackPolyfill=1),e}},3,function(e,t){function n(e,t,n){n=n||{},n.childrenKeyName=n.childrenKeyName||"children";var r,o=e||[],a=[],i=0;do{var r=o.filter(function(e){return t(e,i)})[0];if(!r)break;a.push(r),o=r[n.childrenKeyName]||[],i+=1}while(o.length>0);return a}e.exports=n},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,n,r,o,a){!e.required||n.hasOwnProperty(e.field)&&!i.isEmptyValue(t,a)||r.push(i.format(o.messages.required,e.fullField))}Object.defineProperty(t,"__esModule",{value:!0});var a=n(5),i=r(a);t["default"]=o,e.exports=t["default"]},function(e,t){"use strict";function n(){if(void 0!==r)return r;var e="Webkit Moz O ms Khtml".split(" "),t=document.createElement("div");if(void 0!==t.style.animationName&&(r=!0),void 0!==r)for(var n=0;n<e.length;n++)if(void 0!==t.style[e[n]+"AnimationName"]){r=!0;break}return r=r||!1}Object.defineProperty(t,"__esModule",{value:!0});var r=void 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){var r=void 0;return(0,i["default"])(e,"ant-motion-collapse",{start:function(){t?(r=e.offsetHeight,e.style.height=0):e.style.height=e.offsetHeight+"px"},active:function(){e.style.height=(t?r:0)+"px"},end:function(){e.style.height="",n()}})}Object.defineProperty(t,"__esModule",{value:!0});var a=n(36),i=r(a),s={enter:function(e,t){return o(e,!0,t)},leave:function(e,t){return o(e,!1,t)},appear:function(e,t){return o(e,!0,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){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return 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 i(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}),t["default"]=void 0;var u,c,p=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},f=n(1),d=r(f),h=(c=u=function(e){function t(){return i(this,t),s(this,e.apply(this,arguments))}return l(t,e),t.prototype.render=function(){var e=this.props,t=e.prefixCls,n=e.separator,r=e.children,o=a(e,["prefixCls","separator","children"]),i=void 0;return i="href"in this.props?d["default"].createElement("a",p({className:t+"-link"},o),r):d["default"].createElement("span",p({className:t+"-link"},o),r),d["default"].createElement("span",null,i,d["default"].createElement("span",{className:t+"-separator"},n))},t}(d["default"].Component),u.defaultProps={prefixCls:"ant-breadcrumb",separator:"/"},u.propTypes={prefixCls:d["default"].PropTypes.string,separator:d["default"].PropTypes.oneOfType([d["default"].PropTypes.string,d["default"].PropTypes.element]),href:d["default"].PropTypes.string},c);t["default"]=h,e.exports=t["default"]},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});t.PREFIX_CLS="ant-fullcalendar"},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},a=n(80),i=r(a),s=n(91),l=r(s),u=n(68),c=r(u),p=o({},i["default"]);p.lang=o({placeholder:"\u8bf7\u9009\u62e9\u65e5\u671f",rangePlaceholder:["\u5f00\u59cb\u65e5\u671f","\u7ed3\u675f\u65e5\u671f"]},l["default"]),p.timePickerLocale=o({},c["default"]),p.lang.ok="\u786e \u5b9a",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){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return 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 i(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}),t["default"]=void 0;var u,c,p=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},f=n(1),d=r(f),h=n(309),y=r(h),v=(c=u=function(e){function t(){return i(this,t),s(this,e.apply(this,arguments))}return l(t,e),t.prototype.render=function(){var e=this.props,t=e.overlay,n=a(e,["overlay"]),r=d["default"].cloneElement(t,{openTransitionName:"zoom-big"});return d["default"].createElement(y["default"],p({},n,{overlay:r}))},t}(d["default"].Component),u.defaultProps={transitionName:"slide-up",prefixCls:"ant-dropdown",mouseEnterDelay:.15,mouseLeaveDelay:.1},c);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(53),a=r(o),i=n(178),s=r(i);a["default"].Button=s["default"],t["default"]=a["default"],e.exports=t["default"]},[461,430],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(188),a=r(o),i=n(187),s=r(i);a["default"].Group=s["default"],t["default"]=a["default"],e.exports=t["default"]},[459,45],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],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(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 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):o(e,t))}function l(){}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var u,c,p=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},f=n(1),d=r(f),h=n(307),y=r(h),v=n(6),m=n(15),g=r(m),b=void 0,P=void 0,O=(c=u=function(e){function t(){var n,r,o;a(this,t);for(var s=arguments.length,l=Array(s),u=0;s>u;u++)l[u]=arguments[u];return n=r=i(this,e.call.apply(e,[this].concat(l))),r.handleCancel=function(e){r.props.onCancel(e)},r.handleOk=function(){r.props.onOk()},o=n,i(r,o)}return s(t,e),t.prototype.componentDidMount=function(){P||(v.Dom.addEventListener(document.documentElement,"click",function(e){b={x:e.pageX,y:e.pageY},setTimeout(function(){return b=null},20)}),P=!0)},t.prototype.render=function(){var e=this.props,t=e.okText,n=e.cancelText;this.context.antLocale&&this.context.antLocale.Modal&&(t=t||this.context.antLocale.Modal.okText,n=n||this.context.antLocale.Modal.cancelText);var r=[d["default"].createElement(g["default"],{key:"cancel",type:"ghost",size:"large",onClick:this.handleCancel},n||"\u53d6\u6d88"),d["default"].createElement(g["default"],{key:"confirm",type:"primary",size:"large",loading:e.confirmLoading,onClick:this.handleOk},t||"\u786e\u5b9a")],o=e.footer||r;return d["default"].createElement(y["default"],p({onClose:this.handleCancel,footer:o},e,{visible:e.visible,mousePosition:b}))},t}(d["default"].Component),u.defaultProps={prefixCls:"ant-modal",onOk:l,onCancel:l,width:520,transitionName:"zoom",maskTransitionName:"fade",confirmLoading:!1,visible:!1},u.propTypes={prefixCls:f.PropTypes.string,onOk:f.PropTypes.func,onCancel:f.PropTypes.func,okText:f.PropTypes.node,cancelText:f.PropTypes.node,width:f.PropTypes.oneOfType([f.PropTypes.number,f.PropTypes.string]),confirmLoading:f.PropTypes.bool,visible:f.PropTypes.bool,align:f.PropTypes.object,footer:f.PropTypes.node,title:f.PropTypes.node,closable:f.PropTypes.bool},u.contextTypes={antLocale:d["default"].PropTypes.object},c);t["default"]=O,e.exports=t["default"]},function(e,t){"use strict";function n(e){i=e?o({},i,e):o({},a)}function r(){return i}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.changeConfirmLocale=n,t.getConfirmLocale=r;var a={okText:"\u786e\u5b9a",cancelText:"\u53d6\u6d88",justOkText:"\u77e5\u9053\u4e86"},i=o({},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(204),a=r(o);t["default"]=a["default"],e.exports=t["default"]},function(e,t,n){"use strict";n(3),n(438),n(26),n(13)},[459,439],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},a=n(1),i=r(a),s=n(209),l=r(s),u=n(17),c=r(u),p=l["default"];p.Line=function(e){return(0,c["default"])(!1,'<Progress.Line /> is deprecated, use <Progress type="line" /> instead.'),i["default"].createElement(l["default"],o({},e,{type:"line"}))},p.Circle=function(e){return(0,c["default"])(!1,'<Progress.Circle /> is deprecated, use <Progress type="circle" /> instead.'),i["default"].createElement(l["default"],o({},e,{type:"circle"}))},t["default"]=p,e.exports=t["default"]},[459,440],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],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(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 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):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var l,u,c=n(1),p=r(c),f=n(33),d=r(f),h=(u=l=function(e){function t(){return a(this,t),i(this,e.apply(this,arguments))}return s(t,e),t.prototype.render=function(){return p["default"].createElement(d["default"],this.props)},t}(p["default"].Component),l.defaultProps={prefixCls:"ant-radio-button"},u);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,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(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 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}),t["default"]=void 0;var c,p,f=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),h=r(d),y=n(4),v=n(2),m=r(v),g=n(48),b=r(g),P=n(17),O=r(P),C=(p=c=function(e){function t(n){s(this,t);var r=l(this,e.call(this,n)),o=r.getSpinning(n);return r.state={spinning:o},r}return u(t,e),t.prototype.isNestedPattern=function(){return!(!this.props||!this.props.children)},t.prototype.componentDidMount=function(){(0,O["default"])(!("spining"in this.props),"`spining` property of Popover is a spell mistake, use `spinning` instead."),(0,b["default"])()||((0,y.findDOMNode)(this).className+=" "+this.props.prefixCls+"-show-text")},t.prototype.componentWillUnmount=function(){this.debounceTimeout&&clearTimeout(this.debounceTimeout)},t.prototype.getSpinning=function(e){return"spining"in e?((0,O["default"])(!1,"`spining` property of Spin is a spell mistake, use `spinning` instead."),e.spining):e.spinning},t.prototype.componentWillReceiveProps=function(e){var t=this,n=this.getSpinning(e);this.debounceTimeout&&clearTimeout(this.debounceTimeout),n?this.debounceTimeout=setTimeout(function(){return t.setState({spinning:n})},250):this.setState({spinning:n})},t.prototype.render=function(){var e,t=this.props,n=t.className,r=t.size,o=t.prefixCls,s=t.tip,l=i(t,["className","size","prefixCls","tip"]),u=this.state.spinning,c=(0,m["default"])((e={},a(e,o,!0),a(e,o+"-sm","small"===r),a(e,o+"-lg","large"===r),a(e,o+"-spinning",u),a(e,o+"-show-text",!!this.props.tip),a(e,n,!!n),e)),p=h["default"].createElement("div",f({},l,{className:c}),h["default"].createElement("span",{className:o+"-dot "+o+"-dot-first"}),h["default"].createElement("span",{className:o+"-dot "+o+"-dot-second"}),h["default"].createElement("span",{className:o+"-dot "+o+"-dot-third"}),h["default"].createElement("div",{className:o+"-text"},s||"\u52a0\u8f7d\u4e2d..."));return this.isNestedPattern()?h["default"].createElement("div",f({},l,{className:u?o+"-nested-loading":""}),p,h["default"].createElement("div",{className:o+"-container"},this.props.children)):p},t}(h["default"].Component),c.defaultProps={prefixCls:"ant-spin",spinning:!0},c.propTypes={className:h["default"].PropTypes.string,size:h["default"].PropTypes.oneOf(["small","default","large"])},p);t["default"]=C,e.exports=t["default"]},[459,445],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},a=n(369),i=r(a),s=o({placeholder:"\u8bf7\u9009\u62e9\u65f6\u95f4"},i["default"]);t["default"]=s,e.exports=t["default"]},[460,451],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],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e; }function a(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 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}),t["default"]=void 0;var c,p,f=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),h=r(d),y=n(2),v=r(y),m=(p=c=function(e){function t(){return s(this,t),l(this,e.apply(this,arguments))}return u(t,e),t.prototype.render=function(){var e,t,n=this.props,r=n.prefixCls,o=n.color,s=n.last,l=n.children,u=n.pending,c=n.className,p=n.dot,d=i(n,["prefixCls","color","last","children","pending","className","dot"]),y=(0,v["default"])((e={},a(e,r+"-item",!0),a(e,r+"-item-last",s),a(e,r+"-item-pending",u),a(e,c,c),e)),m=(0,v["default"])((t={},a(t,r+"-item-head",!0),a(t,r+"-item-head-custom",p),a(t,r+"-item-head-"+o,!0),t));return h["default"].createElement("li",f({},d,{className:y}),h["default"].createElement("div",{className:r+"-item-tail"}),h["default"].createElement("div",{className:m,style:{color:/blue|red|green/.test(o)?null:o}},p),h["default"].createElement("div",{className:r+"-item-content"},l))},t}(h["default"].Component),c.defaultProps={prefixCls:"ant-timeline",color:"blue",last:!1,pending:!1},p);t["default"]=m,e.exports=t["default"]},[459,453],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],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(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 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):o(e,t))}function l(){}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var u,c,p=n(1),f=r(p),d=n(7),h=r(d),y=(c=u=function(e){function t(){var n,r,o;a(this,t);for(var s=arguments.length,l=Array(s),u=0;s>u;u++)l[u]=arguments[u];return n=r=i(this,e.call.apply(e,[this].concat(l))),r.handleChange=function(e){r.props.onChange(e)},r.handleClear=function(e){e.preventDefault(),r.props.handleClear(e)},o=n,i(r,o)}return s(t,e),t.prototype.render=function(){var e=this.props,t=e.placeholder,n=e.value,r=e.prefixCls;return f["default"].createElement("div",null,f["default"].createElement("input",{placeholder:t,className:r+" ant-input",value:n,ref:"input",onChange:this.handleChange}),n&&n.length>0?f["default"].createElement("a",{href:"#",className:r+"-action",onClick:this.handleClear},f["default"].createElement(h["default"],{type:"cross-circle"})):f["default"].createElement("span",{className:r+"-action"},f["default"].createElement(h["default"],{type:"search"})))},t}(f["default"].Component),u.defaultProps={placeholder:"",onChange:l,handleClear:l},u.propTypes={prefixCls:p.PropTypes.string,placeholder:p.PropTypes.string,onChange:p.PropTypes.func,handleClear:p.PropTypes.func},c);t["default"]=y,e.exports=t["default"]},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(74)}catch(a){var o=n(74)}var i=/\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(i);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){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){"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=i["default"].css(e,"position"),a="fixed"===o||"absolute"===o;if(!a)return"html"===e.nodeName.toLowerCase()?null:e.parentNode;for(r=e.parentNode;r&&r!==n;r=r.parentNode)if(o=i["default"].css(r,"position"),"static"!==o)return r;return null}Object.defineProperty(t,"__esModule",{value:!0});var a=n(20),i=r(a);t["default"]=o,e.exports=t["default"]},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";e.exports={eras:["\u516c\u5143\u524d","\u516c\u5143"],months:["\u4e00\u6708","\u4e8c\u6708","\u4e09\u6708","\u56db\u6708","\u4e94\u6708","\u516d\u6708","\u4e03\u6708","\u516b\u6708","\u4e5d\u6708","\u5341\u6708","\u5341\u4e00\u6708","\u5341\u4e8c\u6708"],shortMonths:["\u4e00\u6708","\u4e8c\u6708","\u4e09\u6708","\u56db\u6708","\u4e94\u6708","\u516d\u6708","\u4e03\u6708","\u516b\u6708","\u4e5d\u6708","\u5341\u6708","\u5341\u4e00\u6708","\u5341\u4e8c\u6708"],weekdays:["\u661f\u671f\u5929","\u661f\u671f\u4e00","\u661f\u671f\u4e8c","\u661f\u671f\u4e09","\u661f\u671f\u56db","\u661f\u671f\u4e94","\u661f\u671f\u516d"],shortWeekdays:["\u5468\u65e5","\u5468\u4e00","\u5468\u4e8c","\u5468\u4e09","\u5468\u56db","\u5468\u4e94","\u5468\u516d"],veryShortWeekdays:["\u65e5","\u4e00","\u4e8c","\u4e09","\u56db","\u4e94","\u516d"],ampms:["\u4e0a\u5348","\u4e0b\u5348"],datePatterns:["yyyy'\u5e74'M'\u6708'd'\u65e5' EEEE","yyyy'\u5e74'M'\u6708'd'\u65e5'","yyyy-M-d","yy-M-d"],timePatterns:["ahh'\u65f6'mm'\u5206'ss'\u79d2' 'GMT'Z","ahh'\u65f6'mm'\u5206'ss'\u79d2'","H:mm:ss","ah:mm"],dateTimePattern:"{date} {time}"}},function(e,t){"use strict";e.exports={SUNDAY:0,MONDAY:1,TUESDAY:2,WEDNESDAY:3,THURSDAY:4,FRIDAY:5,SATURDAY:6,JANUARY:0,FEBRUARY:1,MARCH:2,APRIL:3,MAY:4,JUNE:5,JULY:6,AUGUST:7,SEPTEMBER:8,OCTOBER:9,NOVEMBER:10,DECEMBER:11}},function(e,t){"use strict";e.exports={timezoneOffset:-480,firstDayOfWeek:0,minimalDaysInFirstWeek:1}},function(e,t){"use strict";e.exports={timezoneOffset:480,firstDayOfWeek:1,minimalDaysInFirstWeek:1}},function(e,t,n){var r=n(416),o=function(e){var t=/[height|width]$/;return t.test(e)},a=function(e){var t="",n=Object.keys(e);return n.forEach(function(a,i){var s=e[a];a=r(a),o(a)&&"number"==typeof s&&(s+="px"),t+=s===!0?a:s===!1?"not "+a:"("+a+": "+s+")",i<n.length-1&&(t+=" and ")}),t},i=function(e){var t="";return"string"==typeof e?e:e instanceof Array?(e.forEach(function(n,r){t+=a(n),r<e.length-1&&(t+=", ")}),t):a(e)};e.exports=i},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";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(1),a=r(o),i=n(92),s=r(i),l=n(40),u=r(l),c=n(28),p=r(c),f=n(6),d=a["default"].createClass({displayName:"MonthCalendar",mixins:[p["default"],u["default"]],onKeyDown:function(e){var t=e.keyCode,n=e.ctrlKey||e.metaKey,r=this.state.value,o=r;switch(t){case f.KeyCode.DOWN:o=r.clone(),o.addMonth(3);break;case f.KeyCode.UP:o=r.clone(),o.addMonth(-3);break;case f.KeyCode.LEFT:o=r.clone(),n?o.addYear(-1):o.addMonth(-1);break;case f.KeyCode.RIGHT:o=r.clone(),n?o.addYear(1):o.addMonth(1);break;case f.KeyCode.ENTER:return this.onSelect(r),e.preventDefault(),1;default:return}return o!==r?(this.setValue(o),e.preventDefault(),1):void 0},render:function(){var e=this.props,t=a["default"].createElement(s["default"],{locale:e.locale,disabledDate:e.disabledDate,style:{position:"relative"},value:this.state.value,rootPrefixCls:e.prefixCls,onChange:this.setValue,onSelect:this.onSelect});return this.renderRoot({children:t})}});t["default"]=d,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){}function a(e,t){this[e]=t}Object.defineProperty(t,"__esModule",{value:!0});var i=n(1),s=r(i),l=n(4),u=r(l),c=n(6),p=n(293),f=r(p),d=n(14),h=r(d),y=s["default"].createClass({displayName:"Picker",propTypes:{animation:i.PropTypes.oneOfType([i.PropTypes.func,i.PropTypes.string]),disabled:i.PropTypes.bool,transitionName:i.PropTypes.string,onChange:i.PropTypes.func,onOpen:i.PropTypes.func,onClose:i.PropTypes.func,children:i.PropTypes.func,getCalendarContainer:i.PropTypes.func,calendar:i.PropTypes.element,style:i.PropTypes.object,open:i.PropTypes.bool,defaultOpen:i.PropTypes.bool,prefixCls:i.PropTypes.string,placement:i.PropTypes.any,value:i.PropTypes.oneOfType([i.PropTypes.object,i.PropTypes.array]),defaultValue:i.PropTypes.oneOfType([i.PropTypes.object,i.PropTypes.array]),align:i.PropTypes.object},getDefaultProps:function(){return{prefixCls:"rc-calendar-picker",style:{},align:{},placement:"bottomLeft",defaultOpen:!1,onChange:o,onOpen:o,onClose:o}},getInitialState:function(){var e=this.props,t=void 0;t="open"in e?e.open:e.defaultOpen;var n=e.value||e.defaultValue;return this.saveCalendarRef=a.bind(this,"calendarInstance"),{open:t,value:n}},componentWillReceiveProps:function(e){var t=e.value,n=e.open;"value"in e&&this.setState({value:t}),void 0!==n&&this.setState({open:n})},onCalendarKeyDown:function(e){e.keyCode===c.KeyCode.ESC&&(e.stopPropagation(),this.close(this.focus))},onCalendarSelect:function(e){var t=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],n=this.props;"value"in n||this.setState({value:e}),(!n.calendar.props.timePicker&&"dateInput"!==t.source||"todayButton"===t.source)&&this.close(this.focus),n.onChange(e)},onCalendarOk:function(){this.close(this.focus)},onCalendarClear:function(){this.close(this.focus)},onVisibleChange:function(e){var t=this;this.setOpen(e,function(){e&&u["default"].findDOMNode(t.calendarInstance).focus()})},getCalendarElement:function(){var e=this.props,t=this.state,n=e.calendar,r=t.value,o=void 0;o=Array.isArray(r)?r[0]:r;var a={ref:this.saveCalendarRef,defaultValue:o||n.props.defaultValue,defaultSelectedValue:r,onKeyDown:this.onCalendarKeyDown,onOk:(0,c.createChainedFunction)(n.props.onOk,this.onCalendarOk),onSelect:(0,c.createChainedFunction)(n.props.onSelect,this.onCalendarSelect),onClear:(0,c.createChainedFunction)(n.props.onClear,this.onCalendarClear)};return s["default"].cloneElement(n,a)},setOpen:function(e,t){var n=this.props,r=n.onOpen,o=n.onClose;if(this.state.open!==e){this.setState({open:e},t);var a={open:e};e?r(a):o(a)}},open:function(e){this.setOpen(!0,e)},close:function(e){this.setOpen(!1,e)},focus:function(){this.state.open||u["default"].findDOMNode(this).focus()},render:function(){var e=this.props,t=e.prefixCls,n=e.placement,r=e.style,o=e.getCalendarContainer,a=e.align,i=e.animation,l=e.disabled,u=e.transitionName,c=e.children,p=this.state;return s["default"].createElement(h["default"],{popup:this.getCalendarElement(),popupAlign:a,builtinPlacements:f["default"],popupPlacement:n,action:l?[]:["click"],destroyPopupOnHide:!0,getPopupContainer:o,popupStyle:r,popupAnimation:i,popupTransitionName:u,popupVisible:p.open,onPopupVisibleChange:this.onVisibleChange,prefixCls:t},c(p,e))}});t["default"]=y,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=this.props.value.clone();t.addMonth(e),this.props.onValueChange(t)}function a(e){var t=this.props.value.clone();t.addYear(e),this.props.onValueChange(t)}Object.defineProperty(t,"__esModule",{value:!0});var i=n(1),s=r(i),l=n(92),u=r(l),c=n(12),p=n(94),f=r(p),d=n(6),h=r(d),y=h["default"].Children.mapSelf,v=s["default"].createClass({displayName:"CalendarHeader",propTypes:{enablePrev:i.PropTypes.any,enableNext:i.PropTypes.any,prefixCls:i.PropTypes.string,locale:i.PropTypes.object,value:i.PropTypes.object,onValueChange:i.PropTypes.func},getDefaultProps:function(){return{enableNext:1,enablePrev:1}},getInitialState:function(){var e=this.props;return this.yearFormatter=(0,c.getFormatter)(e.locale.yearFormat,e.locale),this.monthFormatter=(0,c.getFormatter)(e.locale.monthFormat,e.locale),this.nextMonth=o.bind(this,1),this.previousMonth=o.bind(this,-1),this.nextYear=a.bind(this,1),this.previousYear=a.bind(this,-1),{}},componentWillReceiveProps:function(e){var t=this.props.locale,n=e.locale;n!==t&&(this.yearFormatter=(0,c.getFormatter)(n.yearFormat,n),this.monthFormatter=(0,c.getFormatter)(n.monthFormat,n))},onSelect:function(e){this.setState({showMonthPanel:0,showYearPanel:0}),this.props.onValueChange(e)},getMonthYearElement:function(){var e=this.props,t=e.prefixCls,n=e.locale,r=this.props.value,o=n.monthBeforeYear,a=t+"-"+(o?"my-select":"ym-select"),i=s["default"].createElement("a",{className:t+"-year-select",role:"button",onClick:this.showYearPanel,title:n.monthSelect},this.yearFormatter.format(r)),l=s["default"].createElement("a",{className:t+"-month-select",role:"button",onClick:this.showMonthPanel,title:n.monthSelect},this.monthFormatter.format(r)),u=[];return u=o?[l,i]:[i,l],s["default"].createElement("span",{className:a},y(u))},showIf:function(e,t){return e?t:null},showMonthPanel:function(){this.setState({showMonthPanel:1,showYearPanel:0})},showYearPanel:function(){this.setState({showMonthPanel:0,showYearPanel:1})},render:function(){var e=this.props,t=e.enableNext,n=e.enablePrev,r=e.prefixCls,o=e.locale,a=e.value,i=this.state,l=null;i.showMonthPanel?l=u["default"]:i.showYearPanel&&(l=f["default"]);var c=void 0;return l&&(c=s["default"].createElement(l,{locale:o,defaultValue:a,rootPrefixCls:r,onSelect:this.onSelect})),s["default"].createElement("div",{className:r+"-header"},s["default"].createElement("div",{style:{position:"relative"}},this.showIf(n,s["default"].createElement("a",{className:r+"-prev-year-btn",role:"button",onClick:this.previousYear,title:o.previousYear},"\xab")),this.showIf(n,s["default"].createElement("a",{className:r+"-prev-month-btn",role:"button",onClick:this.previousMonth,title:o.previousMonth},"\u2039")),this.getMonthYearElement(),this.showIf(t,s["default"].createElement("a",{className:r+"-next-month-btn",onClick:this.nextMonth,title:o.nextMonth},"\u203a")),this.showIf(t,s["default"].createElement("a",{className:r+"-next-year-btn",onClick:this.nextYear,title:o.nextYear},"\xbb"))),c)}});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=e.prefixCls,n=e.locale,r=e.okDisabled,o=e.onOk,a=t+"-ok-btn";return r&&(a+=" "+t+"-ok-btn-disabled"),i["default"].createElement("a",{className:a,role:"button",onClick:r?null:o},n.ok)}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var a=n(1),i=r(a);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.prefixCls,n=e.locale,r=e.value,o=e.timePicker,a=e.disabledDate,l=e.disabledTime,u=e.onToday,c=!1,p=n.today;o&&(p=n.now||n.today);var f="";return a&&(c=!(0,s.isAllowedDate)((0,s.getTodayTime)(r),a,l),c&&(f=t+"-today-btn-disabled")),i["default"].createElement("a",{className:t+"-today-btn "+f,role:"button",onClick:c?null:u,title:(0,s.getTodayTimeStr)(r)},p)}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var a=n(1),i=r(a),s=n(12);e.exports=t["default"]},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t["default"]={DATE_ROW_COUNT:6,DATE_COL_COUNT:7},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 t&&(e.setHourOfDay(t.getHourOfDay()),e.setMinutes(t.getMinutes()),e.setSeconds(t.getSeconds())),e}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},i=n(1),s=r(i),l=n(4),u=r(l),c=n(12),p=s["default"].createClass({displayName:"DateInput",propTypes:{prefixCls:i.PropTypes.string,timePicker:i.PropTypes.object,disabledTime:i.PropTypes.any,formatter:i.PropTypes.object,locale:i.PropTypes.object,gregorianCalendarLocale:i.PropTypes.object,disabledDate:i.PropTypes.func,onChange:i.PropTypes.func,onClear:i.PropTypes.func,placeholder:i.PropTypes.string,onSelect:i.PropTypes.func,selectedValue:i.PropTypes.object},getInitialState:function(){var e=this.props.selectedValue;return{str:e&&this.props.formatter.format(e)||"",invalid:!1}},componentWillReceiveProps:function(e){var t=e.selectedValue;this.setState({str:t&&e.formatter.format(t)||"",invalid:!1})},onInputChange:function(e){var t=e.target.value;this.setState({str:t});var n=void 0,r=this.props,a=r.disabledDate,i=r.formatter,s=r.gregorianCalendarLocale,l=r.onChange;if(t){try{n=o(i.parse(t,{locale:s,obeyCount:!0}),this.props.selectedValue)}catch(u){return void this.setState({invalid:!0})}if(!n||a&&a(n))return void this.setState({invalid:!0});var c=this.props.selectedValue;c&&n?c.getTime()!==n.getTime()&&l(n):c!==n&&l(n)}else l(null);this.setState({invalid:!1})},onClear:function(){this.setState({str:""}),this.props.onClear(null)},getRootDOMNode:function(){return u["default"].findDOMNode(this)},render:function(){var e=this.props,t=this.state,n=t.invalid,r=t.str,o=e.selectedValue,i=e.locale,l=e.prefixCls,u=e.placeholder,p=e.onChange,f=e.timePicker,d=e.disabledTime,h=e.gregorianCalendarLocale,y=n?l+"-input-invalid":"",v=d&&f?(0,c.getTimeConfig)(o,d):null;return s["default"].createElement("div",{className:l+"-input-wrap"},s["default"].createElement("div",{className:l+"-time-picker-wrap"},f?s["default"].cloneElement(f,a({showClear:!1,allowEmpty:!1,getPopupContainer:this.getRootDOMNode,gregorianCalendarLocale:h,value:o,onChange:p},v)):null),s["default"].createElement("div",{className:l+"-date-input-wrap"},s["default"].createElement("input",{className:l+"-input "+y,value:r,placeholder:u,onChange:this.onInputChange})),e.showClear?s["default"].createElement("a",{className:l+"-clear-btn",role:"button",title:i.clear,onClick:this.onClear}):null)}});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(284),a=r(o);t["default"]=a["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(77),a=r(o);t["default"]={today:"\u4eca\u5929",now:"\u6b64\u523b",ok:"\u786e\u5b9a",clear:"\u6e05\u9664",month:"\u6708",year:"\u5e74",previousMonth:"\u4e0a\u4e2a\u6708 (\u7ffb\u9875\u4e0a\u952e)",nextMonth:"\u4e0b\u4e2a\u6708 (\u7ffb\u9875\u4e0b\u952e)",monthSelect:"\u9009\u62e9\u6708\u4efd",yearSelect:"\u9009\u62e9\u5e74\u4efd",decadeSelect:"\u9009\u62e9\u5e74\u4ee3",yearFormat:"yyyy'\u5e74'",monthFormat:"M'\u6708'",dateFormat:"yyyy'\u5e74'M'\u6708'd'\u65e5'",previousYear:"\u4e0a\u4e00\u5e74 (Control\u952e\u52a0\u5de6\u65b9\u5411\u952e)",nextYear:"\u4e0b\u4e00\u5e74 (Control\u952e\u52a0\u53f3\u65b9\u5411\u952e)",previousDecade:"\u4e0a\u4e00\u5e74\u4ee3",nextDecade:"\u4e0b\u4e00\u5e74\u4ee3",previousCentury:"\u4e0a\u4e00\u4e16\u7eaa",nextCentury:"\u4e0b\u4e00\u4e16\u7eaa",format:a["default"]},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=this.state.value.clone();t.addYear(e),this.setAndChangeValue(t)}function a(){}Object.defineProperty(t,"__esModule",{value:!0});var i=n(1),s=r(i),l=n(94),u=r(l),c=n(93),p=r(c),f=s["default"].createClass({displayName:"MonthPanel",propTypes:{onChange:i.PropTypes.func,disabledDate:i.PropTypes.func,onSelect:i.PropTypes.func},getDefaultProps:function(){return{onChange:a,onSelect:a}},getInitialState:function(){var e=this.props;return this.nextYear=o.bind(this,1),this.previousYear=o.bind(this,-1),this.prefixCls=e.rootPrefixCls+"-month-panel",{value:e.value||e.defaultValue}},componentWillReceiveProps:function(e){"value"in e&&this.setState({value:e.value})},onYearPanelSelect:function(e){this.setState({showYearPanel:0}),this.setAndChangeValue(e)},setAndChangeValue:function(e){this.setValue(e),this.props.onChange(e)},setAndSelectValue:function(e){this.setValue(e),this.props.onSelect(e)},setValue:function(e){"value"in this.props||this.setState({value:e})},showYearPanel:function(){this.setState({showYearPanel:1})},render:function(){var e=this.props,t=this.state.value,n=e.locale,r=t.getYear(),o=this.prefixCls,a=void 0;return this.state.showYearPanel&&(a=s["default"].createElement(u["default"],{locale:n,value:t,rootPrefixCls:e.rootPrefixCls,onSelect:this.onYearPanelSelect})),s["default"].createElement("div",{className:o,style:e.style},s["default"].createElement("div",null,s["default"].createElement("div",{className:o+"-header"},s["default"].createElement("a",{className:o+"-prev-year-btn",role:"button",onClick:this.previousYear,title:n.previousYear},"\xab"),s["default"].createElement("a",{className:o+"-year-select",role:"button",onClick:this.showYearPanel,title:n.yearSelect},s["default"].createElement("span",{className:o+"-year-select-content"},r),s["default"].createElement("span",{className:o+"-year-select-arrow"},"x")),s["default"].createElement("a",{className:o+"-next-year-btn",role:"button",onClick:this.nextYear,title:n.nextYear},"\xbb")),s["default"].createElement("div",{className:o+"-body"},s["default"].createElement(p["default"],{disabledDate:e.disabledDate,onSelect:this.setAndSelectValue,locale:n,value:t,prefixCls:o}))),a)}});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}function a(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 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)}function l(e){var t=this.state.value.clone();t.rollSetMonth(e),this.setAndSelectValue(t)}function u(){}Object.defineProperty(t,"__esModule",{value:!0});var c=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}}(),p=n(1),f=r(p),d=n(2),h=r(d),y=4,v=3,m=function(e){function t(e){a(this,t);var n=i(this,Object.getPrototypeOf(t).call(this,e));return n.state={value:e.value},n}return s(t,e),c(t,[{key:"componentWillReceiveProps",value:function(e){"value"in e&&this.setState({value:e.value})}},{key:"getMonths",value:function(){for(var e=this.props,t=this.state.value,n=t.clone(),r=e.locale,o=[],a=r.format.shortMonths,i=0,s=0;y>s;s++){o[s]=[];for(var l=0;v>l;l++)n.rollSetMonth(i),o[s][l]={value:i,content:a[i],title:a[i]},i++}return o}},{key:"setAndSelectValue",value:function(e){this.setState({value:e}),this.props.onSelect(e)}},{key:"render",value:function(){var e=this,t=this.props,n=this.state.value,r=n.clone();r.setTime(Date.now());var a=this.getMonths(),i=n.getMonth(),s=t.prefixCls,u=t.locale,c=t.contentRender,p=t.cellRender,d=a.map(function(a,d){var y=a.map(function(a){var d,y=!1;if(t.disabledDate){var v=n.clone();v.rollSetMonth(a.value),y=t.disabledDate(v)}var m=(d={},o(d,s+"-cell",1),o(d,s+"-cell-disabled",y),o(d,s+"-selected-cell",a.value===i),o(d,s+"-current-cell",r.getYear()===n.getYear()&&a.value===r.getMonth()),d),g=void 0;if(p){var b=n.clone();b.rollSetMonth(a.value),g=p(b,u)}else{var P=void 0;if(c){var O=n.clone();O.rollSetMonth(a.value),P=c(O,u)}else P=a.content;g=f["default"].createElement("div",{className:s+"-month"},P)}return f["default"].createElement("td",{role:"gridcell",key:a.value,onClick:y?null:l.bind(e,a.value),title:a.title,className:(0,h["default"])(m)},g)});return f["default"].createElement("tr",{key:d,role:"row"},y)});return f["default"].createElement("table",{className:s+"-table",cellSpacing:"0",role:"grid"},f["default"].createElement("tbody",{className:s+"-tbody"},d))}}]),t}(p.Component);m.defaultProps={onSelect:u},m.propTypes={onSelect:p.PropTypes.func,cellRender:p.PropTypes.func,prefixCls:p.PropTypes.string,value:p.PropTypes.object},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 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 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 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)}function l(e){var t=this.state.value.clone();t.addYear(e),this.setState({value:t})}function u(e){var t=this.state.value.clone();t.setYear(e),t.rollSetMonth(this.state.value.getMonth()),this.props.onSelect(t)}Object.defineProperty(t,"__esModule",{value:!0});var c=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}}(),p=n(1),f=r(p),d=n(2),h=r(d),y=n(290),v=r(y),m=4,g=3,b=function(e){function t(e){a(this,t);var n=i(this,Object.getPrototypeOf(t).call(this,e));return n.prefixCls=e.rootPrefixCls+"-year-panel",n.state={value:e.value||e.defaultValue},n.nextDecade=l.bind(n,10),n.previousDecade=l.bind(n,-10),["showDecadePanel","onDecadePanelSelect"].forEach(function(e){n[e]=n[e].bind(n)}),n}return s(t,e),c(t,[{key:"onDecadePanelSelect",value:function(e){this.setState({value:e,showDecadePanel:0})}},{key:"getYears",value:function(){for(var e=this.state.value,t=e.getYear(),n=10*parseInt(t/10,10),r=n-1,o=n+9,a=[],i=0,s=0;m>s;s++){a[s]=[];for(var l=0;g>l;l++){var u=r+i,c=void 0;c=n>u?"":u>o?"":String(u),a[s][l]={content:c,year:u,title:c},i++}}return a}},{key:"showDecadePanel",value:function(){this.setState({showDecadePanel:1})}},{key:"render",value:function(){var e=this,t=this.props,n=this.state.value,r=t.locale,a=this.getYears(),i=n.getYear(),s=10*parseInt(i/10,10),l=s+9,c=this.prefixCls,p=a.map(function(t,n){var r=t.map(function(t){var n,r=(n={},o(n,c+"-cell",1),o(n,c+"-selected-cell",t.year===i),o(n,c+"-last-decade-cell",t.year<s),o(n,c+"-next-decade-cell",t.year>l),n),a=void 0;return a=t.year<s?e.previousDecade:t.year>l?e.nextDecade:u.bind(e,t.year),f["default"].createElement("td",{role:"gridcell",title:t.title,key:t.content,onClick:a,className:(0,h["default"])(r)},f["default"].createElement("a",{className:c+"-year"},t.content))});return f["default"].createElement("tr",{key:n,role:"row"},r)}),d=void 0;return this.state.showDecadePanel&&(d=f["default"].createElement(v["default"],{locale:r,value:n,rootPrefixCls:t.rootPrefixCls,onSelect:this.onDecadePanelSelect})),f["default"].createElement("div",{className:this.prefixCls},f["default"].createElement("div",null,f["default"].createElement("div",{className:c+"-header"},f["default"].createElement("a",{className:c+"-prev-decade-btn",role:"button",onClick:this.previousDecade,title:r.previousDecade},"\xab"),f["default"].createElement("a",{className:c+"-decade-select",role:"button",onClick:this.showDecadePanel,title:r.decadeSelect},f["default"].createElement("span",{className:c+"-decade-select-content"},s,"-",l),f["default"].createElement("span",{className:c+"-decade-select-arrow"},"x")),f["default"].createElement("a",{className:c+"-next-decade-btn",role:"button",onClick:this.nextDecade,title:r.nextDecade},"\xbb")),f["default"].createElement("div",{className:c+"-body"},f["default"].createElement("table",{className:c+"-table",cellSpacing:"0",role:"grid"},f["default"].createElement("tbody",{className:c+"-tbody"},p)))),d)}}]),t}(f["default"].Component);t["default"]=b,b.propTypes={rootPrefixCls:p.PropTypes.string,value:p.PropTypes.object,defaultValue:p.PropTypes.object},b.defaultProps={onSelect:function(){}},e.exports=t["default"]},function(e,t,n){"use strict";e.exports=n(298)},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 a(){function e(e){var t=l["default"].createClass({displayName:"Form",mixins:n,getInitialState:function(){var e=void 0;return r&&(e=r(this.props)),this.fields=e||{},this.instances={},this.fieldsMeta={},this.cachedBind={},{submitting:!1}},componentWillReceiveProps:function(e){r&&(this.fields=r(e))},onChange:function(e,t){for(var n=this.getFieldMeta(e),r=n.validate,a=arguments.length,s=Array(a>2?a-2:0),l=2;a>l;l++)s[l-2]=arguments[l];n[t]&&n[t].apply(n,s);var c=n.getValueFromEvent?n.getValueFromEvent.apply(n,s):u.getValueFromEvent.apply(void 0,s),p=this.getField(e,!0);this.setFields(o({},e,i({},p,{value:c,dirty:(0,u.hasRules)(r)})))},onChangeValidate:function(e,t){for(var n=this.getFieldMeta(e),r=arguments.length,o=Array(r>2?r-2:0),a=2;r>a;a++)o[a-2]=arguments[a];n[t]&&n[t].apply(n,o);var i=n.getValueFromEvent?n.getValueFromEvent.apply(n,o):u.getValueFromEvent.apply(void 0,o),s=this.getField(e,!0);s.value=i,s.dirty=!0,this.validateFieldsInternal([s],{ action:t,options:{firstFields:!!n.validateFirst}})},getCacheBind:function(e,t,n){var r=this.cachedBind[e]=this.cachedBind[e]||{};return r[t]||(r[t]=n.bind(this,e,t)),r[t]},getFieldMeta:function(e){return this.fieldsMeta[e]},getField:function(e,t){var n=this.fields[e];return n&&(n.name=e),t?n?i({},n):{name:e}:n},getFieldProps:function(e){function t(e){return-1===e.trigger.indexOf(l)||!e.rules||!e.rules.length}var n=this,r=arguments.length<=1||void 0===arguments[1]?{}:arguments[1];if(!e)throw new Error("must call getFieldProps with valid name string!");var o=r.rules,a=r.trigger,l=void 0===a?d:a,u=r.valuePropName,p=void 0===u?"value":u,h=r.getValueProps,y=r.validateTrigger,v=void 0===y?f:y,m=r.validate,g=void 0===m?[]:m,b=this.fieldsMeta[e]||{};"initialValue"in r&&(b.initialValue=r.initialValue);var P={};s&&(P[s]=e);var O=g.map(function(e){var t=i({},e,{trigger:e.trigger||[]});return"string"==typeof t.trigger&&(t.trigger=[t.trigger]),t});o&&O.push({trigger:v?[].concat(v):[],rules:o}),O.filter(function(e){return!!e.rules&&e.rules.length}).map(function(e){return e.trigger}).reduce(function(e,t){return e.concat(t)},[]).forEach(function(t){P[t]=n.getCacheBind(e,t,n.onChangeValidate)}),l&&O.every(t)&&(P[l]=this.getCacheBind(e,l,this.onChange));var C=this.getField(e),T=b.initialValue;C&&"value"in C&&(T=C.value),h?P=i({},P,h(T)):P[p]=T,P.ref=this.getCacheBind(e,e+"__ref",this.saveRef);var w=i({},b,r,{validate:O});return this.fieldsMeta[e]=w,c&&(P[c]=w),P},getFieldMember:function(e,t){var n=this.getField(e);return n&&n[t]},getFieldError:function(e){return(0,u.getErrorStrs)(this.getFieldMember(e,"errors"))},getValidFieldsName:function(){var e=this.fieldsMeta;return e?Object.keys(e).filter(function(t){return!e[t].hidden}):[]},getFieldsValue:function(e){var t=this,n=e||this.getValidFieldsName(),r={};return n.forEach(function(e){r[e]=t.getFieldValue(e)}),r},getFieldValue:function(e){var t=this.fields;return this.getValueFromFields(e,t)},getFieldInstance:function(e){return this.instances[e]},getValueFromFields:function(e,t){var n=this.fieldsMeta,r=t[e];if(r&&"value"in r)return r.value;var o=n[e];return o&&o.initialValue},getRules:function(e,t){var n=e.validate.filter(function(e){return!t||e.trigger.indexOf(t)>=0}).map(function(e){return e.rules});return(0,u.flattenArray)(n)},setFields:function(e){var t=this,n=this.fields,r=i({},n,e),o=this.fieldsMeta,s={};Object.keys(o).forEach(function(e){s[e]=t.getValueFromFields(e,r)});var l=Object.keys(e);Object.keys(s).forEach(function(e){var a=s[e],u=o[e];if(u&&u.normalize){var c=u.normalize(a,t.getValueFromFields(e,n),s);c!==a&&(r[e]=i({},r[e],{value:c}),-1===l.indexOf(e)&&l.push(e))}}),this.fields=r,a&&!function(){var e={};l.forEach(function(t){e[t]=r[t]}),a(t.props,e)}(),this.forceUpdate()},setFieldsValue:function(e){var t={};for(var n in e)e.hasOwnProperty(n)&&(t[n]={name:n,value:e[n]});this.setFields(t)},setFieldsInitialValue:function(e){var t=this.fieldsMeta;for(var n in e)if(e.hasOwnProperty(n)){var r=t[n];t[n]=i({},r,{initialValue:e[n]})}},saveRef:function(e,t,n){if(!n)return delete this.fieldsMeta[e],delete this.fields[e],void delete this.instances[e];var r=this.getFieldMeta(e);if(r&&r.ref){if("string"==typeof r.ref)throw new Error("can not set ref string for "+e);r.ref(n)}this.instances[e]=n},validateFieldsInternal:function(e,t,n){var r=this,o=t.fieldNames,a=t.action,s=t.options,l=void 0===s?{}:s,c={},f={},d={},y={};e.forEach(function(e){var t=e.name;if(l.force!==!0&&e.dirty===!1)return void(e.errors&&(y[t]={errors:e.errors}));var n=r.getFieldMeta(t),o=i({},e);o.errors=void 0,o.validating=!0,o.dirty=!0,c[t]=r.getRules(n,a),f[t]=o.value,d[t]=o}),this.setFields(d);var v=this.fields;if(Object.keys(f).forEach(function(e){f[e]=v[e].value}),n&&(0,u.isEmptyObject)(d))return void n((0,u.isEmptyObject)(y)?null:y,this.getFieldsValue(o));var m=new p["default"](c);h&&m.messages(h),m.validate(f,l,function(e){var t=i({},y);e&&e.length&&e.forEach(function(e){var n=e.field;t[n]||(t[n]={errors:[]});var r=t[n].errors;r.push(e)});var a=[],s={};Object.keys(c).forEach(function(e){var n=t[e],o=r.getField(e,!0);o.value!==f[e]?a.push({name:e}):(o.errors=n&&n.errors,o.value=f[e],o.validating=!1,o.dirty=!1,s[e]=o)}),r.setFields(s),n&&(a.length&&a.forEach(function(e){var n=e.name,r=[{message:n+" need to revalidate",field:n}];t[n]={expired:!0,errors:r}}),n((0,u.isEmptyObject)(t)?null:t,r.getFieldsValue(o)))})},validateFields:function(e,t,n){var r=this,o=(0,u.getParams)(e,t,n),a=o.names,i=o.callback,s=o.options,l=a||this.getValidFieldsName(),c=l.map(function(e){var t=r.getFieldMeta(e);if(!(0,u.hasRules)(t.validate))return null;var n=r.getField(e,!0);return n.value=r.getFieldValue(e),n}).filter(function(e){return!!e});return c.length?("firstFields"in s||(s.firstFields=l.filter(function(e){var t=r.getFieldMeta(e);return!!t.validateFirst})),void this.validateFieldsInternal(c,{fieldNames:l,options:s},i)):void(i&&i(null,this.getFieldsValue(l)))},isFieldValidating:function(e){return this.getFieldMember(e,"validating")},isFieldsValidating:function(e){var t=e||this.getValidFieldsName();return t.some(this.isFieldValidating)},isSubmitting:function(){return this.state.submitting},submit:function(e){var t=this,n=function(){t.setState({submitting:!1})};this.setState({submitting:!0}),e(n)},resetFields:function(e){var t={},n=this.fields,r=!1,o=e||Object.keys(n);o.forEach(function(e){var o=n[e];o&&"value"in o&&(r=!0,t[e]={})}),r&&this.setFields(t)},render:function(){var t=o({},g,this.getForm());b&&(t.ref="wrappedComponent");var n=v.call(this,i({},t,this.props));return l["default"].createElement(e,n)}});return(0,u.argumentContainer)(t,e)}var t=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],n=arguments.length<=1||void 0===arguments[1]?[]:arguments[1],r=t.mapPropsToFields,a=t.onFieldsChange,s=t.fieldNameProp,c=t.fieldMetaProp,h=t.validateMessages,y=t.mapProps,v=void 0===y?u.mirror:y,m=t.formPropName,g=void 0===m?"form":m,b=t.withRef;return 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},s=n(1),l=r(s),u=n(97),c=n(125),p=r(c),f="onChange",d=f;t["default"]=a,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.displayName||e.name||"WrappedComponent"}function a(e,t){return e.displayName="Form("+o(t)+")",e.WrappedComponent=t,(0,h["default"])(e,t)}function i(e){if(!e||!e.target)return e;var t=e.target;return"checkbox"===t.type?t.checked:t.value}function s(e){return e?e.map(function(e){return e&&e.message?e.message:e}):e}function l(e){return 0===Object.keys(e).length}function u(e){return Array.prototype.concat.apply([],e)}function c(e){return e}function p(e){return e?e.some(function(e){return!!e.rules&&e.rules.length}):!1}function f(e,t,n){var r=e,o=n,a=t;return void 0===n&&("function"==typeof r?(o=r,a={},r=void 0):Array.isArray(e)?"function"==typeof a?(o=a,a={}):a=a||{}:(o=a,a=r||{},r=void 0)),{names:r,callback:o,options:a}}Object.defineProperty(t,"__esModule",{value:!0}),t.argumentContainer=a,t.getValueFromEvent=i,t.getErrorStrs=s,t.isEmptyObject=l,t.flattenArray=u,t.mirror=c,t.hasRules=p,t.getParams=f;var d=n(265),h=r(d)},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 a(e){return e.length?e.every(function(e){return!!e.props.disabled}):!0}function i(e,t){var n=t,r=e.children,o=e.eventKey;if(n){var a=void 0;if((0,P.loopMenuItem)(r,function(e,t){e.props.disabled||n!==(0,P.getKeyFromChildrenIndex)(e,o,t)||(a=!0)}),a)return n}return n=null,e.defaultActiveFirst?((0,P.loopMenuItem)(r,function(e,t){n||e.props.disabled||(n=(0,P.getKeyFromChildrenIndex)(e,o,t))}),n):n}function s(e,t,n){n&&(void 0!==t?(this.instanceArray[e]=this.instanceArray[e]||[],this.instanceArray[e][t]=n):this.instanceArray[e]=n)}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=n(1),c=r(u),p=n(4),f=r(p),d=n(6),h=n(2),y=r(h),v=n(37),m=r(v),g=n(11),b=r(g),P=n(22),O=n(315),C=r(O),T={propTypes:{focusable:u.PropTypes.bool,multiple:u.PropTypes.bool,style:u.PropTypes.object,defaultActiveFirst:u.PropTypes.bool,visible:u.PropTypes.bool,activeKey:u.PropTypes.string,selectedKeys:u.PropTypes.arrayOf(u.PropTypes.string),defaultSelectedKeys:u.PropTypes.arrayOf(u.PropTypes.string),defaultOpenKeys:u.PropTypes.arrayOf(u.PropTypes.string),openKeys:u.PropTypes.arrayOf(u.PropTypes.string),children:u.PropTypes.any},getDefaultProps:function(){return{prefixCls:"rc-menu",className:"",mode:"vertical",level:1,inlineIndent:24,visible:!0,focusable:!0,style:{}}},getInitialState:function(){var e=this.props;return{activeKey:i(e,e.activeKey)}},componentWillReceiveProps:function(e){var t=void 0;if("activeKey"in e)t={activeKey:i(e,e.activeKey)};else{var n=this.state.activeKey,r=i(e,n);r!==n&&(t={activeKey:r})}t&&this.setState(t)},shouldComponentUpdate:function(e){return this.props.visible||e.visible},componentWillMount:function(){this.instanceArray=[]},onKeyDown:function(e){var t=this,n=e.keyCode,r=void 0;if(this.getFlatInstanceArray().forEach(function(t){t&&t.props.active&&(r=t.onKeyDown(e))}),r)return 1;var o=null;return n!==d.KeyCode.UP&&n!==d.KeyCode.DOWN||(o=this.step(n===d.KeyCode.UP?-1:1)),o?(e.preventDefault(),this.setState({activeKey:o.props.eventKey},function(){(0,m["default"])(f["default"].findDOMNode(o),f["default"].findDOMNode(t),{onlyScrollIfNeeded:!0})}),1):void 0===o?(e.preventDefault(),this.setState({activeKey:null}),1):void 0},onCommonItemHover:function(e){var t=this.props.mode,n=e.key,r=e.hover,o=e.trigger,a=this.state.activeKey;if(o&&!r&&!this.props.closeSubMenuOnMouseLeave&&e.item.isSubMenu&&"inline"!==t||this.setState({activeKey:r?n:null}),r&&"inline"!==t){var i=this.getFlatInstanceArray().filter(function(e){return e&&e.props.eventKey===a})[0];i&&i.isSubMenu&&i.props.eventKey!==n&&this.onOpenChange({item:i,key:i.props.eventKey,open:!1})}},getFlatInstanceArray:function(){var e=this.instanceArray,t=e.some(function(e){return Array.isArray(e)});return t&&(e=[],this.instanceArray.forEach(function(t){Array.isArray(t)?e.push.apply(e,t):e.push(t)}),this.instanceArray=e),e},renderCommonMenuItem:function(e,t,n,r){var o=this.state,a=this.props,i=(0,P.getKeyFromChildrenIndex)(e,a.eventKey,t),l=e.props,u=i===o.activeKey,p=(0,b["default"])({mode:a.mode,level:a.level,inlineIndent:a.inlineIndent,renderMenuItem:this.renderMenuItem,rootPrefixCls:a.prefixCls,index:t,parentMenu:this,ref:l.disabled?void 0:(0,d.createChainedFunction)(e.ref,s.bind(this,t,n)),eventKey:i,closeSubMenuOnMouseLeave:a.closeSubMenuOnMouseLeave,onItemHover:this.onItemHover,active:!l.disabled&&u,multiple:a.multiple,onClick:this.onClick,openTransitionName:this.getOpenTransitionName(),openAnimation:a.openAnimation,onOpenChange:this.onOpenChange,onDeselect:this.onDeselect,onDestroy:this.onDestroy,onSelect:this.onSelect},r);return"inline"===a.mode&&(p.closeSubMenuOnMouseLeave=p.openSubMenuOnMouseEnter=!1),c["default"].cloneElement(e,p)},renderRoot:function(e){var t;this.instanceArray=[];var n=(t={},o(t,e.prefixCls,1),o(t,e.prefixCls+"-"+e.mode,1),o(t,e.className,!!e.className),t),r={className:(0,y["default"])(n),role:"menu","aria-activedescendant":""};return e.id&&(r.id=e.id),e.focusable&&(r.tabIndex="0",r.onKeyDown=this.onKeyDown),c["default"].createElement(C["default"],l({style:e.style,tag:"ul",hiddenClassName:e.prefixCls+"-hidden",visible:e.visible},r),c["default"].Children.map(e.children,this.renderMenuItem))},step:function(e){var t=this.getFlatInstanceArray(),n=this.state.activeKey,r=t.length;if(!r)return null;0>e&&(t=t.concat().reverse());var o=-1;if(t.every(function(e,t){return e&&e.props.eventKey===n?(o=t,!1):!0}),this.props.defaultActiveFirst||-1===o||!a(t.slice(o,r-1)))for(var i=(o+1)%r,s=i;;){var l=t[s];if(l&&!l.props.disabled)return l;if(s=(s+1+r)%r,s===i)return null}}};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(324),a=r(o);t["default"]=a["default"],e.exports=t["default"]},function(e,t){"use strict";e.exports={ZERO:48,NINE:57,NUMPAD_ZERO:96,NUMPAD_NINE:105,BACKSPACE:8,DELETE:46,ENTER:13,ARROW_UP:38,ARROW_DOWN:40}},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t["default"]={items_per_page:"\u6761/\u9875",jump_to:"\u8df3\u81f3",page:"\u9875",first_page:"\u7b2c\u4e00\u9875",last_page:"\u6700\u540e\u4e00\u9875",prev_page:"\u4e0a\u4e00\u9875",next_page:"\u4e0b\u4e00\u9875",prev_5:"\u5411\u524d 5 \u9875",next_5:"\u5411\u540e 5 \u9875"},e.exports=t["default"]},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],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(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 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):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0});var l=n(1),u=r(l),c=function(e){function t(){return a(this,t),i(this,e.apply(this,arguments))}return s(t,e),t}(u["default"].Component);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,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 a=n(1),i=r(a),s=n(2),l=r(s),u=i["default"].createClass({displayName:"TabPane",propTypes:{active:a.PropTypes.bool},render:function(){var e,t=this.props;if(this._isActived=this._isActived||t.active,!this._isActived)return null;var n=t.rootPrefixCls+"-tabpane",r=(0,l["default"])((e={},o(e,n+"-hidden",!t.active),o(e,n,1),e));return i["default"].createElement("div",{role:"tabpanel","aria-hidden":t.active?"false":"true",className:r},t.children)}});t["default"]=u,e.exports=t["default"]},function(e,t){"use strict";function n(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 r(e){var t=void 0,r=void 0,o=void 0,a=e.ownerDocument,i=a.body,s=a&&a.documentElement;t=e.getBoundingClientRect(),r=t.left,o=t.top,r-=s.clientLeft||i.clientLeft||0,o-=s.clientTop||i.clientTop||0;var l=a.defaultView||a.parentWindow;return r+=n(l),o+=n(l,!0),{left:r,top:o}}function o(){if(!window.getComputedStyle)return!1;if(void 0!==a)return a;var e=document.createElement("p"),t=void 0,n={webkitTransform:"-webkit-transform",OTransform:"-o-transform",msTransform:"-ms-transform",MozTransform:"-moz-transform",transform:"transform"};document.body.insertBefore(e,null);for(var r in n)void 0!==e.style[r]&&(e.style[r]="translate3d(1px,1px,1px)",t=window.getComputedStyle(e).getPropertyValue(n[r]),void 0!==t&&t.length>0&&"none"!==t&&(a=r));return document.body.removeChild(e),a}Object.defineProperty(t,"__esModule",{value:!0}),t.getScroll=n,t.offset=r,t.getTransformPropertyName=o;var a=void 0},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){}function a(e,t){this[e]=t}Object.defineProperty(t,"__esModule",{value:!0});var i=n(1),s=r(i),l=n(14),u=r(l),c=n(372),p=r(c),f=n(375),d=r(f),h=n(106),y=r(h),v=n(374),m=s["default"].createClass({displayName:"Picker",propTypes:{prefixCls:i.PropTypes.string,locale:i.PropTypes.object,value:i.PropTypes.object,disabled:i.PropTypes.bool,allowEmpty:i.PropTypes.bool,defaultValue:i.PropTypes.object,open:i.PropTypes.bool,defaultOpen:i.PropTypes.bool,align:i.PropTypes.object,placement:i.PropTypes.any,transitionName:i.PropTypes.string,getPopupContainer:i.PropTypes.func,placeholder:i.PropTypes.string,formatter:i.PropTypes.any,showHour:i.PropTypes.bool,style:i.PropTypes.object,className:i.PropTypes.string,showSecond:i.PropTypes.bool,disabledHours:i.PropTypes.func,disabledMinutes:i.PropTypes.func,disabledSeconds:i.PropTypes.func,hideDisabledOptions:i.PropTypes.bool,onChange:i.PropTypes.func,onOpen:i.PropTypes.func,onClose:i.PropTypes.func},mixins:[y["default"]],getDefaultProps:function(){return{defaultOpen:!1,style:{},className:"",align:{},allowEmpty:!0,showHour:!0,showSecond:!0,disabledHours:o,disabledMinutes:o,disabledSeconds:o,hideDisabledOptions:!1,placement:"bottomLeft",onChange:o,onOpen:o,onClose:o}},getInitialState:function(){this.savePanelRef=a.bind(this,"panelInstance");var e=this.props,t=e.defaultOpen,n=e.defaultValue,r=e.open,o=void 0===r?t:r,i=e.value,s=void 0===i?n:i;return{open:o,value:s}},componentWillReceiveProps:function(e){var t=e.value,n=e.open;"value"in e&&this.setState({value:t}),void 0!==n&&this.setState({open:n})},onPanelChange:function(e){this.setValue(e)},onPanelClear:function(){this.setValue(null),this.setOpen(!1)},onVisibleChange:function(e){this.setOpen(e)},onEsc:function(){this.setOpen(!1),this.refs.picker.focus()},onKeyDown:function(e){40===e.keyCode&&this.setOpen(!0)},setValue:function(e){"value"in this.props||this.setState({value:e}),this.props.onChange(e)},getFormatter:function(){var e=this.props.formatter,t=this.props.locale;return e?e===this.lastFormatter?this.normalFormatter:(this.normalFormatter=(0,v.getFormatter)(e,t),this.lastFormatter=e,this.normalFormatter):this.props.showSecond?this.props.showHour?(this.normalFormatter||(this.normalFormatter=(0,v.getFormatter)("HH:mm:ss",t)),this.normalFormatter):(this.notShowHourFormatter||(this.notShowHourFormatter=(0,v.getFormatter)("mm:ss",t)),this.notShowHourFormatter):(this.notShowSecondFormatter||(this.notShowSecondFormatter=(0,v.getFormatter)("HH:mm",t)),this.notShowSecondFormatter)},getPanelElement:function(){var e=this.props,t=e.prefixCls,n=e.defaultValue,r=e.locale,o=e.placeholder,a=e.disabledHours,i=e.disabledMinutes,l=e.disabledSeconds,u=e.hideDisabledOptions,c=e.allowEmpty,f=e.showHour,d=e.showSecond;return s["default"].createElement(p["default"],{prefixCls:t+"-panel",ref:this.savePanelRef,value:this.state.value,onChange:this.onPanelChange,gregorianCalendarLocale:r.calendar,onClear:this.onPanelClear,defaultValue:n,showHour:f,onEsc:this.onEsc,showSecond:d,locale:r,allowEmpty:c,formatter:this.getFormatter(),placeholder:o,disabledHours:a,disabledMinutes:i,disabledSeconds:l,hideDisabledOptions:u})},setOpen:function(e,t){var n=this.props,r=n.onOpen,o=n.onClose;if(this.state.open!==e){this.setState({open:e},t);var a={open:e};e?r(a):o(a)}},render:function(){var e=this.props,t=e.prefixCls,n=e.placeholder,r=e.placement,o=e.align,a=e.disabled,i=e.transitionName,l=e.style,c=e.className,p=e.showHour,f=e.showSecond,h=e.getPopupContainer,y=this.state,v=y.open,m=y.value,g=void 0;return p&&f||(g=t+"-panel-narrow"),s["default"].createElement(u["default"],{prefixCls:t+"-panel",popupClassName:g,popup:this.getPanelElement(),popupAlign:o,builtinPlacements:d["default"],popupPlacement:r,action:a?[]:["click"],destroyPopupOnHide:!0,getPopupContainer:h,popupTransitionName:i,popupVisible:v,onPopupVisibleChange:this.onVisibleChange},s["default"].createElement("span",{className:t+" "+c,style:l},s["default"].createElement("input",{className:t+"-input",ref:"picker",type:"text",placeholder:n,readOnly:!0,onKeyDown:this.onKeyDown,disabled:a,value:m&&this.getFormatter().format(m)||""}),s["default"].createElement("span",{className:t+"-icon"})))}});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),a=n(368),i=r(a);t["default"]={propTypes:{prefixCls:o.PropTypes.string,locale:o.PropTypes.object},getDefaultProps:function(){return{prefixCls:"rc-time-picker",locale:i["default"]}}},e.exports=t["default"]},function(e,t,n){"use strict";e.exports=n(377)},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 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 i=function(e,t,n){for(var r=!0;r;){var o=e,a=t,i=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,a);if(void 0!==s){if("value"in s)return s.value;var l=s.get;if(void 0===l)return;return l.call(i)}var u=Object.getPrototypeOf(o);if(null===u)return;e=u,t=a,n=i,r=!0,s=u=void 0}},s=n(1),l=r(s),u=function(e){function t(){o(this,t),i(Object.getPrototypeOf(t.prototype),"constructor",this).apply(this,arguments)}return a(t,e),t}(l["default"].Component);t["default"]=u,u.propTypes={value:l["default"].PropTypes.string},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 a(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.props;if("value"in t)return t.value;if(e.key)return e.key;throw new Error("no key or value for "+e)}function s(e,t){return"value"===t?i(e):e.props[t]}function l(e){return e.combobox}function u(e){return e.multiple||e.tags||e.treeCheckable}function c(e){return u(e)||l(e)}function p(e){return!c(e)}function f(e){var t=e;return void 0===e?t=[]:Array.isArray(e)||(t=[e]),t}function d(e){e.preventDefault()}function h(e){var t=e;return"label"===t&&(t="title"),t}function y(e,t){return e.every(function(e,n){return e===t[n]})}function v(e){var t=1;return Array.isArray(e)&&(t=e.length),t}function m(e,t,n){return 1===t?(n.first=!0,n.last=!0):(n.first=0===e,n.last=e===t-1),n}function g(e,t,n){var r=function o(e,n,r){var a=v(e);D["default"].Children.forEach(e,function(e,i){var s=n+"-"+i;e&&e.props.children&&e.type&&o(e.props.children,s,{node:e,pos:s}),e&&t(e,i,s,e.key||s,m(i,a,{}),r)})};r(e,0,n)}function b(e){if(!e.length)return e;var t=[],n={};e.forEach(function(e){var t=e.pos.split("-").length;n[t]||(n[t]=[]),n[t].push(e)});var r=Object.keys(n).sort(function(e,t){return t-e});return r.reduce(function(e,r){return r&&r!==e&&n[e].forEach(function(e){var o=!1;n[r].forEach(function(t){y(t.pos.split("-"),e.pos.split("-"))&&(o=!0,t.children||(t.children=[]),t.children.push(e))}),o||t.push(e)}),r}),n[r[r.length-1]].concat(t)}function P(e){var t={};e.forEach(function(e){var n=e.split("-").length;t[n]||(t[n]=[]),t[n].push(e)});for(var n=Object.keys(t).sort(),r=function(e){n[e+1]&&t[n[e]].forEach(function(r){for(var o=function(e){t[n[e]].forEach(function(o,a){y(r.split("-"),o.split("-"))&&(t[n[e]][a]=null)}),t[n[e]]=t[n[e]].filter(function(e){return e})},a=e+1;a<n.length;a++)o(a)})},o=0;o<n.length;o++)r(o);var a=[];return n.forEach(function(e){a=a.concat(t[e])}),a}function O(e){var t=e.match(/(.+)(-[^-]+)$/),n="";return t&&3===t.length&&(n=t[1]),n}function C(e){return e.split("-")}function T(e,t,n){var r=Object.keys(e);r.forEach(function(o,a){var i=C(o),s=!1;t.forEach(function(t){var l=C(t);i.length>l.length&&y(l,i)&&(e[o].halfChecked=!1,e[o].checked=n,r[a]=null),i[0]===l[0]&&i[1]===l[1]&&(s=!0)}),s||(r[a]=null)}),r=r.filter(function(e){return e});for(var o=function(n){var o=function i(o){var a=C(o).length;if(!(2>=a)){var s=0,l=0,u=O(o);r.forEach(function(r){var o=C(r);if(o.length===a&&y(C(u),o))if(s++,e[r].checked){l++;var i=t.indexOf(r);i>-1&&(t.splice(i,1),n>=i&&n--)}else e[r].halfChecked&&(l+=.5)});var c=e[u];0===l?(c.checked=!1,c.halfChecked=!1):l===s?(c.checked=!0,c.halfChecked=!1):(c.halfChecked=!0,c.checked=!1),i(u)}};o(t[n],n),a=n},a=0;a<t.length;a++)o(a)}function w(e,t){var n=[],r=[],o=[];return Object.keys(e).forEach(function(t){var a=e[t];a.checked?(r.push(a.key),o.push(N({},a,{pos:t}))):a.halfChecked&&n.push(a.key)}),{halfCheckedKeys:n,checkedKeys:r,checkedNodes:o,treeNodesStates:e,checkedPositions:t}}function x(e,t){var n=[],r={};return g(e,function(e,o,a,s,l){r[a]={node:e,key:s,checked:!1,halfChecked:!1,siblingPosition:l},-1!==t.indexOf(i(e))&&(r[a].checked=!0,n.push(a))}),T(r,P(n.sort()),!0),w(r,n)}function E(e){var t=arguments.length<=1||void 0===arguments[1]?function(e){return e}:arguments[1];return Array.from(e).map(function(e){var n=t(e);return n&&n.props&&n.props.children?D["default"].cloneElement(n,{},E(n.props.children,t)):n})}function S(e){var t=arguments.length<=1||void 0===arguments[1]?0:arguments[1];return D["default"].Children.map(e,function(e,n){var r=t+"-"+n,o={title:e.props.title,label:e.props.label||e.props.title,value:e.props.value,key:e.key,_pos:r};return e.props.children&&(o.children=S(e.props.children,r)),o})}function k(e,t){e.forEach(function(e){t(e),e.children&&k(e.children,t)})}function j(e,t){function n(e){e.forEach(function(e){if(!e.__checked){var t=a.indexOf(e.value),r=e.children;t>-1?(e.__checked=!0,s.push({node:e,pos:e._pos}),a.splice(t,1),r&&k(r,function(e){e.__checked=!0,s.push({node:e,pos:e._pos})})):r&&n(r)}})}function r(e){var t=arguments.length<=1||void 0===arguments[1]?{root:!0}:arguments[1],n=0;e.forEach(function(e){var t=e.children;if(!t||e.__checked||e.__halfChecked)e.__checked?n++:e.__halfChecked&&(n+=.5);else{var o=r(t,e);o.__checked?n++:o.__halfChecked&&(n+=.5)}});var o=e.length;return n===o?(t.__checked=!0,s.push({node:t,pos:t._pos})):o>n&&n>0&&(t.__halfChecked=!0),t.root?e:t}var a=[].concat(o(e));if(!a.length)return a;var i=S(t),s=[];return n(i),r(i),s.forEach(function(e,t){delete s[t].node.__checked,delete s[t].node._pos,s[t].node.props={title:s[t].node.title,label:s[t].node.label||s[t].node.title,value:s[t].node.value},s[t].node.children&&(s[t].node.props.children=s[t].node.children),delete s[t].node.title,delete s[t].node.label,delete s[t].node.value,delete s[t].node.children}),s}function _(e,t){function n(e){for(var r=arguments.length<=1||void 0===arguments[1]?a({},t.id,t.rootPId):arguments[1],o=[],i=0;i<e.length;i++)e[i][t.pId]===r[t.id]&&(e[i].key=e[i][t.id],o.push(e[i]),e.splice(i--,1));return o.length&&(r.children=o,o.forEach(function(t){return n(e,t)})),r[t.id]===t.rootPId?o:void 0}return n(e)}Object.defineProperty(t,"__esModule",{value:!0});var N=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.getValuePropValue=i,t.getPropValue=s,t.isCombobox=l,t.isMultipleOrTags=u,t.isMultipleOrTagsOrCombobox=c,t.isSingleMode=p,t.toArray=f,t.preventDefaultEvent=d,t.labelCompatible=h,t.isInclude=y,t.loopAllChildren=g,t.flatToHierarchy=b,t.filterParentPosition=P,t.handleCheckState=T,t.getTreeNodesStates=x,t.recursiveCloneChildren=E,t.filterAllCheckedData=j,t.processSimpleTreeData=_;var M=n(1),D=r(M),A={userSelect:"none",WebkitUserSelect:"none"};t.UNSELECTABLE_STYLE=A;var L={unselectable:"unselectable"};t.UNSELECTABLE_ATTRIBUTE=L},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(382),a=r(o),i=n(383),s=r(i);a["default"].TreeNode=s["default"],t["default"]=a["default"],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=e.userAgent,r=n.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i)||[];return/trident/i.test(r[1])?(t=/\brv[ :]+(\d+)/g.exec(n)||[],"IE "+(t[1]||"")):"Chrome"===r[1]&&(t=n.match(/\b(OPR|Edge)\/(\d+)/))?t.slice(1).join(" ").replace("OPR","Opera"):(r=r[2]?[r[1],r[2]]:[e.appName,e.appVersion,"-?"],t=n.match(/version\/(\d+)/i),t&&r.splice(1,1,t[1]),r.join(" "))}function a(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}}function i(e){var t=1;return Array.isArray(e)&&(t=e.length),t}function s(e,t,n){return 1===t?(n.first=!0,n.last=!0):(n.first=0===e,n.last=e===t-1),n}function l(e,t,n){var r=function o(e,n,r){var a=i(e);m["default"].Children.forEach(e,function(e,i){var l=n+"-"+i;e.props.children&&e.type&&e.type.isTreeNode&&o(e.props.children,l,{node:e,pos:l}),t(e,i,l,e.key||l,s(i,a,{}),r)})};r(e,0,n)}function u(e,t){return e.every(function(e,n){return e===t[n]})}function c(e){var t={};e.forEach(function(e){var n=e.split("-").length;t[n]||(t[n]=[]),t[n].push(e)});for(var n=Object.keys(t).sort(),r=function(e){n[e+1]&&t[n[e]].forEach(function(r){for(var o=function(e){t[n[e]].forEach(function(o,a){u(r.split("-"),o.split("-"))&&(t[n[e]][a]=null)}),t[n[e]]=t[n[e]].filter(function(e){return e})},a=e+1;a<n.length;a++)o(a)})},o=0;o<n.length;o++)r(o);var a=[];return n.forEach(function(e){a=a.concat(t[e])}),a}function p(e){var t=e.match(/(.+)(-[^-]+)$/),n="";return t&&3===t.length&&(n=t[1]),n}function f(e){return e.split("-")}function d(e,t,n){var r=Object.keys(e);r.forEach(function(o,a){var i=f(o),s=!1;t.forEach(function(t){var l=f(t);i.length>l.length&&u(l,i)&&(e[o].halfChecked=!1,e[o].checked=n,r[a]=null),i[0]===l[0]&&i[1]===l[1]&&(s=!0)}),s||(r[a]=null)}),r=r.filter(function(e){return e});for(var o=function(n){var o=function i(o){var a=f(o).length;if(!(2>=a)){var s=0,l=0,c=p(o);r.forEach(function(r){var o=f(r);if(o.length===a&&u(f(c),o))if(s++,e[r].checked){l++;var i=t.indexOf(r);i>-1&&(t.splice(i,1),n>=i&&n--)}else e[r].halfChecked&&(l+=.5)});var d=e[c];0===l?(d.checked=!1,d.halfChecked=!1):l===s?(d.checked=!0,d.halfChecked=!1):(d.halfChecked=!0,d.checked=!1),i(c)}};o(t[n],n),a=n},a=0;a<t.length;a++)o(a)}function h(e){var t=[],n=[],r=[],o=[];return Object.keys(e).forEach(function(a){var i=e[a];i.checked?(n.push(i.key),r.push(i.node),o.push({node:i.node,pos:a})):i.halfChecked&&t.push(i.key)}),{halfCheckedKeys:t,checkedKeys:n,checkedNodes:r,checkedNodesPositions:o,treeNodesStates:e}}function y(e,t){return t?{checked:e,halfChecked:t}:e}Object.defineProperty(t,"__esModule",{value:!0}),t.browser=o,t.getOffset=a,t.loopAllChildren=l,t.isInclude=u,t.filterParentPosition=c,t.handleCheckState=d,t.getCheck=h,t.getStrictlyValue=y;var v=n(1),m=r(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=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),i=r(a),s=i["default"].createClass({displayName:"LazyRenderBox",propTypes:{children:a.PropTypes.any,className:a.PropTypes.string,visible:a.PropTypes.bool,hiddenClassName:a.PropTypes.string},shouldComponentUpdate:function(e){return e.hiddenClassName||e.visible},render:function(){if(this.props.hiddenClassName){var e=this.props.className;return this.props.visible||(e+=" "+this.props.hiddenClassName),i["default"].createElement("div",o({},this.props,{className:e}))}return i["default"].Children.count(this.props.children)>1?i["default"].createElement("div",this.props):i["default"].Children.only(this.props.children)}});t["default"]=s,e.exports=t["default"]},function(e,t){"use strict";function n(){return"rc-upload-"+r+"-"+ ++o}Object.defineProperty(t,"__esModule",{ value:!0}),t["default"]=n;var r=+new Date,o=0;e.exports=t["default"]},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(-1!==window.navigation.userAgent.indexOf("WebKit")&&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";var n={className:"",adaptiveHeight:!1,arrows:!0,autoplay:!1,autoplaySpeed:3e3,centerMode:!1,centerPadding:"50px",cssEase:"ease",dots:!1,dotsClass:"slick-dots",draggable:!0,easing:"linear",edgeFriction:.35,fade:!1,focusOnSelect:!1,infinite:!0,initialSlide:0,lazyLoad:!1,pauseOnHover:!1,responsive:null,rtl:!1,slide:"div",slidesToShow:1,slidesToScroll:1,speed:500,swipe:!0,swipeToSlide:!1,touchMove:!0,touchThreshold:5,useCSS:!0,variableWidth:!1,vertical:!1,waitForAnimate:!0,afterChange:null,beforeChange:null,edgeEvent:null,init:null,swipeEvent:null,nextArrow:null,prevArrow:null};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(1),a=r(o),i=n(4),s=r(i),l=a["default"].version>="0.14.0"?s["default"]:a["default"];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(1),a=r(o),i=n(116),s=r(i),l=n(413),u=r(l),c=n(118),p=n(29),f=r(p),d={initialize:function(e){var t=a["default"].Children.count(e.children),n=this.getWidth(s["default"].findDOMNode(this.refs.list)),r=this.getWidth(s["default"].findDOMNode(this.refs.track)),o=this.getWidth(s["default"].findDOMNode(this))/e.slidesToShow,i=e.rtl?t-1-e.initialSlide:e.initialSlide;this.setState({slideCount:t,slideWidth:o,listWidth:n,trackWidth:r,currentSlide:i},function(){var t=(0,c.getTrackLeft)((0,f["default"])({slideIndex:this.state.currentSlide,trackRef:this.refs.track},e,this.state)),n=(0,c.getTrackCSS)((0,f["default"])({left:t},e,this.state));this.setState({trackStyle:n}),this.autoPlay()})},update:function(e){var t=a["default"].Children.count(e.children),n=this.getWidth(s["default"].findDOMNode(this.refs.list)),r=this.getWidth(s["default"].findDOMNode(this.refs.track)),o=this.getWidth(s["default"].findDOMNode(this))/e.slidesToShow;this.setState({slideCount:t,slideWidth:o,listWidth:n,trackWidth:r},function(){var t=(0,c.getTrackLeft)((0,f["default"])({slideIndex:this.state.currentSlide,trackRef:this.refs.track},e,this.state)),n=(0,c.getTrackCSS)((0,f["default"])({left:t},e,this.state));this.setState({trackStyle:n})})},getWidth:function(e){return e.getBoundingClientRect().width||e.offsetWidth},adaptHeight:function(){if(this.props.adaptiveHeight){var e='[data-index="'+this.state.currentSlide+'"]';if(this.refs.list){var t=s["default"].findDOMNode(this.refs.list);t.style.height=t.querySelector(e).offsetHeight+"px"}}},slideHandler:function(e){var t,n,r,o,a,i=this;if(!this.props.waitForAnimate||!this.state.animating){if(this.props.fade)return n=this.state.currentSlide,t=0>e?e+this.state.slideCount:e>=this.state.slideCount?e-this.state.slideCount:e,this.props.lazyLoad&&this.state.lazyLoadedList.indexOf(t)<0&&this.setState({lazyLoadedList:this.state.lazyLoadedList.concat(t)}),a=function(){i.setState({animating:!1}),i.props.afterChange&&i.props.afterChange(n),u["default"].removeEndEventListener(s["default"].findDOMNode(i.refs.track).children[n],a)},this.setState({animating:!0,currentSlide:t},function(){u["default"].addEndEventListener(s["default"].findDOMNode(this.refs.track).children[n],a)}),this.props.beforeChange&&this.props.beforeChange(this.state.currentSlide,n),void this.autoPlay();if(t=e,n=0>t?this.props.infinite===!1?0:this.state.slideCount%this.props.slidesToScroll!==0?this.state.slideCount-this.state.slideCount%this.props.slidesToScroll:this.state.slideCount+t:t>=this.state.slideCount?this.props.infinite===!1?this.state.slideCount-this.props.slidesToShow:this.state.slideCount%this.props.slidesToScroll!==0?0:t-this.state.slideCount:t,r=(0,c.getTrackLeft)((0,f["default"])({slideIndex:t,trackRef:this.refs.track},this.props,this.state)),o=(0,c.getTrackLeft)((0,f["default"])({slideIndex:n,trackRef:this.refs.track},this.props,this.state)),this.props.infinite===!1&&(r=o),this.props.beforeChange&&this.props.beforeChange(this.state.currentSlide,n),this.props.lazyLoad){for(var l=!0,p=[],d=t;d<t+this.props.slidesToShow;d++)l=l&&this.state.lazyLoadedList.indexOf(d)>=0,l||p.push(d);l||this.setState({lazyLoadedList:this.state.lazyLoadedList.concat(p)})}if(this.props.useCSS===!1)this.setState({currentSlide:n,trackStyle:(0,c.getTrackCSS)((0,f["default"])({left:o},this.props,this.state))},function(){this.props.afterChange&&this.props.afterChange(n)});else{var h={animating:!1,currentSlide:n,trackStyle:(0,c.getTrackCSS)((0,f["default"])({left:o},this.props,this.state)),swipeLeft:null};a=function(){i.setState(h),i.props.afterChange&&i.props.afterChange(n),u["default"].removeEndEventListener(s["default"].findDOMNode(i.refs.track),a)},this.setState({animating:!0,currentSlide:n,trackStyle:(0,c.getTrackAnimateCSS)((0,f["default"])({left:r},this.props,this.state))},function(){u["default"].addEndEventListener(s["default"].findDOMNode(this.refs.track),a)})}this.autoPlay()}},swipeDirection:function(e){var t,n,r,o;return t=e.startX-e.curX,n=e.startY-e.curY,r=Math.atan2(n,t),o=Math.round(180*r/Math.PI),0>o&&(o=360-Math.abs(o)),45>=o&&o>=0||360>=o&&o>=315?this.props.rtl===!1?"left":"right":o>=135&&225>=o?this.props.rtl===!1?"right":"left":"vertical"},autoPlay:function(){var e=this;if(!this.state.autoPlayTimer){var t=function(){if(e.state.mounted){var t=e.props.rtl?e.state.currentSlide-e.props.slidesToScroll:e.state.currentSlide+e.props.slidesToScroll;e.slideHandler(t)}};this.props.autoplay&&this.setState({autoPlayTimer:window.setInterval(t,this.props.autoplaySpeed)})}},pause:function(){this.state.autoPlayTimer&&(window.clearInterval(this.state.autoPlayTimer),this.setState({autoPlayTimer:null}))}};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(116),a=r(o),i=function(e,t){return t.reduce(function(t,n){return t&&e.hasOwnProperty(n)},!0)?null:console.error("Keys Missing",e)},s=function(e){i(e,["left","variableWidth","slideCount","slidesToShow","slideWidth"]);var t;t=e.variableWidth?(e.slideCount+2*e.slidesToShow)*e.slideWidth:e.centerMode?(e.slideCount+2*(e.slidesToShow+1))*e.slideWidth:(e.slideCount+2*e.slidesToShow)*e.slideWidth;var n={opacity:1,width:t,WebkitTransform:"translate3d("+e.left+"px, 0px, 0px)",transform:"translate3d("+e.left+"px, 0px, 0px)",transition:"",WebkitTransition:"",msTransform:"translateX("+e.left+"px)"};return!window.addEventListener&&window.attachEvent&&(n.marginLeft=e.left+"px"),n};t.getTrackCSS=s;var l=function(e){i(e,["left","variableWidth","slideCount","slidesToShow","slideWidth","speed","cssEase"]);var t=s(e);return t.WebkitTransition="-webkit-transform "+e.speed+"ms "+e.cssEase,t.transition="transform "+e.speed+"ms "+e.cssEase,t};t.getTrackAnimateCSS=l;var u=function(e){i(e,["slideIndex","trackRef","infinite","centerMode","slideCount","slidesToShow","slidesToScroll","slideWidth","listWidth","variableWidth"]);var t,n,r=0;if(e.fade)return 0;if(e.infinite&&(e.slideCount>e.slidesToShow&&(r=e.slideWidth*e.slidesToShow*-1),e.slideCount%e.slidesToScroll!==0&&e.slideIndex+e.slidesToScroll>e.slideCount&&e.slideCount>e.slidesToShow&&(r=e.slideIndex>e.slideCount?(e.slidesToShow-(e.slideIndex-e.slideCount))*e.slideWidth*-1:e.slideCount%e.slidesToScroll*e.slideWidth*-1)),e.centerMode&&(e.infinite?r+=e.slideWidth*Math.floor(e.slidesToShow/2):r=e.slideWidth*Math.floor(e.slidesToShow/2)),t=e.slideIndex*e.slideWidth*-1+r,e.variableWidth===!0){var o;e.slideCount<=e.slidesToShow||e.infinite===!1?n=a["default"].findDOMNode(e.trackRef).childNodes[e.slideIndex]:(o=e.slideIndex+e.slidesToShow,n=a["default"].findDOMNode(e.trackRef).childNodes[o]),t=n?-1*n.offsetLeft:0,e.centerMode===!0&&(n=e.infinite===!1?a["default"].findDOMNode(e.trackRef).children[e.slideIndex]:a["default"].findDOMNode(e.trackRef).children[e.slideIndex+e.slidesToShow+1],t=n?-1*n.offsetLeft:0,t+=(e.listWidth-n.offsetWidth)/2)}return t};t.getTrackLeft=u},function(e,t,n){"use strict";var r=n(272);e.exports=function(e,t,n,o){var a=n?n.call(o,e,t):void 0;if(void 0!==a)return!!a;if(e===t)return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;var i=r(e),s=r(t),l=i.length;if(l!==s.length)return!1;o=o||null;for(var u=Object.prototype.hasOwnProperty.bind(t),c=0;l>c;c++){var p=i[c];if(!u(p))return!1;var f=e[p],d=t[p],h=n?n.call(o,f,d,p):void 0;if(h===!1||void 0===h&&f!==d)return!1}return!0}},function(e,t){(function(t){function n(e,t){function n(){if(!o){if(r("throwDeprecation"))throw new Error(t);r("traceDeprecation")?console.trace(t):console.warn(t),o=!0}return e.apply(this,arguments)}if(r("noDeprecation"))return e;var o=!1;return n}function r(e){try{if(!t.localStorage)return!1}catch(n){return!1}var r=t.localStorage[e];return null==r?!1:"true"===String(r).toLowerCase()}e.exports=n}).call(t,function(){return this}())},function(e,t,n){function r(e){return n(o(e))}function o(e){return a[e]||function(){throw new Error("Cannot find module '"+e+"'.")}()}var a={"./affix/index.jsx":145,"./affix/style/index.js":146,"./alert/index.jsx":147,"./alert/style/index.js":148,"./badge/index.jsx":150,"./badge/style/index.js":151,"./breadcrumb/index.jsx":153,"./breadcrumb/style/index.js":154,"./button/index.jsx":15,"./button/style/index.js":23,"./calendar/index.jsx":158,"./calendar/style/index.js":160,"./card/index.jsx":161,"./card/style/index.js":162,"./carousel/index.jsx":163,"./carousel/style/index.js":164,"./cascader/index.jsx":165,"./cascader/style/index.js":166,"./checkbox/index.jsx":18,"./checkbox/style/index.js":19,"./col/index.js":168,"./col/style/index.js":169,"./collapse/index.jsx":170,"./collapse/style/index.js":171,"./date-picker/index.jsx":175,"./date-picker/style/index.js":176,"./dropdown/index.jsx":54,"./dropdown/style/index.js":55,"./form/index.jsx":182,"./form/style/index.js":183,"./icon/index.jsx":7,"./icon/style/index.js":184,"./input-number/index.jsx":185,"./input-number/style/index.js":186,"./input/index.jsx":56,"./input/style/index.js":13,"./layout/index.jsx":31,"./layout/style/index.js":57,"./locale-provider/index.jsx":192,"./locale-provider/style/index.js":193,"./menu/index.jsx":194,"./menu/style/index.js":195,"./message/index.jsx":196,"./message/style/index.js":197,"./modal/index.jsx":199,"./modal/style/index.js":200,"./notification/index.jsx":201,"./notification/style/index.js":202,"./pagination/index.jsx":60,"./pagination/style/index.js":61,"./popconfirm/index.jsx":206,"./popconfirm/style/index.js":207,"./popover/index.jsx":208,"./popover/style/index.js":62,"./progress/index.jsx":63,"./progress/style/index.js":64,"./queue-anim/index.jsx":210,"./queue-anim/style/index.js":211,"./radio/index.jsx":24,"./radio/style/index.js":34,"./rate/index.jsx":213,"./rate/style/index.js":214,"./row/index.js":215,"./row/style/index.js":216,"./select/index.jsx":25,"./select/style/index.js":26,"./slider/index.jsx":217,"./slider/style/index.js":218,"./spin/index.jsx":66,"./spin/style/index.js":67,"./steps/index.jsx":219,"./steps/style/index.js":220,"./style/index.js":221,"./switch/index.jsx":222,"./switch/style/index.js":223,"./table/index.jsx":225,"./table/style/index.js":226,"./tabs/index.jsx":228,"./tabs/style/index.js":229,"./tag/index.jsx":230,"./tag/style/index.js":231,"./time-picker/index.jsx":232,"./time-picker/style/index.js":69,"./timeline/index.jsx":234,"./timeline/style/index.js":235,"./tooltip/index.jsx":35,"./tooltip/style/index.js":71,"./transfer/index.jsx":236,"./transfer/style/index.js":239,"./tree-select/index.jsx":240,"./tree-select/style/index.js":241,"./tree/index.jsx":242,"./tree/style/index.js":243,"./upload/index.jsx":245,"./upload/style/index.js":246,"./validation/index.jsx":248,"./validation/style/index.js":249};r.keys=function(){return Object.keys(a)},r.resolve=o,e.exports=r,r.id=121},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 a(){return f}function i(){return d}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=i;"defaultPrevented"in e?r=e.defaultPrevented?a:i:"getPreventDefault"in e?r=e.getPreventDefault()?a:i:"returnValue"in e&&(r=e.returnValue===d?a:i),this.isDefaultPrevented=r;var o=[],s=void 0,l=void 0,c=void 0,p=h.concat();for(y.forEach(function(e){t.match(e.reg)&&(p=p.concat(e.props),e.fix&&o.push(e.fix))}),l=p.length;l;)c=p[--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(122),u=r(l),c=n(11),p=r(c),f=!0,d=!1,h=["altKey","bubbles","cancelable","ctrlKey","currentTarget","eventPhase","metaKey","shiftKey","target","timeStamp","view","type"],y=[{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,a=t.wheelDelta,i=t.axis,s=t.wheelDeltaY,l=t.wheelDeltaX,u=t.detail;a&&(o=a/120),u&&(o=0-(u%3===0?u/3:u)),void 0!==i&&(i===e.HORIZONTAL_AXIS?(r=0,n=0-o):i===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,a=void 0,i=e.target,s=t.button;return i&&o(e.pageX)&&!o(t.clientX)&&(n=i.ownerDocument||document,r=n.documentElement,a=n.body,e.pageX=t.clientX+(r&&r.scrollLeft||a&&a.scrollLeft||0)-(r&&r.clientLeft||a&&a.clientLeft||0),e.pageY=t.clientY+(r&&r.scrollTop||a&&a.scrollTop||0)-(r&&r.clientTop||a&&a.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===i?e.toElement:e.fromElement),e}}],v=u["default"].prototype;(0,p["default"])(s.prototype,v,{constructor:s,preventDefault:function(){var e=this.nativeEvent;e.preventDefault?e.preventDefault():e.returnValue=d,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 i["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 a=n(123),i=r(a);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"object"!==("undefined"==typeof e?"undefined":s(e))?t:void 0}function a(e){this.rules=null,this._messages=p.messages,this.define(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},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(5),u=n(137),c=r(u),p=n(126),f=n(8),d=n(274),h=r(d);a.prototype={messages:function(e){return e&&(this._messages=(0,h["default"])((0,p.newMessages)(),e,o)),this._messages},define:function(e){if(!e)throw new Error("Cannot configure a schema with no rules");if("object"!==("undefined"==typeof e?"undefined":s(e))||Array.isArray(e))throw new Error("Rules must be an object");this.rules={};var t=void 0,n=void 0;for(t in e)e.hasOwnProperty(t)&&(n=e[t],this.rules[t]=Array.isArray(n)?n:[n])},validate:function(e){function t(e){function t(e){Array.isArray(e)?o=o.concat.apply(o,e):o.push(e)}var n=void 0,r=void 0,o=[],a={};for(n=0;n<e.length;n++)t(e[n]);if(o.length)for(n=0;n<o.length;n++)r=o[n].field,a[r]=a[r]||[],a[r].push(o[n]);else o=null,a=null;y(o,a)}var n=this,r=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],u=arguments[2],c=e,d=r;if(!this.rules)throw new Error("Cannot validate with no rules.");var y=u;if("function"==typeof d&&(y=d,d={}),d.messages){var v=this.messages();v===p.messages&&(v=(0,p.newMessages)()),(0,h["default"])(v,d.messages,o),d.messages=v}else d.messages=this.messages();d.error=f.error;var m=void 0,g=void 0,b={},P=d.keys||Object.keys(this.rules);P.forEach(function(t){m=n.rules[t],g=c[t],m.forEach(function(r){var o=r;"function"==typeof o.transform&&(c===e&&(c=i({},c)),g=c[t]=o.transform(g)),o="function"==typeof o?{validator:o}:i({},o),o.field=t,o.fullField=o.fullField||t,o.type=n.getType(o),o.validator=n.getValidationMethod(o),o.validator&&(b[t]=b[t]||[],b[t].push({rule:o,value:g,source:c,field:t}))})});var O={};(0,l.asyncMap)(b,d,function(e,t){function n(e,t){return i({},t,{fullField:o.fullField+"."+e})}function r(){var r=arguments.length<=0||void 0===arguments[0]?[]:arguments[0],s=r;if(Array.isArray(s)||(s=[s]),s.length&&(0,l.warning)("async-validator:",s),s.length&&o.message&&(s=[].concat(o.message)),s=s.map((0,l.complementError)(o)),(d.first||d.fieldFirst)&&s.length)return O[o.field]=1,t(s);if(u){if(o.required&&!e.value)return s=o.message?[].concat(o.message).map((0,l.complementError)(o)):[d.error(o,(0,l.format)(d.messages.required,o.field))],t(s);var c={};if(o.defaultField)for(var p in e.value)e.value.hasOwnProperty(p)&&(c[p]=o.defaultField);c=i({},c,e.rule.fields);for(var f in c)if(c.hasOwnProperty(f)){var h=Array.isArray(c[f])?c[f]:[c[f]];c[f]=h.map(n.bind(null,f))}var y=new a(c);y.messages(d.messages),e.rule.options&&(e.rule.options.messages=d.messages,e.rule.options.error=d.error),y.validate(e.value,e.rule.options||d,function(e){t(e&&e.length?s.concat(e):e)})}else t(s)}var o=e.rule,u=!("object"!==o.type&&"array"!==o.type||"object"!==s(o.fields)&&"object"!==s(o.defaultField));u=u&&(o.required||!o.required&&e.value),o.field=e.field,o.validator(o,e.value,r,e.source,d)},function(e){t(e)})},getType:function(e){if(void 0===e.type&&e.pattern instanceof RegExp&&(e.type="pattern"),"function"!=typeof e.validator&&e.type&&!c["default"].hasOwnProperty(e.type))throw new Error((0,l.format)("Unknown rule type %s",e.type));return e.type||"string"},getValidationMethod:function(e){return"function"==typeof e.validator?e.validator:c["default"][e.type]||!1}},a.register=function(e,t){if("function"!=typeof t)throw new Error("Cannot register a validator by type, validator is not a function");c["default"][e]=t},a.messages=p.messages,t["default"]=a,e.exports=t["default"]},function(e,t){"use strict";function n(){return{"default":"Validation error on field %s",required:"%s is required","enum":"%s must be one of %s",whitespace:"%s cannot be empty",date:{format:"%s date %s is invalid for format %s",parse:"%s date could not be parsed, %s is invalid ",invalid:"%s date %s is invalid"},types:{string:"%s is not a %s",method:"%s is not a %s (function)",array:"%s is not an %s",object:"%s is not an %s",number:"%s is not a %s",date:"%s is not a %s","boolean":"%s is not a %s",integer:"%s is not an %s","float":"%s is not a %s",regexp:"%s is not a valid %s",email:"%s is not a valid %s",url:"%s is not a valid %s",hex:"%s is not a valid %s"},string:{len:"%s must be exactly %s characters",min:"%s must be at least %s characters",max:"%s cannot be longer than %s characters",range:"%s must be between %s and %s characters"},number:{len:"%s must equal %s",min:"%s cannot be less than %s",max:"%s cannot be greater than %s",range:"%s must be between %s and %s"},array:{len:"%s must be exactly %s in length",min:"%s cannot be less than %s in length",max:"%s cannot be greater than %s in length",range:"%s must be between %s and %s in length"},pattern:{mismatch:"%s value %s does not match pattern %s"},clone:function(){var e=JSON.parse(JSON.stringify(this));return e.clone=this.clone,e}}}Object.defineProperty(t,"__esModule",{value:!0}),t.newMessages=n;t.messages=n()},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,n,r,o){e[s]=Array.isArray(e[s])?e[s]:[],-1===e[s].indexOf(t)&&r.push(i.format(o.messages[s],e.fullField,e[s].join(", ")))}Object.defineProperty(t,"__esModule",{value:!0});var a=n(5),i=r(a),s="enum";t["default"]=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,t,n,r,o){e.pattern instanceof RegExp&&(e.pattern.test(t)||r.push(i.format(o.messages.pattern.mismatch,e.fullField,t,e.pattern)))}Object.defineProperty(t,"__esModule",{value:!0});var a=n(5),i=r(a);t["default"]=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,t,n,r,o){var a="number"==typeof e.len,s="number"==typeof e.min,l="number"==typeof e.max,u=t,c=null,p="number"==typeof t,f="string"==typeof t,d=Array.isArray(t);return p?c="number":f?c="string":d&&(c="array"),c?((f||d)&&(u=t.length),void(a?u!==e.len&&r.push(i.format(o.messages[c].len,e.fullField,e.len)):s&&!l&&u<e.min?r.push(i.format(o.messages[c].min,e.fullField,e.min)):l&&!s&&u>e.max?r.push(i.format(o.messages[c].max,e.fullField,e.max)):s&&l&&(u<e.min||u>e.max)&&r.push(i.format(o.messages[c].range,e.fullField,e.min,e.max)))):!1}Object.defineProperty(t,"__esModule",{value:!0});var a=n(5),i=r(a);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(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 a(e,t,n,r,o){if(e.required&&void 0===t)return void(0,c["default"])(e,t,n,r,o);var a=["integer","float","array","regexp","object","method","email","number","date","url","hex"],s=e.type;a.indexOf(s)>-1?f[s](t)||r.push(l.format(o.messages.types[s],e.fullField,e.type)):s&&("undefined"==typeof t?"undefined":i(t))!==e.type&&r.push(l.format(o.messages.types[s],e.fullField,e.type))}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},s=n(5),l=o(s),u=n(47),c=r(u),p={email:/^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/,url:new RegExp("^(?!mailto:)(?:(?:http|https|ftp)://)(?:\\S+(?::\\S*)?@)?(?:(?:(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[0-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))|localhost)(?::\\d{2,5})?(?:(/|\\?|#)[^\\s]*)?$","i"),hex:/^#?([a-f0-9]{6}|[a-f0-9]{3})$/i},f={integer:function(e){return f.number(e)&&parseInt(e,10)===e},"float":function(e){return f.number(e)&&!f.integer(e)},array:function(e){return Array.isArray(e)},regexp:function(e){if(e instanceof RegExp)return!0;try{return!!new RegExp(e)}catch(t){return!1}},date:function(e){return"function"==typeof e.getTime&&"function"==typeof e.getMonth&&"function"==typeof e.getYear},number:function(e){return isNaN(e)?!1:"number"==typeof e},object:function(e){return"object"===("undefined"==typeof e?"undefined":i(e))&&!f.array(e)},method:function(e){return"function"==typeof e},email:function(e){return"string"==typeof e&&!!e.match(p.email)},url:function(e){return"string"==typeof e&&!!e.match(p.url)},hex:function(e){return"string"==typeof e&&!!e.match(p.hex)}};t["default"]=a,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,n,r,o){(/^\s+$/.test(t)||""===t)&&r.push(i.format(o.messages.whitespace,e.fullField))}Object.defineProperty(t,"__esModule",{value:!0});var a=n(5),i=r(a);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,r,o){var a=[],l=e.required||!e.required&&r.hasOwnProperty(e.field);if(l){if((0,s.isEmptyValue)(t,"array")&&!e.required)return n();i["default"].required(e,t,r,a,o,"array"),(0,s.isEmptyValue)(t,"array")||(i["default"].type(e,t,r,a,o),i["default"].range(e,t,r,a,o))}n(a)}Object.defineProperty(t,"__esModule",{value:!0});var a=n(8),i=r(a),s=n(5);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,r,o){var i=[],l=e.required||!e.required&&r.hasOwnProperty(e.field);if(l){if((0,a.isEmptyValue)(t)&&!e.required)return n();s["default"].required(e,t,r,i,o),void 0!==t&&s["default"].type(e,t,r,i,o)}n(i)}Object.defineProperty(t,"__esModule",{value:!0});var a=n(5),i=n(8),s=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,t,n,r,o){var a=[],l=e.required||!e.required&&r.hasOwnProperty(e.field);if(l){if((0,s.isEmptyValue)(t)&&!e.required)return n();i["default"].required(e,t,r,a,o),(0,s.isEmptyValue)(t)||(i["default"].type(e,t,r,a,o),t&&i["default"].range(e,t.getTime(),r,a,o))}n(a)}Object.defineProperty(t,"__esModule",{value:!0});var a=n(8),i=r(a),s=n(5);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,r,o){var a=[],u=e.required||!e.required&&r.hasOwnProperty(e.field);if(u){if((0,s.isEmptyValue)(t)&&!e.required)return n();i["default"].required(e,t,r,a,o),t&&i["default"][l](e,t,r,a,o)}n(a)}Object.defineProperty(t,"__esModule",{value:!0});var a=n(8),i=r(a),s=n(5),l="enum";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,r,o){var a=[],l=e.required||!e.required&&r.hasOwnProperty(e.field);if(l){if((0,s.isEmptyValue)(t)&&!e.required)return n();i["default"].required(e,t,r,a,o),void 0!==t&&(i["default"].type(e,t,r,a,o),i["default"].range(e,t,r,a,o))}n(a)}Object.defineProperty(t,"__esModule",{value:!0});var a=n(8),i=r(a),s=n(5);t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t["default"]={string:n(144),method:n(139),number:n(140),"boolean":n(133),regexp:n(143),integer:n(138),"float":n(136),array:n(132),object:n(141),"enum":n(135),pattern:n(142),email:n(30),url:n(30),date:n(134),hex:n(30)},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 a=[],l=e.required||!e.required&&r.hasOwnProperty(e.field);if(l){if((0,s.isEmptyValue)(t)&&!e.required)return n();i["default"].required(e,t,r,a,o),void 0!==t&&(i["default"].type(e,t,r,a,o),i["default"].range(e,t,r,a,o))}n(a)}Object.defineProperty(t,"__esModule",{value:!0});var a=n(8),i=r(a),s=n(5);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,r,o){var a=[],l=e.required||!e.required&&r.hasOwnProperty(e.field);if(l){if((0,s.isEmptyValue)(t)&&!e.required)return n();i["default"].required(e,t,r,a,o),void 0!==t&&i["default"].type(e,t,r,a,o)}n(a)}Object.defineProperty(t,"__esModule",{value:!0});var a=n(8),i=r(a),s=n(5);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,r,o){var a=[],l=e.required||!e.required&&r.hasOwnProperty(e.field);if(l){if((0,s.isEmptyValue)(t)&&!e.required)return n();i["default"].required(e,t,r,a,o),void 0!==t&&(i["default"].type(e,t,r,a,o),i["default"].range(e,t,r,a,o))}n(a)}Object.defineProperty(t,"__esModule",{value:!0});var a=n(8),i=r(a),s=n(5);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,r,o){var a=[],l=e.required||!e.required&&r.hasOwnProperty(e.field);if(l){if((0,s.isEmptyValue)(t)&&!e.required)return n();i["default"].required(e,t,r,a,o),void 0!==t&&i["default"].type(e,t,r,a,o)}n(a)}Object.defineProperty(t,"__esModule",{value:!0});var a=n(8),i=r(a),s=n(5);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,r,o){var a=[],l=e.required||!e.required&&r.hasOwnProperty(e.field);if(l){if((0,s.isEmptyValue)(t,"string")&&!e.required)return n();i["default"].required(e,t,r,a,o),(0,s.isEmptyValue)(t,"string")||i["default"].pattern(e,t,r,a,o)}n(a)}Object.defineProperty(t,"__esModule",{value:!0});var a=n(8),i=r(a),s=n(5);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,r,o){var a=[],l=e.required||!e.required&&r.hasOwnProperty(e.field);if(l){if((0,s.isEmptyValue)(t)&&!e.required)return n();i["default"].required(e,t,r,a,o),(0,s.isEmptyValue)(t)||i["default"].type(e,t,r,a,o)}n(a)}Object.defineProperty(t,"__esModule",{value:!0});var a=n(8),i=r(a),s=n(5);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,r,o){var a=[],l=e.required||!e.required&&r.hasOwnProperty(e.field);if(l){if((0,s.isEmptyValue)(t,"string")&&!e.required)return n();i["default"].required(e,t,r,a,o,"string"),(0,s.isEmptyValue)(t,"string")||(i["default"].type(e,t,r,a,o),i["default"].range(e,t,r,a,o),i["default"].pattern(e,t,r,a,o),e.whitespace===!0&&i["default"].whitespace(e,t,r,a,o))}n(a)}Object.defineProperty(t,"__esModule",{value:!0});var a=n(8),i=r(a),s=n(5);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){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(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 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):o(e,t))}function l(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 u(e){var t=e.getBoundingClientRect(),n=document.body,r=e.clientTop||n.clientTop||0,o=e.clientLeft||n.clientLeft||0,a=l(window,!0),i=l(window);return{top:t.top+a-r,left:t.left+i-o}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var c,p,f=n(1),d=r(f),h=n(4),y=r(h),v=n(6),m=n(2),g=r(m),b=n(17),P=r(b),O=(p=c=function(e){function t(n){a(this,t);var r=i(this,e.call(this,n));return r.handleScroll=function(){var e=r.props,t=e.offsetTop,n=e.offsetBottom,o=e.offset;t=t||o;var a=l(window,!0),i=u(y["default"].findDOMNode(r)),s={width:y["default"].findDOMNode(r.refs.fixedNode).offsetWidth,height:y["default"].findDOMNode(r.refs.fixedNode).offsetHeight},c={};"number"!=typeof t&&"number"!=typeof n?(c.top=!0,t=0):(c.top="number"==typeof t,c.bottom="number"==typeof n),a>i.top-t&&c.top?r.state.affixStyle||r.setState({affixStyle:{position:"fixed",top:t,left:i.left,width:y["default"].findDOMNode(r).offsetWidth}},function(){return r.props.onChange(!!r.state.affixStyle)}):a<i.top+s.height+n-window.innerHeight&&c.bottom?r.state.affixStyle||r.setState({affixStyle:{position:"fixed",bottom:n,left:i.left,width:y["default"].findDOMNode(r).offsetWidth}},function(){return r.props.onChange(!!r.state.affixStyle)}):r.state.affixStyle&&r.setState({affixStyle:null},function(){return r.props.onChange(!!r.state.affixStyle)})},r.state={affixStyle:null},r}return s(t,e),t.prototype.componentDidMount=function(){(0,P["default"])(!("offset"in this.props),"`offset` prop of Affix is deprecated, use `offsetTop` instead."),this.scrollEvent=v.Dom.addEventListener(window,"scroll",this.handleScroll),this.resizeEvent=v.Dom.addEventListener(window,"resize",this.handleScroll)},t.prototype.componentWillUnmount=function(){this.scrollEvent&&this.scrollEvent.remove(),this.resizeEvent&&this.resizeEvent.remove()},t.prototype.render=function(){var e=(0,g["default"])({"ant-affix":this.state.affixStyle});return d["default"].createElement("div",this.props,d["default"].createElement("div",{className:e,ref:"fixedNode",style:this.state.affixStyle},this.props.children))},t}(d["default"].Component),c.propTypes={offsetTop:d["default"].PropTypes.number,offsetBottom:d["default"].PropTypes.number},c.defaultProps={onChange:function(){}},p);t["default"]=O,e.exports=t["default"]},[459,418],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],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(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){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}),t["default"]=void 0;var u,c,p=n(1),f=r(p),d=n(4),h=r(d),y=n(9),v=r(y),m=n(7),g=r(m),b=n(2),P=r(b),O=(c=u=function(e){function t(n){i(this,t);var r=s(this,e.call(this,n));return r.handleClose=function(e){e.preventDefault();var t=h["default"].findDOMNode(r);t.style.height=t.offsetHeight+"px",t.style.height=t.offsetHeight+"px",r.setState({closing:!1}),r.props.onClose.call(r,e)},r.animationEnd=function(){r.setState({closed:!0,closing:!0})},r.state={closing:!0,closed:!1},r}return l(t,e),t.prototype.render=function(){var e,t=this.props,n=t.closable,r=t.description,o=t.type,i=t.prefixCls,s=t.message,l=t.closeText,u=t.showIcon,c="";switch(o){case"success":c="check-circle";break;case"info":c="info-circle";break;case"error":c="cross-circle";break;case"warning":c="exclamation-circle";break;default:c="default"}r&&(c+="-o");var p=(0,P["default"])((e={},a(e,i,!0),a(e,i+"-"+o,!0),a(e,i+"-close",!this.state.closing),a(e,i+"-with-description",!!r),a(e,i+"-no-icon",!u),e));return l&&(n=!0),this.state.closed?null:f["default"].createElement(v["default"],{component:"",showProp:"data-show",transitionName:"slide-up",onEnd:this.animationEnd},f["default"].createElement("div",{"data-show":this.state.closing,className:p},u?f["default"].createElement(g["default"],{className:"ant-alert-icon",type:c}):null,f["default"].createElement("span",{className:i+"-message"},s),f["default"].createElement("span",{className:i+"-description"},r),n?f["default"].createElement("a",{onClick:this.handleClose,className:i+"-close-icon"},l||f["default"].createElement(g["default"],{type:"cross"})):null))},t}(f["default"].Component),u.defaultProps={prefixCls:"ant-alert",showIcon:!1,onClose:function(){},type:"info"},c);t["default"]=O,e.exports=t["default"]},[459,419],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],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(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 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):o(e,t))}function l(e){return e?e.toString().split("").reverse().map(function(e){return Number(e)}):[]}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var u,c,p=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},f=n(1),d=r(f),h=n(4),y=n(48),v=r(y),m=(c=u=function(e){function t(n){a(this,t);var r=i(this,e.call(this,n));return r.state={animateStarted:!0,count:n.count},r}return s(t,e),t.prototype.componentDidMount=function(){(0,v["default"])()||((0,h.findDOMNode)(this).className+=" not-support-css-animation")},t.prototype.getPositionByNum=function(e,t){if(this.state.animateStarted)return 10+e;var n=l(this.state.count)[t],r=l(this.lastCount)[t];return this.state.count>this.lastCount?n>=r?10+e:20+e:r>=n?10+e:e},t.prototype.componentWillReceiveProps=function(e){var t=this;if("count"in e){if(this.state.count===e.count)return;this.lastCount=this.state.count,this.setState({animateStarted:!0},function(){setTimeout(function(){t.setState({animateStarted:!1,count:e.count},function(){t.props.onAnimated()})},5)})}},t.prototype.renderNumberList=function(e){for(var t=[],n=0;30>n;n++){var r=e===n?"current":null;t.push(d["default"].createElement("p",{key:n,className:r},n%10))}return t},t.prototype.renderCurrentNumber=function(e,t){var n=this.getPositionByNum(e,t),r=this.props.height,o=this.state.animateStarted||void 0===l(this.lastCount)[t];return(0,f.createElement)("span",{className:this.props.prefixCls+"-only",style:{transition:o&&"none",WebkitTransform:"translate3d(0, "+-n*r+"px, 0)",transform:"translate3d(0, "+-n*r+"px, 0)",height:r},key:t},this.renderNumberList(n))},t.prototype.renderNumberElement=function(){var e=this,t=this.state;return!t.count||isNaN(t.count)?t.count:l(t.count).map(function(t,n){return e.renderCurrentNumber(t,n)}).reverse()},t.prototype.render=function(){var e=p({},this.props,{className:this.props.prefixCls+" "+this.props.className});return(0,f.createElement)(this.props.component,e,this.renderNumberElement())},t}(d["default"].Component),u.defaultProps={prefixCls:"ant-scroll-number",count:null,component:"sup",onAnimated:function(){},height:18},u.propTypes={count:d["default"].PropTypes.oneOfType([d["default"].PropTypes.string,d["default"].PropTypes.number]),component:d["default"].PropTypes.string,onAnimated:d["default"].PropTypes.func,height:d["default"].PropTypes.number},c);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){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(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){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}),t["default"]=void 0;var u,c,p=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},f=n(1),d=r(f),h=n(9),y=r(h),v=n(149),m=r(v),g=n(2),b=r(g),P=(c=u=function(e){function t(){return i(this,t),s(this,e.apply(this,arguments))}return l(t,e),t.prototype.render=function(){var e,t=this.props,n=t.count,r=t.prefixCls,o=t.overflowCount,i=t.className,s=t.style,l=t.children,u=this.props.dot;n=n>o?o+"+":n,u&&(n="");var c=!(n&&"0"!==n||u),f=r+(u?"-dot":"-count"),h=(0,b["default"])((e={},a(e,i,!!i),a(e,r,!0),a(e,r+"-not-a-wrapper",!l),e));return d["default"].createElement("span",p({className:h,title:n},this.props,{style:null}),l,d["default"].createElement(y["default"],{component:"",showProp:"data-show",transitionName:r+"-zoom",transitionAppear:!0},c?null:d["default"].createElement(m["default"],{"data-show":!c,className:f,count:n,style:s})))},t}(d["default"].Component),u.defaultProps={prefixCls:"ant-badge",count:null,dot:!1,overflowCount:99},u.propTypes={count:d["default"].PropTypes.oneOfType([d["default"].PropTypes.string,d["default"].PropTypes.number]),dot:d["default"].PropTypes.bool,overflowCount:d["default"].PropTypes.number},c);t["default"]=P,e.exports=t["default"]},[459,420],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],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(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 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):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var l,u,c=n(1),p=r(c),f=n(50),d=r(f),h=function(e,t,n){if(!e)return null;var r=Object.keys(n).join("|"),o=e.replace(new RegExp(":("+r+")","g"),function(e,t){return n[t]||e});return p["default"].createElement("span",null,o)},y=(u=l=function(e){function t(){return a(this,t),i(this,e.apply(this,arguments))}return s(t,e),t.prototype.render=function(){var e=void 0,t=this.props,n=t.separator,r=t.prefixCls,o=t.routes,a=t.params,i=t.children,s=t.linkRender,l=t.nameRender;return o&&o.length>0?!function(){var t=[],r=o.length-1;e=o.map(function(e,o){e.path=e.path||"";var i=e.path.replace(/^\//,"");Object.keys(a).forEach(function(e){i=i.replace(":"+e,a[e])}),i&&t.push(i);var u=l(e.breadcrumbName,e,a);if(u){var c=o===r?u:s("/"+t.join("/"),u,t);return p["default"].createElement(d["default"],{separator:n,key:e.breadcrumbName||o},c)}return null})}():e=p["default"].Children.map(i,function(e,t){return(0,c.cloneElement)(e,{separator:n,key:t})}),p["default"].createElement("div",{className:r},e)},t}(p["default"].Component),l.defaultProps={prefixCls:"ant-breadcrumb",separator:"/",linkRender:function(e,t){return p["default"].createElement("a",{href:"#"+e},t)},nameRender:h},l.propTypes={prefixCls:p["default"].PropTypes.string,separator:p["default"].PropTypes.oneOfType([p["default"].PropTypes.string,p["default"].PropTypes.element]),routes:p["default"].PropTypes.array,params:p["default"].PropTypes.object,linkRender:p["default"].PropTypes.func,nameRender:p["default"].PropTypes.func},u);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(152),a=r(o),i=n(50),s=r(i);a["default"].Item=s["default"],t["default"]=a["default"],e.exports=t["default"]},[459,421],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 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 i(e){var t,n=e.size,r=e.className,i=a(e,["size","className"]),l={large:"lg",small:"sm"}[n]||"",c=(0,p["default"])((t={"ant-btn-group":!0},o(t,f+l,l),o(t,r,r),t));return u["default"].createElement("div",s({},i,{className:c}))}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};t["default"]=i;var l=n(1),u=r(l),c=n(2),p=r(c),f="ant-btn-group-";i.propTypes={size:u["default"].PropTypes.oneOf(["large","small"])},e.exports=t["default"]},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],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(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 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))}function c(e){return"string"==typeof e}function p(e){return c(e.type)&&w(e.props.children)?m["default"].cloneElement(e,{},e.props.children.split("").join(" ")):c(e)?(w(e)&&(e=e.split("").join(" ")),m["default"].createElement("span",null,e)):e}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var f,d,h,y=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},v=n(1),m=r(v),g=n(2),b=r(g),P=n(4),O=n(7),C=r(O),T=/^[\u4e00-\u9fa5]{2}$/,w=T.test.bind(T),x=(d=f=function(e){function t(){var n,r,o;s(this,t);for(var a=arguments.length,i=Array(a),u=0;a>u;u++)i[u]=arguments[u];return n=r=l(this,e.call.apply(e,[this].concat(i))),h.call(r),o=n,l(r,o)}return u(t,e),t.prototype.componentWillUnmount=function(){this.clickedTimeout&&clearTimeout(this.clickedTimeout),this.timeout&&clearTimeout(this.timeout)},t.prototype.render=function(){var e,t=this.props,n=t.type,r=t.shape,o=t.size,s=t.className,l=t.htmlType,u=t.children,c=t.icon,f=t.loading,d=t.prefixCls,h=i(t,["type","shape","size","className","htmlType","children","icon","loading","prefixCls"]),v={large:"lg",small:"sm"}[o]||"",g=(0,b["default"])((e={},a(e,d,!0),a(e,d+"-"+n,n),a(e,d+"-"+r,r),a(e,d+"-"+v,v),a(e,d+"-icon-only",!u&&c),a(e,d+"-loading",f),a(e,s,s),e)),P=f?"loading":c,O=m["default"].Children.map(u,p);return m["default"].createElement("button",y({},h,{type:l||"button",className:g,onMouseUp:this.handleMouseUp,onClick:this.handleClick}),P?m["default"].createElement(C["default"],{type:P}):null,O)},t}(m["default"].Component),f.defaultProps={prefixCls:"ant-btn",onClick:function(){},loading:!1},f.propTypes={type:m["default"].PropTypes.string,shape:m["default"].PropTypes.oneOf(["circle","circle-outline"]),size:m["default"].PropTypes.oneOf(["large","default","small"]),htmlType:m["default"].PropTypes.oneOf(["submit","button","reset"]),onClick:m["default"].PropTypes.func,loading:m["default"].PropTypes.bool,className:m["default"].PropTypes.string,icon:m["default"].PropTypes.string},h=function(){var e=this;this.clearButton=function(t){t.className=t.className.replace(" "+e.props.prefixCls+"-clicked","")},this.handleClick=function(){var t,n=(0,P.findDOMNode)(e);e.clearButton(n),e.clickedTimeout=setTimeout(function(){return n.className+=" "+e.props.prefixCls+"-clicked"},10),clearTimeout(e.timeout),e.timeout=setTimeout(function(){return e.clearButton(n)},500),(t=e.props).onClick.apply(t,arguments)},this.handleMouseUp=function(t){(0,P.findDOMNode)(e).blur(),e.props.onMouseUp&&e.props.onMouseUp(t)}},d);t["default"]=x,e.exports=t["default"]},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],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(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 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):o(e,t))}function l(){}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var u,c,p=n(1),f=r(p),d=n(51),h=n(25),y=r(h),v=n(24),m=y["default"].Option,g=(c=u=function(e){function t(){var n,r,o;a(this,t);for(var s=arguments.length,l=Array(s),u=0;s>u;u++)l[u]=arguments[u];return n=r=i(this,e.call.apply(e,[this].concat(l))),r.onYearChange=function(e){var t=r.props.value.clone();t.setYear(parseInt(e,10)),r.props.onValueChange(t)},r.onMonthChange=function(e){var t=r.props.value.clone();t.setMonth(parseInt(e,10)),r.props.onValueChange(t)},r.onTypeChange=function(e){r.props.onTypeChange(e.target.value)},o=n,i(r,o)}return s(t,e),t.prototype.getYearSelectElement=function(e){for(var t=this.props,n=t.yearSelectOffset,r=t.yearSelectTotal,o=t.locale,a=t.prefixCls,i=t.fullscreen,s=e-n,l=s+r,u="\u5e74"===o.year?"\u5e74":"",c=[],p=s;l>p;p++)c.push(f["default"].createElement(m,{key:""+p},p+u));return f["default"].createElement(y["default"],{style:{width:75},size:i?null:"small",dropdownMatchSelectWidth:!1,dropdownMenuStyle:{minWidth:103},className:a+"-year-select",onChange:this.onYearChange,value:String(e)},c)},t.prototype.getMonthSelectElement=function(e){for(var t=this.props,n=t.locale.format.months,r=t.prefixCls,o=t.fullscreen,a=[],i=0;12>i;i++)a.push(f["default"].createElement(m,{key:""+i},n[i]));return f["default"].createElement(y["default"],{style:{minWidth:70},dropdownMenuStyle:{minWidth:125},size:o?null:"small",dropdownMatchSelectWidth:!1,className:r+"-month-select",value:String(e),onChange:this.onMonthChange},a)},t.prototype.render=function(){var e=this.props,t=e.type,n=e.value,r=e.prefixCls,o=e.locale,a=this.getYearSelectElement(n.getYear()),i="date"===t?this.getMonthSelectElement(n.getMonth()):null,s=f["default"].createElement(v.Group,{onChange:this.onTypeChange,value:t},f["default"].createElement(v.Button,{value:"date"},o.month),f["default"].createElement(v.Button,{value:"month"},o.year));return f["default"].createElement("div",{className:r+"-header"},a,i,s)},t}(f["default"].Component),u.defaultProps={prefixCls:d.PREFIX_CLS+"-header",yearSelectOffset:10,yearSelectTotal:20,onValueChange:l,onTypeChange:l},u.propTypes={value:p.PropTypes.object,locale:p.PropTypes.object,yearSelectOffset:p.PropTypes.number,yearSelectTotal:p.PropTypes.number,onValueChange:p.PropTypes.func,onTypeChange:p.PropTypes.func,prefixCls:p.PropTypes.string,selectPrefixCls:p.PropTypes.string,type:p.PropTypes.string},c);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){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(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 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):o(e,t))}function l(){return null}function u(e){return 10>e?"0"+e:""+e}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var c,p,f,d=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},h=n(1),y=r(h),v=n(10),m=r(v),g=n(159),b=r(g),P=n(285),O=r(P),C=n(51),T=n(157),w=r(T),x=(p=c=function(e){function t(n){a(this,t);var r=i(this,e.call(this,n));return f.call(r),r.state={value:r.parseDateFromValue(n.value||new Date),mode:n.mode},r}return s(t,e),t.prototype.parseDateFromValue=function(e){var t=new m["default"](this.getLocale());return t.setTime(+e),t},t.prototype.componentWillReceiveProps=function(e){"value"in e&&this.setState({value:this.parseDateFromValue(e.value)})},t.prototype.render=function(){var e=this.props,t=this.state,n=t.value,r=t.mode,o=e.prefixCls,a=e.style,i=e.className,s=e.fullscreen,u="year"===r?"month":"date",c=this.getLocale(),p=i||"";return s&&(p+=" "+o+"-fullscreen"),y["default"].createElement("div",{className:p,style:a},y["default"].createElement(w["default"],{fullscreen:s,type:u,value:n,locale:c.lang,prefixCls:o,onTypeChange:this.setType,onValueChange:this.setValue}),y["default"].createElement(O["default"],d({},e,{Select:l,locale:c.lang,type:u,prefixCls:o,showHeader:!1,value:n,monthCellRender:this.monthCellRender,dateCellRender:this.dateCellRender})))},t}(y["default"].Component),c.defaultProps={monthCellRender:l,dateCellRender:l,locale:{},fullscreen:!0,prefixCls:C.PREFIX_CLS,onPanelChange:l,mode:"month"},c.propTypes={monthCellRender:h.PropTypes.func,dateCellRender:h.PropTypes.func,fullscreen:h.PropTypes.bool,locale:h.PropTypes.object,prefixCls:h.PropTypes.string,className:h.PropTypes.string,style:h.PropTypes.object,onPanelChange:h.PropTypes.func,value:h.PropTypes.instanceOf(Date)},c.contextTypes={antLocale:h.PropTypes.object},f=function(){var e=this;this.getLocale=function(){var t=e.props,n=b["default"],r=e.context;r&&r.antLocale&&r.antLocale.Calendar&&(n=r.antLocale.Calendar);var o=d({},n,t.locale);return o.lang=d({},n.lang,t.locale.lang),o},this.monthCellRender=function(t,n){var r=e.props.prefixCls,o=t.getMonth();return y["default"].createElement("div",{className:r+"-month"},y["default"].createElement("div",{className:r+"-value"},n.format.shortMonths[o]),y["default"].createElement("div",{className:r+"-content"},e.props.monthCellRender(t)))},this.dateCellRender=function(t){var n=e.props.prefixCls;return y["default"].createElement("div",{className:n+"-date"},y["default"].createElement("div",{className:n+"-value"},u(t.getDayOfMonth())),y["default"].createElement("div",{className:n+"-content"},e.props.dateCellRender(t)))},this.setValue=function(t){"value"in e.props||e.state.value===t||e.setState({value:t}),e.props.onPanelChange(t,e.state.mode)},this.setType=function(t){var n="date"===t?"month":"year";e.state.mode!==n&&(e.setState({mode:n}),e.props.onPanelChange(e.state.value,n))}},p);t["default"]=x,e.exports=t["default"]},function(e,t,n){"use strict";e.exports=n(52)},function(e,t,n){"use strict";n(3),n(423),n(26),n(34)},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 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}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},s=n(1),l=r(s),u=n(2),c=r(u);t["default"]=function(e){var t,n=e.prefixCls,r=void 0===n?"ant-card":n,s=e.className,u=e.children,p=e.extra,f=e.bodyStyle,d=e.title,h=e.loading,y=e.bordered,v=void 0===y?!0:y,m=a(e,["prefixCls","className","children","extra","bodyStyle","title","loading","bordered"]),g=(0,c["default"])((t={},o(t,r,!0),o(t,s,!!s),o(t,r+"-loading",h),o(t,r+"-bordered",v),t));h&&(u=l["default"].createElement("div",null,l["default"].createElement("p",null,"\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588"),l["default"].createElement("p",null,"\u2588\u2588\u2588\u2588\u2588\u2588\u3000\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588"),l["default"].createElement("p",null,"\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u3000\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588"),l["default"].createElement("p",null,"\u2588\u2588\u2588\u2588\u2588\u3000\u2588\u2588\u2588\u2588\u2588\u2588\u3000\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588"),l["default"].createElement("p",null,"\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u3000\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u3000\u2588\u2588\u2588")));var b=d?l["default"].createElement("div",{className:r+"-head"},l["default"].createElement("h3",{className:r+"-head-title"},d)):null;return l["default"].createElement("div",i({},m,{className:g}),b,p?l["default"].createElement("div",{className:r+"-extra"},p):null,l["default"].createElement("div",{className:r+"-body",style:f},u))},e.exports=t["default"]},[459,424],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],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(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 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):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var l,u,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(406),f=r(p),d=n(1),h=r(d);if("undefined"!=typeof window){var y=function(){return{matches:!1,addListener:function(){},removeListener:function(){}}};window.matchMedia=window.matchMedia||y}var v=(u=l=function(e){function t(){return a(this,t),i(this,e.apply(this,arguments))}return s(t,e),t.prototype.render=function(){var e=c({},this.props);"fade"===e.effect&&(e.fade=!0,e.draggable=!1);var t="ant-carousel";return e.vertical&&(t+=" ant-carousel-vertical"),h["default"].createElement("div",{className:t},h["default"].createElement(f["default"],e))},t}(h["default"].Component),l.defaultProps={dots:!0,arrows:!1},u);t["default"]=v,e.exports=t["default"]},[459,425],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],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a); }return e}function a(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 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}),t["default"]=void 0;var c,p,f,d=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},h=n(1),y=r(h),v=n(297),m=r(v),g=n(56),b=r(g),P=n(7),O=r(P),C=n(46),T=r(C),w=n(2),x=r(w),E=(p=c=function(e){function t(n){s(this,t);var r=l(this,e.call(this,n));f.call(r);var o=void 0;return"value"in n?o=n.value:"defaultValue"in n&&(o=n.defaultValue),r.state={value:o||[],popupVisible:!1},r}return u(t,e),t.prototype.componentWillReceiveProps=function(e){"value"in e&&this.setState({value:e.value||[]})},t.prototype.getLabel=function(){var e=this,t=this.props,n=t.options,r=t.displayRender,o=(0,T["default"])(n,function(t,n){return t.value===e.state.value[n]}),a=o.map(function(e){return e.label});return r(a,o)},t.prototype.render=function(){var e,t,n=this.props,r=n.prefixCls,o=n.children,s=n.placeholder,l=n.size,u=n.disabled,c=n.className,p=n.style,f=n.allowClear,h=i(n,["prefixCls","children","placeholder","size","disabled","className","style","allowClear"]),v=(0,x["default"])({"ant-input-lg":"large"===l,"ant-input-sm":"small"===l}),g=f&&!u&&this.state.value.length>0?y["default"].createElement(O["default"],{type:"cross-circle",className:r+"-picker-clear",onClick:this.clearSelection}):null,P=(0,x["default"])((e={},a(e,r+"-picker-arrow",!0),a(e,r+"-picker-arrow-expand",this.state.popupVisible),e)),C=(0,x["default"])((t={},a(t,c,!!c),a(t,r+"-picker",!0),a(t,r+"-picker-disabled",u),t));return delete h.onChange,y["default"].createElement(m["default"],d({},n,{value:this.state.value,popupVisible:this.state.popupVisible,onPopupVisibleChange:this.handlePopupVisibleChange,onChange:this.handleChange}),o||y["default"].createElement("span",{style:p,className:C},y["default"].createElement(b["default"],d({},h,{placeholder:this.state.value&&this.state.value.length>0?null:s,className:r+"-input ant-input "+v,value:null,disabled:u,readOnly:!0})),y["default"].createElement("span",{className:r+"-picker-label"},this.getLabel()),g,y["default"].createElement(O["default"],{type:"down",className:P})))},t}(y["default"].Component),c.defaultProps={prefixCls:"ant-cascader",placeholder:"Please select",transitionName:"slide-up",popupPlacement:"bottomLeft",onChange:function(){},options:[],displayRender:function(e){return e.join(" / ")},disabled:!1,allowClear:!0,onPopupVisibleChange:function(){}},f=function(){var e=this;this.handleChange=function(t,n){e.setValue(t,n)},this.handlePopupVisibleChange=function(t){e.setState({popupVisible:t}),e.props.onPopupVisibleChange(t)},this.setValue=function(t){var n=arguments.length<=1||void 0===arguments[1]?[]:arguments[1];"value"in e.props||e.setState({value:t}),e.props.onChange(t,n)},this.clearSelection=function(t){t.preventDefault(),t.stopPropagation(),e.setValue([]),e.setState({popupVisible:!1})}},p);t["default"]=E,e.exports=t["default"]},[460,426],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],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(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,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}),t["default"]=void 0;var u,c,p,f=n(1),d=r(f),h=n(18),y=r(h),v=n(16),m=r(v),g=(c=u=function(e){function t(n){i(this,t);var r=s(this,e.call(this,n));p.call(r);var o=void 0;return"value"in n?o=n.value||[]:"defaultValue"in n&&(o=n.defaultValue||[]),r.state={value:o},r}return l(t,e),t.prototype.componentWillReceiveProps=function(e){"value"in e&&this.setState({value:e.value||[]})},t.prototype.shouldComponentUpdate=function(){for(var e=arguments.length,t=Array(e),n=0;e>n;n++)t[n]=arguments[n];return m["default"].shouldComponentUpdate.apply(this,t)},t.prototype.getOptions=function(){var e=this.props.options;return e.map(function(e){return"string"==typeof e?{label:e,value:e}:e})},t.prototype.render=function(){var e=this,t=this.getOptions();return d["default"].createElement("div",{className:"ant-checkbox-group"},t.map(function(t){return d["default"].createElement(y["default"],{disabled:"disabled"in t?t.disabled:e.props.disabled,checked:-1!==e.state.value.indexOf(t.value),onChange:function(){return e.toggleOption(t)},className:"ant-checkbox-group-item",key:t.value},t.label)}))},t}(d["default"].Component),u.defaultProps={options:[],defaultValue:[],onChange:function(){}},u.propTypes={defaultValue:d["default"].PropTypes.array,value:d["default"].PropTypes.array,options:d["default"].PropTypes.array.isRequired,onChange:d["default"].PropTypes.func},p=function(){var e=this;this.toggleOption=function(t){var n=e.state.value.indexOf(t.value),r=[].concat(a(e.state.value));-1===n?r.push(t.value):r.splice(n,1),"value"in e.props||e.setState({value:r}),e.props.onChange(r)}},c);t["default"]=g,e.exports=t["default"]},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(31);t["default"]=r.Col,e.exports=t["default"]},function(e,t,n){"use strict";n(3),n(45)},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],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(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 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):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var l,u,c=n(302),p=r(c),f=n(1),d=r(f),h=(u=l=function(e){function t(){return a(this,t),i(this,e.apply(this,arguments))}return s(t,e),t.prototype.render=function(){return d["default"].createElement(p["default"],this.props)},t}(d["default"].Component),l.Panel=p["default"].Panel,l.defaultProps={prefixCls:"ant-collapse"},u);t["default"]=h,e.exports=t["default"]},[459,428],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],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(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 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):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var l,u,c=n(1),p=r(c),f=n(91),d=r(f),h=n(90),y=r(h),v=(u=l=function(e){function t(){return a(this,t),i(this,e.apply(this,arguments))}return s(t,e),t.prototype.render=function(){return p["default"].createElement(y["default"],this.props)},t}(p["default"].Component),l.defaultProps={locale:d["default"],prefixCls:"ant-calendar"},u);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){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(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 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):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var l,u,c,p=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},f=n(1),d=r(f),h=n(10),y=r(h),v=n(286),m=r(v),g=n(84),b=r(g),P=n(2),O=r(P),C=(u=l=function(e){function t(n){a(this,t);var r=i(this,e.call(this,n));c.call(r);var o=r.props,s=o.value,l=o.defaultValue,u=o.parseDateFromValue,p=s&&s[0]||l[0],f=s&&s[1]||l[1];return r.state={value:[u(p),u(f)]},r}return s(t,e),t.prototype.componentWillReceiveProps=function(e){if("value"in e){var t=e.value||[],n=e.parseDateFromValue(t[0]),r=e.parseDateFromValue(t[1]);this.setState({value:[n,r]})}},t.prototype.render=function(){var e=this,t=this.props,n=t.locale,r=new y["default"](n);r.setTime(Date.now());var o=this.props,a=o.disabledDate,i=o.showTime,s=o.getCalendarContainer,l=o.transitionName,u=o.disabled,c=o.popupStyle,f=o.align,h=o.style,v=o.onOk,g=this.state,P=(0,O["default"])({"ant-calendar-time":i}),C={onChange:this.handleChange},T={onOk:this.handleChange};t.timePicker?C.onChange=function(t){null!==t&&0!==t.length||e.handleChange(t)}:T={};var w="startPlaceholder"in this.props?t.startPlaceholder:n.lang.rangePlaceholder[0],x="endPlaceholder"in t?t.endPlaceholder:n.lang.rangePlaceholder[1],E=d["default"].createElement(m["default"],p({prefixCls:"ant-calendar",className:P,timePicker:t.timePicker,disabledDate:a,dateInputPlaceholder:[w,x],locale:n.lang,onOk:v,defaultValue:[r,r]},T));return d["default"].createElement("span",{className:t.pickerClass,style:h},d["default"].createElement(b["default"],p({formatter:t.getFormatter(),transitionName:l,disabled:u,calendar:E,value:g.value,prefixCls:"ant-calendar-picker-container",style:c,align:f,getCalendarContainer:s,onOpen:t.toggleOpen,onClose:t.toggleOpen},C),function(e){var n=e.value,r=n[0],o=n[1];return d["default"].createElement("span",{className:t.pickerInputClass,disabled:u},d["default"].createElement("input",{disabled:u,onChange:t.handleInputChange,value:r?t.getFormatter().format(r):"",placeholder:w,className:"ant-calendar-range-picker-input"}),d["default"].createElement("span",{className:"ant-calendar-range-picker-separator"}," ~ "),d["default"].createElement("input",{disabled:u,onChange:t.handleInputChange,value:o?t.getFormatter().format(o):"",placeholder:x,className:"ant-calendar-range-picker-input"}),d["default"].createElement("span",{className:"ant-calendar-picker-icon"}))}))},t}(d["default"].Component),l.defaultProps={defaultValue:[]},c=function(){var e=this;this.handleChange=function(t){var n=e.props;"value"in n||e.setState({value:t});var r=t[0]?new Date(t[0].getTime()):null,o=t[1]?new Date(t[1].getTime()):null,a=t[0]?n.getFormatter().format(t[0]):"",i=t[1]?n.getFormatter().format(t[1]):"";n.onChange([r,o],[a,i])}},u);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){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(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 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):o(e,t))}function l(e){var t,n,r;return n=t=function(t){function n(e){a(this,n);var o=i(this,t.call(this,e));return r.call(o),o.state={value:o.props.parseDateFromValue(o.props.value||o.props.defaultValue)},o}return s(n,t),n.prototype.componentWillReceiveProps=function(e){"value"in e&&this.setState({value:e.parseDateFromValue(e.value)})},n.prototype.render=function(){var t=this.props,n=t.locale,r=new m["default"](n);r.setTime(Date.now());var o="placeholder"in t?t.placeholder:n.lang.placeholder,a=t.showTime?t.disabledTime:null,i=(0,b["default"])({"ant-calendar-time":t.showTime,"ant-calendar-month":d["default"]===e}),s=p["default"].createElement(e,{formatter:t.getFormatter(),disabledDate:t.disabledDate,disabledTime:a,locale:n.lang,timePicker:t.timePicker,defaultValue:r,dateInputPlaceholder:o,prefixCls:"ant-calendar",className:i}),l={};return t.showTime&&(l.width=180),p["default"].createElement("span",{className:t.pickerClass,style:u({},l,t.style)},p["default"].createElement(y["default"],{transitionName:t.transitionName,disabled:t.disabled,calendar:s,value:this.state.value,prefixCls:"ant-calendar-picker-container",style:t.popupStyle,align:t.align,getCalendarContainer:t.getCalendarContainer,onOpen:t.toggleOpen,onClose:t.toggleOpen,onChange:this.handleChange},function(e){var n=e.value;return p["default"].createElement("span",null,p["default"].createElement("input",{disabled:t.disabled,onChange:t.handleInputChange,value:n?t.getFormatter().format(n):"",placeholder:o,className:t.pickerInputClass}),p["default"].createElement("span",{className:"ant-calendar-picker-icon"}))}))},n}(p["default"].Component),r=function(){var e=this;this.handleChange=function(t){var n=e.props;"value"in n||e.setState({value:t});var r=t?new Date(t.getTime()):null;n.onChange(r,t?n.getFormatter().format(t):"")}},n}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};t["default"]=l;var c=n(1),p=r(c),f=n(83),d=r(f),h=n(84),y=r(h),v=n(10),m=r(v),g=n(2),b=r(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(90),a=r(o),i=n(83),s=r(i),l=n(174),u=r(l),c=n(177),p=r(c),f=n(173),d=r(f),h=n(172),y=r(h),v=(0,p["default"])((0,u["default"])(a["default"])),m=(0,p["default"])((0,u["default"])(s["default"]),"yyyy-MM");v.Calendar=y["default"],v.RangePicker=(0,p["default"])(d["default"],"yyyy-MM-dd"),v.MonthPicker=m,t["default"]=v,e.exports=t["default"]},function(e,t,n){"use strict";n(3),n(429),n(13),n(69)},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],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(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 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):o(e,t))}function l(e,t){var n,r;return r=n=function(t){function n(e){a(this,n);var r=i(this,t.call(this,e));return r.getFormatter=function(){var e=r.props.format,t=new y["default"](e,r.getLocale().lang.format);return t},r.parseDateFromValue=function(e){if(e){if("string"==typeof e)return r.getFormatter().parse(e,{locale:r.getLocale()});if(e instanceof Date){var t=new m["default"](r.getLocale());return t.setTime(+e),t}}return e},r.toggleOpen=function(e){r.setState({open:e.open}),r.props.toggleOpen(e)},r.state={},r}return s(n,t),n.prototype.handleInputChange=function(){},n.prototype.getLocale=function(){var e=this.props,t=O["default"],n=this.context;n.antLocale&&n.antLocale.DatePicker&&(t=n.antLocale.DatePicker);var r=u({},t,e.locale);return r.lang=u({},t.lang,e.locale.lang),r},n.prototype.render=function(){var t=this.props,n=this.state,r=(0,b["default"])({"ant-calendar-picker":!0,"ant-calendar-picker-open":n.open}),o=(0,b["default"])({"ant-calendar-range-picker":!0,"ant-input":!0,"ant-input-lg":"large"===t.size,"ant-input-sm":"small"===t.size}),a=this.getLocale(),i=t.showTime&&t.showTime.format,s={formatter:new y["default"](i||"HH:mm:ss",a.timePickerLocale.format),showSecond:i&&i.indexOf("ss")>=0,showHour:i&&i.indexOf("HH")>=0},l=t.showTime?p["default"].createElement(d["default"],u({},s,t.showTime,{prefixCls:"ant-time-picker",placeholder:a.timePickerLocale.placeholder,locale:a.timePickerLocale,transitionName:"slide-up"})):null;return p["default"].createElement(e,u({},this.props,{pickerClass:r,pickerInputClass:o,locale:a,timePicker:l,toggleOpen:this.toggleOpen,handleInputChange:this.handleInputChange,getFormatter:this.getFormatter,parseDateFromValue:this.parseDateFromValue}))},n}(p["default"].Component),n.defaultProps={format:t||"yyyy-MM-dd",transitionName:"slide-up",popupStyle:{},onChange:function(){},onOk:function(){},toggleOpen:function(){},locale:{},align:{offset:[0,-9]},open:!1},n.contextTypes={antLocale:c.PropTypes.object},r}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};t["default"]=l;var c=n(1),p=r(c),f=n(367),d=r(f),h=n(27),y=r(h),v=n(10),m=r(v),g=n(2),b=r(g),P=n(52),O=r(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){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return 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 i(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}),t["default"]=void 0;var u,c,p=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},f=n(1),d=r(f),h=n(15),y=r(h),v=n(7),m=r(v),g=n(53),b=r(g),P=n(2),O=r(P),C=y["default"].Group,T=(c=u=function(e){function t(){return i(this,t),s(this,e.apply(this,arguments))}return l(t,e),t.prototype.render=function(){var e=this.props,t=e.type,n=e.overlay,r=e.trigger,o=e.align,i=e.children,s=e.className,l=e.onClick,u=a(e,["type","overlay","trigger","align","children","className","onClick"]),c=(0,O["default"])({"ant-dropdown-button":!0,className:!!s});return d["default"].createElement(C,p({},u,{className:c}),d["default"].createElement(y["default"],{type:t,onClick:l},i),d["default"].createElement(b["default"],{align:o,overlay:n,trigger:r},d["default"].createElement(y["default"],{type:t},d["default"].createElement(m["default"],{type:"down"}))))},t}(d["default"].Component),u.defaultProps={align:{points:["tr","br"],overlay:{adjustX:1,adjustY:1},offset:[0,4],targetOffset:[0,0]},type:"default"},c);t["default"]=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){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(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){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}),t["default"]=void 0;var u,c,p=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},f=n(1),d=r(f),h=n(2),y=r(h),v=n(16),m=r(v),g=(c=u=function(e){function t(){return i(this,t),s(this,e.apply(this,arguments))}return l(t,e),t.prototype.shouldComponentUpdate=function(){for(var e=arguments.length,t=Array(e),n=0;e>n;n++)t[n]=arguments[n];return m["default"].shouldComponentUpdate.apply(this,t)},t.prototype.getChildContext=function(){return{form:this.props.form}},t.prototype.render=function(){var e,t=this.props,n=t.prefixCls,r=t.className,o=t.style,i=(0,y["default"])((e={},a(e,n+"-horizontal",this.props.horizontal),a(e,n+"-inline",this.props.inline),a(e,r,!!r),e));return d["default"].createElement("form",p({},this.props,{className:i,style:o}),this.props.children)},t}(d["default"].Component),u.defaultProps={prefixCls:"ant-form",onSubmit:function(e){e.preventDefault()}},u.propTypes={prefixCls:d["default"].PropTypes.string,horizontal:d["default"].PropTypes.bool,inline:d["default"].PropTypes.bool,form:d["default"].PropTypes.object,children:d["default"].PropTypes.any,onSubmit:d["default"].PropTypes.func},u.childContextTypes={form:d["default"].PropTypes.object},c);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){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(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){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}),t["default"]=void 0;var u,c,p=n(1),f=r(p),d=n(2),h=r(d),y=n(16),v=r(y),m=(c=u=function(e){function t(){return i(this,t),s(this,e.apply(this,arguments))}return l(t,e),t.prototype.shouldComponentUpdate=function(){for(var e=arguments.length,t=Array(e),n=0;e>n;n++)t[n]=arguments[n];return v["default"].shouldComponentUpdate.apply(this,t)},t.prototype.getLayoutClass=function(e){if(!e)return"";var t=e.span,n=e.offset,r=t?"ant-col-"+t:"",o=n?" ant-col-offset-"+n:"";return r+o},t.prototype.getHelpMsg=function(){var e=this.context,t=this.props;return void 0===t.help&&e.form?this.getId()?(e.form.getFieldError(this.getId())||[]).join(", "):"":t.help},t.prototype.getOnlyControl=function(){var e=f["default"].Children.toArray(this.props.children),t=e.filter(function(e){return e.props&&"__meta"in e.props})[0];return void 0!==t?t:null},t.prototype.getChildProp=function(e){var t=this.getOnlyControl();return t&&t.props&&t.props[e]},t.prototype.getId=function(){return this.getChildProp("id")},t.prototype.getMeta=function(){return this.getChildProp("__meta")},t.prototype.renderHelp=function(){var e=this.props.prefixCls,t=this.getHelpMsg();return t?f["default"].createElement("div",{className:e+"-explain",key:"help"},t):null},t.prototype.renderExtra=function(){var e=this.props,t=e.prefixCls,n=e.extra;return n?f["default"].createElement("span",{className:t+"-extra"},n):null},t.prototype.getValidateStatus=function(){var e=this.context.form,t=e.isFieldValidating,n=e.getFieldError,r=e.getFieldValue,o=this.getId();return o?t(o)?"validating":n(o)?"error":void 0!==r(o)?"success":"":""},t.prototype.renderValidateWrapper=function(e,t,n){var r="",o=this.context.form,a=this.props,i=void 0===a.validateStatus&&o?this.getValidateStatus():a.validateStatus;return i&&(r=(0,h["default"])({"has-feedback":a.hasFeedback,"has-success":"success"===i,"has-warning":"warning"===i,"has-error":"error"===i,"is-validating":"validating"===i})),f["default"].createElement("div",{className:this.props.prefixCls+"-item-control "+r},e,t,n)},t.prototype.renderWrapper=function(e){var t=this.props.wrapperCol;return f["default"].createElement("div",{className:this.getLayoutClass(t),key:"wrapper"},e)},t.prototype.isRequired=function(){if(this.context.form){var e=this.getMeta()||{},t=e.validate||[];return t.filter(function(e){return!!e.rules}).some(function(e){return e.rules.some(function(e){return e.required})})}return!1},t.prototype.renderLabel=function(){var e,t=this.props,n=t.labelCol,r=void 0===t.required?this.isRequired():t.required,o=(0,h["default"])((e={},a(e,this.getLayoutClass(n),!0),a(e,t.prefixCls+"-item-required",r),e)),i=t.label;return"string"==typeof t.label&&(i=t.label.replace(/\uff1a|:$/,"")),t.label?f["default"].createElement("label",{htmlFor:t.id||this.getId(),className:o,key:"label"},i):null},t.prototype.renderChildren=function(){var e=this.props,t=f["default"].Children.map(e.children,function(e){return e&&"function"==typeof e.type&&!e.props.size?f["default"].cloneElement(e,{size:"large"}):e});return[this.renderLabel(),this.renderWrapper(this.renderValidateWrapper(t,this.renderHelp(),this.renderExtra()))]},t.prototype.renderFormItem=function(e){var t,n=this.props,r=n.prefixCls,o=n.style,i=(t={},a(t,r+"-item",!0),a(t,r+"-item-with-help",!!this.getHelpMsg()),a(t,""+n.className,!!n.className),t);return f["default"].createElement("div",{className:(0,h["default"])(i),style:o},e)},t.prototype.render=function(){var e=this.renderChildren();return this.renderFormItem(e)},t}(f["default"].Component),u.defaultProps={hasFeedback:!1,prefixCls:"ant-form"},u.propTypes={prefixCls:f["default"].PropTypes.string,label:f["default"].PropTypes.node,labelCol:f["default"].PropTypes.object,help:f["default"].PropTypes.oneOfType([f["default"].PropTypes.node,f["default"].PropTypes.bool]),validateStatus:f["default"].PropTypes.oneOf(["","success","warning","error","validating"]),hasFeedback:f["default"].PropTypes.bool,wrapperCol:f["default"].PropTypes.object,className:f["default"].PropTypes.string,id:f["default"].PropTypes.string,children:f["default"].PropTypes.node},u.contextTypes={form:f["default"].PropTypes.object},c);t["default"]=m,e.exports=t["default"]},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=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},r={setValue:function(e,t){var r=t,o=t&&t.target;o&&(r="input"===(""+o.nodeName).toLowerCase()&&"checkbox"===o.type?o.checked:t.target.value);var a={};a[e]=r,this.setState({formData:n({},this.state.formData,a)})}};t["default"]=r,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},a=n(179),i=r(a),s=n(180),l=r(s),u=n(181),c=r(u),p=n(311),f=r(p);i["default"].create=function(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=o({},e,{fieldNameProp:"id",fieldMetaProp:"__meta"});return(0,f["default"])(t)},i["default"].Item=l["default"],i["default"].ValueMixin=c["default"],t["default"]=i["default"],e.exports=t["default"]},function(e,t,n){"use strict";n(3),n(431),n(57)},function(e,t,n){"use strict";n(3)},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],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(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 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}),t["default"]=void 0;var c,p,f=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),h=r(d),y=n(2),v=r(y),m=n(314),g=r(m),b=(p=c=function(e){function t(){return s(this,t),l(this,e.apply(this,arguments))}return u(t,e),t.prototype.render=function(){var e,t=this.props,n=t.className,r=t.size,o=i(t,["className","size"]),s=(0,v["default"])((e={},a(e,this.props.prefixCls+"-lg","large"===r), a(e,this.props.prefixCls+"-sm","small"===r),a(e,n,!!n),e));return h["default"].createElement(g["default"],f({className:s},o))},t}(h["default"].Component),c.defaultProps={prefixCls:"ant-input-number",step:1},p);t["default"]=b,e.exports=t["default"]},[459,432],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 a(e){var t=(0,u["default"])(o({"ant-input-group":!0,"ant-input-group-lg":"large"===e.size,"ant-input-group-sm":"small"===e.size},e.className,!!e.className));return s["default"].createElement("span",{className:t,style:e.style},e.children)}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=a;var i=n(1),s=r(i),l=n(2),u=r(l);a.propTypes={children:s["default"].PropTypes.any},e.exports=t["default"]},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],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(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){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))}function u(e){return"undefined"==typeof e||null===e?"":e}function c(e){return window.requestAnimationFrame?window.requestAnimationFrame(e):window.setTimeout(e,1)}function p(e){window.cancelAnimationFrame?window.cancelAnimationFrame(e):window.clearTimeout(e)}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var f,d,h=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},y=n(1),v=r(y),m=n(2),g=r(m),b=n(189),P=r(b),O=(d=f=function(e){function t(n){i(this,t);var r=s(this,e.call(this,n));return r.handleKeyDown=function(e){13===e.keyCode&&r.props.onPressEnter(e),r.props.onKeyDown(e)},r.handleTextareaChange=function(e){r.resizeTextarea(),r.props.onChange&&r.props.onChange(e)},r.resizeTextarea=function(){var e=r.props,t=e.type,n=e.autosize;if("textarea"===t&&n&&r.refs.input){var o=n?n.minRows:null,a=n?n.maxRows:null,i=(0,P["default"])(r.refs.input,!1,o,a);r.setState({textareaStyles:i})}},r.state={textareaStyles:null},r}return l(t,e),t.prototype.componentDidMount=function(){this.resizeTextarea()},t.prototype.componentWillReceiveProps=function(e){this.props.value!==e.value&&(this.nextFrameActionId&&p(this.nextFrameActionId),this.nextFrameActionId=c(this.resizeTextarea))},t.prototype.renderLabledInput=function(e){var t,n=this.props,r=n.prefixCls+"-group",o=r+"-addon",i=n.addonBefore?v["default"].createElement("span",{className:o},n.addonBefore):null,s=n.addonAfter?v["default"].createElement("span",{className:o},n.addonAfter):null,l=(0,g["default"])((t={},a(t,n.prefixCls+"-wrapper",!0),a(t,r,i||s),t));return v["default"].createElement("span",{className:l},i,e,s)},t.prototype.renderInput=function(){var e,t=h({},this.props),n=t.prefixCls;if(!t.type)return t.children;var r=(0,g["default"])((e={},a(e,n,!0),a(e,n+"-sm","small"===t.size),a(e,n+"-lg","large"===t.size),a(e,t.className,!!t.className),e));switch("value"in t&&(t.value=u(t.value),delete t.defaultValue),t.type){case"textarea":return v["default"].createElement("textarea",h({},t,{style:h({},t.style,this.state.textareaStyles),className:r,onKeyDown:this.handleKeyDown,onChange:this.handleTextareaChange,ref:"input"}));default:return v["default"].createElement("input",h({},t,{className:r,onKeyDown:this.handleKeyDown,ref:"input"}))}},t.prototype.render=function(){return this.renderLabledInput(this.renderInput())},t}(y.Component),f.defaultProps={defaultValue:"",disabled:!1,prefixCls:"ant-input",type:"text",onPressEnter:function(){},onKeyDown:function(){},autosize:!1},f.propTypes={type:y.PropTypes.string,id:y.PropTypes.oneOfType([y.PropTypes.string,y.PropTypes.number]),size:y.PropTypes.oneOf(["small","default","large"]),disabled:y.PropTypes.bool,value:y.PropTypes.any,defaultValue:y.PropTypes.any,className:y.PropTypes.string,addonBefore:y.PropTypes.node,addonAfter:y.PropTypes.node,prefixCls:y.PropTypes.string,autosize:y.PropTypes.oneOfType([y.PropTypes.bool,y.PropTypes.object]),onPressEnter:y.PropTypes.func,onKeyDown:y.PropTypes.func},d);t["default"]=O,e.exports=t["default"]},function(e,t){"use strict";function n(e){var t=arguments.length<=1||void 0===arguments[1]?!1:arguments[1],n=e.getAttribute("id")||e.getAttribute("data-reactid")||e.getAttribute("name");if(t&&i[n])return i[n];var r=window.getComputedStyle(e),o=r.getPropertyValue("box-sizing")||r.getPropertyValue("-moz-box-sizing")||r.getPropertyValue("-webkit-box-sizing"),s=parseFloat(r.getPropertyValue("padding-bottom"))+parseFloat(r.getPropertyValue("padding-top")),l=parseFloat(r.getPropertyValue("border-bottom-width"))+parseFloat(r.getPropertyValue("border-top-width")),u=a.map(function(e){return e+":"+r.getPropertyValue(e)}).join(";"),c={sizingStyle:u,paddingSize:s,borderSize:l,boxSizing:o};return t&&n&&(i[n]=c),c}function r(e){var t=arguments.length<=1||void 0===arguments[1]?!1:arguments[1],r=arguments.length<=2||void 0===arguments[2]?null:arguments[2],a=arguments.length<=3||void 0===arguments[3]?null:arguments[3];s||(s=document.createElement("textarea"),document.body.appendChild(s));var i=n(e,t),l=i.paddingSize,u=i.borderSize,c=i.boxSizing,p=i.sizingStyle;s.setAttribute("style",p+";"+o),s.value=e.value||e.placeholder||"";var f=-(1/0),d=1/0,h=s.scrollHeight;if("border-box"===c?h+=u:"content-box"===c&&(h-=l),null!==r||null!==a){s.value="";var y=s.scrollHeight-l;null!==r&&(f=y*r,"border-box"===c&&(f=f+l+u),h=Math.max(f,h)),null!==a&&(d=y*a,"border-box"===c&&(d=d+l+u),h=Math.min(d,h))}return{height:h,minHeight:f,maxHeight:d}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=r;var o="\n min-height:0 !important;\n max-height:none !important;\n height:0 !important;\n visibility:hidden !important;\n overflow:hidden !important;\n position:absolute !important;\n z-index:-1000 !important;\n top:0 !important;\n right:0 !important\n",a=["letter-spacing","line-height","padding-top","padding-bottom","font-family","font-weight","font-size","text-rendering","text-transform","width","text-indent","padding-left","padding-right","border-width","box-sizing"],i={},s=void 0;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 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 i(e){var t,n=e.span,r=e.order,i=e.offset,u=e.push,p=e.pull,d=e.className,h=e.children,y=a(e,["span","order","offset","push","pull","className","children"]),v={};["xs","sm","md","lg"].forEach(function(t){var n,r={};"number"==typeof e[t]?r.span=e[t]:"object"===l(e[t])&&(r=e[t]||{}),v=s({},v,(n={},o(n,"ant-col-"+t+"-"+r.span,void 0!==r.span),o(n,"ant-col-"+t+"-order-"+r.order,r.order),o(n,"ant-col-"+t+"-offset-"+r.offset,r.offset),o(n,"ant-col-"+t+"-push-"+r.push,r.push),o(n,"ant-col-"+t+"-pull-"+r.pull,r.pull),n))});var m=(0,f["default"])(s((t={},o(t,"ant-col-"+n,void 0!==n),o(t,"ant-col-order-"+r,r),o(t,"ant-col-offset-"+i,i),o(t,"ant-col-push-"+u,u),o(t,"ant-col-pull-"+p,p),o(t,d,!!d),t),v));return c["default"].createElement("div",s({},y,{className:m}),h)}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},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};t["default"]=i;var u=n(1),c=r(u),p=n(2),f=r(p),d=u.PropTypes.oneOfType([u.PropTypes.string,u.PropTypes.number]),h=u.PropTypes.oneOfType([u.PropTypes.object,u.PropTypes.number]);i.propTypes={span:d,order:d,offset:d,push:d,pull:d,className:u.PropTypes.string,children:u.PropTypes.node,xs:h,sm:h,md:h,lg:h},e.exports=t["default"]},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],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(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 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}),t["default"]=void 0;var c,p,f=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),h=r(d),y=n(2),v=r(y),m=(p=c=function(e){function t(){return s(this,t),l(this,e.apply(this,arguments))}return u(t,e),t.prototype.render=function(){var e,t=this.props,n=t.type,r=t.justify,o=t.align,s=t.className,l=t.gutter,u=t.style,c=t.children,p=i(t,["type","justify","align","className","gutter","style","children"]),y=(0,v["default"])((e={"ant-row":!n},a(e,"ant-row-"+n,n),a(e,"ant-row-"+n+"-"+r,r),a(e,"ant-row-"+n+"-"+o,o),a(e,s,s),e)),m=l>0?f({marginLeft:l/-2,marginRight:l/-2},u):u,g=d.Children.map(c,function(e){return e?(0,d.cloneElement)(e,{style:l>0?f({paddingLeft:l/2,paddingRight:l/2},e.props.style):e.props.style}):null});return h["default"].createElement("div",f({},p,{className:y,style:m}),g)},t}(h["default"].Component),c.defaultProps={gutter:0},c.propTypes={type:h["default"].PropTypes.string,align:h["default"].PropTypes.string,justify:h["default"].PropTypes.string,className:h["default"].PropTypes.string,children:h["default"].PropTypes.node,gutter:h["default"].PropTypes.number},p);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){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(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 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):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var l,u,c=n(1),p=r(c),f=n(59),d=(u=l=function(e){function t(){return a(this,t),i(this,e.apply(this,arguments))}return s(t,e),t.prototype.getChildContext=function(){return{antLocale:this.props.locale}},t.prototype.componentDidMount=function(){this.componentDidUpdate()},t.prototype.componentDidUpdate=function(){var e=this.props.locale;(0,f.changeConfirmLocale)(e&&e.Modal)},t.prototype.componentWillUnMount=function(){(0,f.changeConfirmLocale)()},t.prototype.render=function(){return p["default"].Children.only(this.props.children)},t}(p["default"].Component),l.propTypes={locale:p["default"].PropTypes.object},l.childContextTypes={antLocale:p["default"].PropTypes.object},u);t["default"]=d,e.exports=t["default"]},function(e,t){"use strict"},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],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(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 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):o(e,t))}function l(){}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var u,c,p=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},f=n(1),d=r(f),h=n(21),y=r(h),v=n(49),m=r(v),g=(c=u=function(e){function t(n){a(this,t);var r=i(this,e.call(this,n));return r.handleClick=function(e){r.setOpenKeys([]),r.props.onClick(e)},r.handleOpenKeys=function(e){var t=e.openKeys;r.setOpenKeys(t),r.props.onOpen(e)},r.handleCloseKeys=function(e){var t=e.openKeys;r.setOpenKeys(t),r.props.onClose(e)},r.state={openKeys:[]},r}return s(t,e),t.prototype.componentWillReceiveProps=function(e){"inline"===this.props.mode&&"inline"!==e.mode&&(this.switchModeFromInline=!0),"openKeys"in e&&this.setOpenKeys(e.openKeys)},t.prototype.setOpenKeys=function(e){"openKeys"in this.props||this.setState({openKeys:e})},t.prototype.render=function(){var e=this.props.openAnimation||this.props.openTransitionName;if(!e)switch(this.props.mode){case"horizontal":e="slide-up";break;case"vertical":this.switchModeFromInline?(e="",this.switchModeFromInline=!1):e="zoom-big";break;case"inline":e=m["default"]}var t={},n=this.props.className+" "+this.props.prefixCls+"-"+this.props.theme;return t="inline"!==this.props.mode?{openKeys:this.state.openKeys,onClick:this.handleClick,onOpen:this.handleOpenKeys,onClose:this.handleCloseKeys,openTransitionName:e,className:n}:{openAnimation:e,className:n},d["default"].createElement(y["default"],p({},this.props,t))},t}(d["default"].Component),u.Divider=h.Divider,u.Item=h.Item,u.SubMenu=h.SubMenu,u.ItemGroup=h.ItemGroup,u.defaultProps={prefixCls:"ant-menu",onClick:l,onOpen:l,onClose:l,className:"",theme:"light"},c);t["default"]=g,e.exports=t["default"]},[459,434],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){return h=h||u["default"].newInstance({prefixCls:v,transitionName:"move-up",style:{top:d}})}function a(e){var t=arguments.length<=1||void 0===arguments[1]?f:arguments[1],n=arguments[2],r=arguments[3],a={info:"info-circle",success:"check-circle",error:"cross-circle",warning:"exclamation-circle",loading:"loading"}[n],i=o();return i.notice({key:y,duration:t,style:{},content:s["default"].createElement("div",{className:v+"-custom-content "+v+"-"+n},s["default"].createElement(p["default"],{type:a}),s["default"].createElement("span",null,e)),onClose:r}),function(){var e=y++;return function(){i.removeNotice(e)}}()}Object.defineProperty(t,"__esModule",{value:!0});var i=n(1),s=r(i),l=n(99),u=r(l),c=n(7),p=r(c),f=1.5,d=void 0,h=void 0,y=1,v="ant-message";t["default"]={info:function(e,t,n){return a(e,t,"info",n)},success:function(e,t,n){return a(e,t,"success",n)},error:function(e,t,n){return a(e,t,"error",n)},warn:function(e,t,n){return a(e,t,"warning",n)},warning:function(e,t,n){return a(e,t,"warning",n)},loading:function(e,t,n){return a(e,t,"loading",n)},config:function(e){"top"in e&&(d=e.top),"duration"in e&&(f=e.duration),"prefixCls"in e&&(v=e.prefixCls)},destroy:function(){h&&(h.destroy(),h=null)}},e.exports=t["default"]},[459,435],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 a(e){function t(){p.setState({visible:!1}),c["default"].unmountComponentAtNode(u),u.parentNode.removeChild(u)}function n(){var e=s.onCancel;if(e){var n=void 0;e.length?n=e(t):(n=e(),n||t()),n&&n.then&&n.then(t)}else t()}function r(){var e=s.onOk;if(e){var n=void 0;e.length?n=e(t):(n=e(),n||t()),n&&n.then&&n.then(t)}else t()}var a,s=i({},e),u=document.createElement("div");document.body.appendChild(u);var p=void 0;s.iconType=s.iconType||"question-circle";var d=s.width||416,y=s.style||{};"okCancel"in s||(s.okCancel=!0);var m=(0,b.getConfirmLocale)();s.okText=s.okText||(s.okCancel?m.okText:m.justOkText),s.cancelText=s.cancelText||m.cancelText;var P=l["default"].createElement("div",{className:"ant-confirm-body"},l["default"].createElement(h["default"],{type:s.iconType}),l["default"].createElement("span",{className:"ant-confirm-title"},s.title),l["default"].createElement("div",{className:"ant-confirm-content"},s.content)),O=null;O=s.okCancel?l["default"].createElement("div",{className:"ant-confirm-btns"},l["default"].createElement(v["default"],{type:"ghost",size:"large",onClick:n},s.cancelText),l["default"].createElement(v["default"],{type:"primary",size:"large",onClick:r},s.okText)):l["default"].createElement("div",{className:"ant-confirm-btns"},l["default"].createElement(v["default"],{type:"primary",size:"large",onClick:r},s.okText));var C=(0,g["default"])((a={"ant-confirm":!0},o(a,"ant-confirm-"+s.type,!0),o(a,s.className,!!s.className),a));c["default"].render(l["default"].createElement(f["default"],{className:C,visible:!0,closable:!1,title:"",transitionName:"zoom",footer:"",maskTransitionName:"fade",style:y,width:d},l["default"].createElement("div",{style:{zoom:1,overflow:"hidden"}},P," ",O)),u,function(){p=this})}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["default"]=a;var s=n(1),l=r(s),u=n(4),c=r(u),p=n(58),f=r(p),d=n(7),h=r(d),y=n(15),v=r(y),m=n(2),g=r(m),b=n(59);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},a=n(58),i=r(a),s=n(198),l=r(s);i["default"].info=function(e){var t=o({type:"info",iconType:"info-circle",okCancel:!1},e);return(0,l["default"])(t)},i["default"].success=function(e){var t=o({type:"success",iconType:"check-circle",okCancel:!1},e);return(0,l["default"])(t)},i["default"].error=function(e){var t=o({type:"error",iconType:"cross-circle",okCancel:!1},e);return(0,l["default"])(t)},i["default"].warning=i["default"].warn=function(e){var t=o({type:"warning",iconType:"exclamation-circle",okCancel:!1},e);return(0,l["default"])(t)},i["default"].confirm=function(e){var t=o({type:"confirm",okCancel:!0},e);return(0,l["default"])(t)},t["default"]=i["default"],e.exports=t["default"]},[461,436],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){return h?h:h=c["default"].newInstance({prefixCls:"ant-notification",style:{top:d,right:0}})}function a(e){var t=e.prefixCls||"ant-notification-notice",n=void 0;n=void 0===e.duration?y:e.duration;var r="";switch(e.icon){case"success":r="check-circle-o";break;case"info":r="info-circle-o";break;case"error":r="cross-circle-o";break;case"warning":r="exclamation-circle-o";break;default:r="info-circle"}o().notice({content:l["default"].createElement("div",{className:t+"-content "+(e.icon?t+"-with-icon":"")},e.icon?l["default"].createElement(f["default"],{className:t+"-icon "+t+"-icon-"+e.icon,type:r}):null,l["default"].createElement("div",{className:t+"-message"},e.message),l["default"].createElement("div",{className:t+"-description"},e.description),e.btn?l["default"].createElement("span",{className:t+"-btn"},e.btn):null),duration:n,closable:!0,onClose:e.onClose,key:e.key,style:{}})}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},s=n(1),l=r(s),u=n(99),c=r(u),p=n(7),f=r(p),d=24,h=void 0,y=4.5,v={open:function(e){a(e)},close:function(e){h&&h.removeNotice(e)},config:function(e){"top"in e&&(d=e.top),"duration"in e&&(y=e.duration)},destroy:function(){h&&(h.destroy(),h=null)}};["success","info","warning","error"].forEach(function(e){v[e]=function(t){return v.open(i({},t,{icon:e}))}}),v.warn=v.warning,t["default"]=v,e.exports=t["default"]},[459,437],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],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(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 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):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var l,u,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(25),h=r(d),y=(u=l=function(e){function t(){return a(this,t),i(this,e.apply(this,arguments))}return s(t,e),t.prototype.render=function(){return f["default"].createElement(h["default"],c({size:"small"},this.props))},t}(f["default"].Component),l.Option=h["default"].Option,u);t["default"]=y,e.exports=t["default"]},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],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(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 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):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var l,u,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(328),h=r(d),y=n(25),v=r(y),m=n(203),g=r(m),b=n(205),P=r(b),O=(u=l=function(e){function t(){return a(this,t),i(this,e.apply(this,arguments))}return s(t,e),t.prototype.render=function(){var e=this.props.className,t=v["default"],n=void 0;return n=this.context.antLocale&&this.context.antLocale.Pagination?this.context.antLocale.Pagination:this.props.locale,"small"===this.props.size&&(e+=" mini",t=g["default"]),f["default"].createElement(h["default"],c({selectComponentClass:t,selectPrefixCls:"ant-select"},this.props,{locale:n,className:e}))},t}(f["default"].Component),l.defaultProps={locale:P["default"],className:"",prefixCls:"ant-pagination"},l.contextTypes={antLocale:f["default"].PropTypes.object},u);t["default"]=O,e.exports=t["default"]},function(e,t,n){"use strict";e.exports=n(101)},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],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return 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 i(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}),t["default"]=void 0;var u,c,p=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},f=n(1),d=r(f),h=n(35),y=r(h),v=n(7),m=r(v),g=n(15),b=r(g),P=n(32),O=r(P),C=(0,O["default"])(),T="ant-popover",w=function(){},x=(c=u=function(e){function t(n){i(this,t);var r=s(this,e.call(this,n));return r.confirm=function(){r.setVisible(!1),r.props.onConfirm.call(r)},r.cancel=function(){r.setVisible(!1),r.props.onCancel.call(r)},r.onVisibleChange=function(e){r.setVisible(e)},r.state={visible:!1},r}return l(t,e),t.prototype.componentWillReceiveProps=function(e){"visible"in e&&this.setState({visible:e.visible})},t.prototype.setVisible=function(e){"visible"in this.props||this.setState({visible:e}),this.props.onVisibleChange(e)},t.prototype.render=function(){var e=this.props,t=e.title,n=e.placement,r=e.overlayStyle,o=e.trigger,i=a(e,["title","placement","overlayStyle","trigger"]),s=this.props,l=s.okText,u=s.cancelText;this.context.antLocale&&this.context.antLocale.Popconfirm&&(l=l||this.context.antLocale.Popconfirm.okText,u=u||this.context.antLocale.Popconfirm.cancelText);var c=d["default"].createElement("div",null,d["default"].createElement("div",{className:T+"-inner-content"},d["default"].createElement("div",{className:T+"-message"},d["default"].createElement(m["default"],{type:"exclamation-circle"}),d["default"].createElement("div",{className:T+"-message-title"},t)),d["default"].createElement("div",{className:T+"-buttons"},d["default"].createElement(b["default"],{onClick:this.cancel,type:"ghost",size:"small"},u||"\u53d6\u6d88"),d["default"].createElement(b["default"],{onClick:this.confirm,type:"primary",size:"small"},l||"\u786e\u5b9a"))));return d["default"].createElement(y["default"],p({},i,{placement:n,builtinPlacements:C,overlayStyle:r,prefixCls:T,onVisibleChange:this.onVisibleChange,transitionName:this.props.transitionName,visible:this.state.visible,trigger:o,overlay:c}),this.props.children)},t}(d["default"].Component),u.defaultProps={transitionName:"zoom-big",placement:"top",trigger:"click",overlayStyle:{},onConfirm:w,onCancel:w,onVisibleChange:w},u.contextTypes={antLocale:d["default"].PropTypes.object},c);t["default"]=x,e.exports=t["default"]},function(e,t,n){"use strict";n(3),n(62)},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],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(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 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):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var l,u,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(35),h=r(d),y=n(32),v=r(y),m=n(17),g=r(m),b=(0,v["default"])(),P=(u=l=function(e){function t(){return a(this,t),i(this,e.apply(this,arguments))}return s(t,e),t.prototype.render=function(){return f["default"].createElement(h["default"],c({transitionName:this.props.transitionName,builtinPlacements:b,ref:"tooltip"},this.props,{overlay:this.getOverlay()}),this.props.children)},t.prototype.getPopupDomNode=function(){return this.refs.tooltip.getPopupDomNode()},t.prototype.componentDidMount=function(){"overlay"in this.props&&(0,g["default"])(!1,"`overlay` prop of Popover is deprecated, use `content` instead.")},t.prototype.getOverlay=function(){var e=this.props,t=e.title,n=e.prefixCls,r=e.overlay,o=e.content;return f["default"].createElement("div",null,t&&f["default"].createElement("div",{className:n+"-title"},t),f["default"].createElement("div",{className:n+"-inner-content"},o||r))},t}(f["default"].Component),l.defaultProps={prefixCls:"ant-popover",placement:"top",transitionName:"zoom-big",trigger:"hover",mouseEnterDelay:.1,mouseLeaveDelay:.1,overlayStyle:{}},u);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){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(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 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}),t["default"]=void 0;var c,p,f=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),h=r(d),y=n(7),v=r(y),m=n(330),g=n(2),b=r(g),P={normal:"#2db7f5",exception:"#ff5500",success:"#87d068" },O=(p=c=function(e){function t(){return s(this,t),l(this,e.apply(this,arguments))}return u(t,e),t.prototype.render=function(){var e,t=this.props,n=t.prefixCls,r=t.status,o=t.format,s=t.percent,l=t.trailColor,u=t.type,c=t.strokeWidth,p=t.width,d=t.className,y=t.showInfo,g=i(t,["prefixCls","status","format","percent","trailColor","type","strokeWidth","width","className","showInfo"]),O=parseInt(s,10)>=100&&!("status"in this.props)?"success":r||"normal",C=void 0,T=void 0,w=o||function(e){return e+"%"};if(y){var x=void 0,E="circle"===u?"":"-circle";x="exception"===O?o?w(s):h["default"].createElement(v["default"],{type:"cross"+E}):"success"===O?o?w(s):h["default"].createElement(v["default"],{type:"check"+E}):w(s),C=h["default"].createElement("span",{className:n+"-text"},x)}if("line"===u){var S={width:s+"%",height:c||10};T=h["default"].createElement("div",null,h["default"].createElement("div",{className:n+"-outer"},h["default"].createElement("div",{className:n+"-inner"},h["default"].createElement("div",{className:n+"-bg",style:S}))),C)}else if("circle"===u){var k=p||132,j={width:k,height:k,fontSize:.16*k+6};T=h["default"].createElement("div",{className:n+"-inner",style:j},h["default"].createElement(m.Circle,{percent:s,strokeWidth:c||6,strokeColor:P[O],trailColor:l}),C)}var _=(0,b["default"])((e={},a(e,""+n,!0),a(e,n+"-"+u,!0),a(e,n+"-status-"+O,!0),a(e,n+"-show-info",y),a(e,d,!!d),e));return h["default"].createElement("div",f({},g,{className:_}),T)},t}(h["default"].Component),c.defaultProps={type:"line",percent:0,showInfo:!0,trailColor:"#f3f3f3",prefixCls:"ant-progress"},c.propTypes={status:d.PropTypes.oneOf(["normal","exception","active","success"]),type:d.PropTypes.oneOf(["line","circle"]),showInfo:d.PropTypes.bool,percent:d.PropTypes.number,width:d.PropTypes.number,strokeWidth:d.PropTypes.number,trailColor:d.PropTypes.string,format:d.PropTypes.func},p);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){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(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 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):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var l=n(1),u=r(l),c=n(333),p=r(c),f=n(17),d=r(f),h=function(e){function t(){return a(this,t),i(this,e.apply(this,arguments))}return s(t,e),t.prototype.componentDidMount=function(){(0,d["default"])(!1,"`QueueAnim` is deprecated, you can import QueueAnim from 'rc-queue-anim' directly.The Demo will be moved to http://motion.ant.design/#/component/queue-anim")},t.prototype.render=function(){return u["default"].createElement(p["default"],this.props)},t}(u["default"].Component);t["default"]=h,e.exports=t["default"]},193,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],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(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){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))}function u(e){var t=null,n=!1;return h["default"].Children.forEach(e,function(e){e&&e.props&&e.props.checked&&(t=e.props.value,n=!0)}),n?{value:t}:void 0}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var c,p,f=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),h=r(d),y=n(2),v=r(y),m=n(33),g=r(m),b=n(65),P=r(b),O=n(16),C=r(O),T=(p=c=function(e){function t(n){i(this,t);var r=s(this,e.call(this,n));r.onRadioChange=function(e){"value"in r.props||r.setState({value:e.target.value}),r.props.onChange(e)};var o=void 0;if("value"in n)o=n.value;else if("defaultValue"in n)o=n.defaultValue;else{var a=u(n.children);o=a&&a.value}return r.state={value:o},r}return l(t,e),t.prototype.componentWillReceiveProps=function(e){if("value"in e)this.setState({value:e.value});else{var t=u(e.children);t&&this.setState({value:t.value})}},t.prototype.shouldComponentUpdate=function(){for(var e=arguments.length,t=Array(e),n=0;e>n;n++)t[n]=arguments[n];return C["default"].shouldComponentUpdate.apply(this,t)},t.prototype.render=function(){var e,t=this,n=this.props,r=h["default"].Children.map(n.children,function(e){if(e&&(e.type===g["default"]||e.type===P["default"])&&e.props){var n={};return"key"in e||"string"!=typeof e.props.value||(n.key=e.props.value),h["default"].cloneElement(e,f({},n,e.props,{onChange:t.onRadioChange,checked:t.state.value===e.props.value,disabled:e.props.disabled||t.props.disabled}))}return e}),o=(0,v["default"])((e={},a(e,n.prefixCls,!0),a(e,n.prefixCls+"-"+n.size,n.size),e));return h["default"].createElement("div",{className:o,style:n.style},r)},t}(h["default"].Component),c.defaultProps={prefixCls:"ant-radio-group",disabled:!1,onChange:function(){}},p);t["default"]=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){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(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 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):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var l,u,c=n(1),p=r(c),f=n(339),d=r(f),h=(u=l=function(e){function t(){return a(this,t),i(this,e.apply(this,arguments))}return s(t,e),t.prototype.render=function(){return p["default"].createElement(d["default"],this.props)},t}(p["default"].Component),l.propTypes={prefixCls:c.PropTypes.string},l.defaultProps={prefixCls:"ant-rate"},u);t["default"]=h,e.exports=t["default"]},[459,442],function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(31);t["default"]=r.Row,e.exports=t["default"]},169,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],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return 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 i(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}),t["default"]=void 0;var u,c,p=n(1),f=r(p),d=n(352),h=r(d),y=(c=u=function(e){function t(){return i(this,t),s(this,e.apply(this,arguments))}return l(t,e),t.prototype.render=function(){var e=this.props,t=e.isIncluded,n=e.marks,r=e.index,o=e.defaultIndex,i=a(e,["isIncluded","marks","index","defaultIndex"]);return void 0!==t&&(i.included=t),Array.isArray(n)?(i.min=0,i.max=n.length-1,i.step=1,void 0!==r&&(i.value=r),void 0!==o&&(i.defaultValue=o),i.marks={},n.forEach(function(e,t){i.marks[t]=e})):i.marks=n,f["default"].createElement(h["default"],i)},t}(f["default"].Component),u.defaultProps={prefixCls:"ant-slider",tipTransitionName:"zoom-down"},c);t["default"]=y,e.exports=t["default"]},function(e,t,n){"use strict";n(3),n(444),n(71)},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],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(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 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):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var l,u,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(356),h=r(d),y=(u=l=function(e){function t(){return a(this,t),i(this,e.apply(this,arguments))}return s(t,e),t.prototype.render=function(){var e=this.props.maxDescriptionWidth;return"vertical"===this.props.direction&&(e="auto"),f["default"].createElement(h["default"],c({},this.props,{maxDescriptionWidth:e}))},t}(f["default"].Component),l.Step=h["default"].Step,l.defaultProps={prefixCls:"ant-steps",iconPrefix:"ant",maxDescriptionWidth:100,current:0},u);t["default"]=y,e.exports=t["default"]},[459,446],function(e,t,n){"use strict";n(458),n(3)},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],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(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){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}),t["default"]=void 0;var u,c,p=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},f=n(358),d=r(f),h=n(1),y=r(h),v=n(2),m=r(v),g=(c=u=function(e){function t(){return i(this,t),s(this,e.apply(this,arguments))}return l(t,e),t.prototype.render=function(){var e,t=this.props,n=t.prefixCls,r=t.size,o=t.className,i=(0,m["default"])((e={},a(e,o,!!o),a(e,n+"-small","small"===r),e));return y["default"].createElement(d["default"],p({className:i},this.props))},t}(y["default"].Component),u.defaultProps={prefixCls:"ant-switch"},c);t["default"]=g,e.exports=t["default"]},[459,447],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],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(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 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):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var l,u,c="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(1),f=r(p),d=n(21),h=r(d),y=n(54),v=r(y),m=n(7),g=r(m),b=n(18),P=r(b),O=n(24),C=r(O),T=(u=l=function(e){function t(n){a(this,t);var r=i(this,e.call(this,n));return r.setSelectedKeys=function(e){var t=e.selectedKeys;r.setState({selectedKeys:t})},r.handleClearFilters=function(){r.setState({selectedKeys:[]},r.handleConfirm)},r.handleConfirm=function(){r.setState({visible:!1}),r.props.confirmFilter(r.props.column,r.state.selectedKeys)},r.onVisibleChange=function(e){r.setState({visible:e}),e||r.props.confirmFilter(r.props.column,r.state.selectedKeys)},r.handleMenuItemClick=function(e){if(!(e.keyPath.length<=1)){var t=r.state.keyPathOfSelectedItem;r.state.selectedKeys.indexOf(e.key)>=0?delete t[e.key]:t[e.key]=e.keyPath,r.setState({keyPathOfSelectedItem:t})}},r.state={selectedKeys:r.props.selectedKeys,keyPathOfSelectedItem:{},visible:!1},r}return s(t,e),t.prototype.componentWillReceiveProps=function(e){this.setState({selectedKeys:e.selectedKeys})},t.prototype.renderMenuItem=function(e){var t=this.props.column,n="filterMultiple"in t?t.filterMultiple:!0;return f["default"].createElement(d.Item,{key:e.value},n?f["default"].createElement(P["default"],{checked:this.state.selectedKeys.indexOf(e.value.toString())>=0}):f["default"].createElement(C["default"],{checked:this.state.selectedKeys.indexOf(e.value.toString())>=0}),f["default"].createElement("span",null,e.text))},t.prototype.renderMenus=function(e){var t=this;return e.map(function(e){if(e.children&&e.children.length>0){var n=function(){var n=t.state.keyPathOfSelectedItem,r=Object.keys(n).some(function(t){return n[t].indexOf(e.value)>=0}),o=r?"ant-dropdown-submenu-contain-selected":"";return{v:f["default"].createElement(d.SubMenu,{title:e.text,className:o,key:e.value.toString()},e.children.map(function(e){return t.renderMenuItem(e)}))}}();if("object"===("undefined"==typeof n?"undefined":c(n)))return n.v}return t.renderMenuItem(e)})},t.prototype.render=function(){var e=this.props,t=e.column,n=e.locale,r="filterMultiple"in t?t.filterMultiple:!0,o=f["default"].createElement("div",{className:"ant-table-filter-dropdown"},f["default"].createElement(h["default"],{multiple:r,onClick:this.handleMenuItemClick,prefixCls:"ant-dropdown-menu",onSelect:this.setSelectedKeys,onDeselect:this.setSelectedKeys,selectedKeys:this.state.selectedKeys},this.renderMenus(t.filters)),f["default"].createElement("div",{className:"ant-table-filter-dropdown-btns"},f["default"].createElement("a",{className:"ant-table-filter-dropdown-link confirm",onClick:this.handleConfirm},n.filterConfirm),f["default"].createElement("a",{className:"ant-table-filter-dropdown-link clear",onClick:this.handleClearFilters},n.filterReset))),a=this.props.selectedKeys.length>0?"ant-table-filter-selected":"";return f["default"].createElement(v["default"],{trigger:["click"],overlay:o,visible:this.state.visible,onVisibleChange:this.onVisibleChange,closeOnSelect:!1},f["default"].createElement(g["default"],{title:n.filterTitle,type:"filter",className:a}))},t}(f["default"].Component),l.defaultProps={handleFilter:function(){},column:null},u);t["default"]=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){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(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 s(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 l(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function u(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 c(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))}function p(){}function f(e){e.stopPropagation(),e.nativeEvent.stopImmediatePropagation()}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var d,h,y,v=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},m=n(1),g=r(m),b=n(361),P=r(b),O=n(18),C=r(O),T=n(24),w=r(T),x=n(224),E=r(x),S=n(60),k=r(S),j=n(7),_=r(j),N=n(66),M=r(N),D=n(2),A=r(D),L=n(227),V={filterTitle:"\u7b5b\u9009",filterConfirm:"\u786e\u5b9a",filterReset:"\u91cd\u7f6e",emptyText:g["default"].createElement("span",null,g["default"].createElement(_["default"],{type:"frown"}),"\u6682\u65e0\u6570\u636e")},F={pageSize:10,onChange:p,onShowSizeChange:p},I=(h=d=function(e){function t(n){l(this,t);var r=u(this,e.call(this,n));y.call(r);var o=n.pagination||{};return r.state=v({selectedRowKeys:(n.rowSelection||{}).selectedRowKeys||[],filters:r.getFiltersFromColumns(),selectionDirty:!1},r.getSortStateFromColumns(),{pagination:r.hasPagination()?v({},F,o,{current:o.defaultCurrent||o.current||1}):{}}),r}return c(t,e),t.prototype.getDefaultSelection=function(){var e=this;return this.props.rowSelection&&this.props.rowSelection.getCheckboxProps?this.getFlatCurrentPageData().filter(function(t){return e.props.rowSelection.getCheckboxProps(t).defaultChecked}).map(function(t,n){return e.getRecordKey(t,n)}):[]},t.prototype.getLocale=function(){var e={};return this.context.antLocale&&this.context.antLocale.Table&&(e=this.context.antLocale.Table),v({},V,e,this.props.locale)},t.prototype.componentWillReceiveProps=function(e){var t=this;if("pagination"in e&&e.pagination!==!1&&this.setState(function(t){var n=v({},F,t.pagination,e.pagination);return n.current=n.current||1,{pagination:n}}),"dataSource"in e&&e.dataSource!==this.props.dataSource&&this.setState({selectionDirty:!1}),e.rowSelection&&"selectedRowKeys"in e.rowSelection&&this.setState({selectedRowKeys:e.rowSelection.selectedRowKeys||[]}),this.getSortOrderColumns(e.columns).length>0){var n=this.getSortStateFromColumns(e.columns);n.sortColumn===this.state.sortColumn&&n.sortOrder===this.state.sortOrder||this.setState(n)}var r=this.getFilteredValueColumns(e.columns);r.length>0&&!function(){var n=t.getFiltersFromColumns(e.columns),r=v({},t.state.filters);Object.keys(n).forEach(function(e){r[e]=n[e]}),t.isFiltersChanged(r)&&t.setState({filters:r})}()},t.prototype.setSelectedRowKeys=function(e){var t=this;if(!this.props.rowSelection||"selectedRowKeys"in this.props.rowSelection||this.setState({selectedRowKeys:e}),this.props.rowSelection&&this.props.rowSelection.onChange){var n=this.getFlatCurrentPageData(),r=n.filter(function(n,r){return e.indexOf(t.getRecordKey(n,r))>=0});this.props.rowSelection.onChange(e,r)}},t.prototype.hasPagination=function(){return this.props.pagination!==!1},t.prototype.isFiltersChanged=function(e){var t=this,n=!1;return Object.keys(e).length!==Object.keys(this.state.filters).length?n=!0:Object.keys(e).forEach(function(r){e[r]!==t.state.filters[r]&&(n=!0)}),n},t.prototype.getSortOrderColumns=function(e){return(e||this.props.columns||[]).filter(function(e){return"sortOrder"in e})},t.prototype.getFilteredValueColumns=function(e){return(e||this.props.columns||[]).filter(function(e){return"filteredValue"in e})},t.prototype.getFiltersFromColumns=function(e){var t=this,n={};return this.getFilteredValueColumns(e).forEach(function(e){n[t.getColumnKey(e)]=e.filteredValue}),n},t.prototype.getSortStateFromColumns=function(e){var t=this.getSortOrderColumns(e).filter(function(e){return e.sortOrder})[0];return t?{sortColumn:t,sortOrder:t.sortOrder}:{sortColumn:null,sortOrder:null}},t.prototype.getSorterFn=function(){var e=this.state,t=e.sortOrder,n=e.sortColumn;return t&&n&&"function"==typeof n.sorter?function(e,r){var o=n.sorter(e,r);return 0!==o?"descend"===t?-o:o:e.indexForSort-r.indexForSort}:void 0},t.prototype.toggleSortOrder=function(e,t){var n,r=this.state,o=r.sortColumn,a=r.sortOrder,i=this.isSortColumn(t);i?a===e?(a="",o=null):a=e:(a=e,o=t);var l={sortOrder:a,sortColumn:o};0===this.getSortOrderColumns().length&&this.setState(l),(n=this.props).onChange.apply(n,s(this.prepareParamsArguments(v({},this.state,l))))},t.prototype.getRecordKey=function(e,t){return this.props.rowKey?this.props.rowKey(e,t):e.key||t},t.prototype.renderRowSelection=function(){var e=this,t=this.props.columns.concat();if(this.props.rowSelection){var n=this.getFlatCurrentPageData().filter(function(t){return e.props.rowSelection.getCheckboxProps?!e.props.rowSelection.getCheckboxProps(t).disabled:!0}),r=void 0;r=n.length?this.state.selectionDirty?n.every(function(t,n){return e.state.selectedRowKeys.indexOf(e.getRecordKey(t,n))>=0}):n.every(function(t,n){return e.state.selectedRowKeys.indexOf(e.getRecordKey(t,n))>=0})||n.every(function(t){return e.props.rowSelection.getCheckboxProps&&e.props.rowSelection.getCheckboxProps(t).defaultChecked}):!1;var o=void 0;if("radio"===this.props.rowSelection.type)o={key:"selection-column",render:this.renderSelectionRadio,className:"ant-table-selection-column"};else{var a=n.every(function(t){return e.props.rowSelection.getCheckboxProps&&e.props.rowSelection.getCheckboxProps(t).disabled}),i=g["default"].createElement(C["default"],{checked:r,disabled:a,onChange:this.handleSelectAllRow});o={key:"selection-column",title:i,render:this.renderSelectionCheckBox,className:"ant-table-selection-column"}}t.some(function(e){return"left"===e.fixed||e.fixed===!0})&&(o.fixed="left"),t[0]&&"selection-column"===t[0].key?t[0]=o:t.unshift(o)}return t},t.prototype.getColumnKey=function(e,t){return e.key||e.dataIndex||t},t.prototype.isSortColumn=function(e){var t=this.state.sortColumn;return e&&t?this.getColumnKey(t)===this.getColumnKey(e):!1},t.prototype.renderColumnsDropdown=function(e){var t=this,n=this.state.sortOrder,r=this.getLocale();return e.map(function(e,o){var a=v({},e),i=t.getColumnKey(a,o),s=void 0,l=void 0;if(a.filters&&a.filters.length>0){var u=t.state.filters[i]||[];s=g["default"].createElement(E["default"],{locale:r,column:a,selectedKeys:u,confirmFilter:t.handleFilter})}if(a.sorter){var c=t.isSortColumn(a);c&&(a.className=a.className||"",n&&(a.className+=" ant-table-column-sort"));var p=c&&"ascend"===n,f=c&&"descend"===n;l=g["default"].createElement("div",{className:"ant-table-column-sorter"},g["default"].createElement("span",{className:"ant-table-column-sorter-up "+(p?"on":"off"),title:"\u2191",onClick:function(){return t.toggleSortOrder("ascend",a)}},g["default"].createElement(_["default"],{type:"caret-up"})),g["default"].createElement("span",{className:"ant-table-column-sorter-down "+(f?"on":"off"),title:"\u2193",onClick:function(){return t.toggleSortOrder("descend",a)}},g["default"].createElement(_["default"],{type:"caret-down"})))}return a.title=g["default"].createElement("span",null,a.title,l,s),a})},t.prototype.renderPagination=function(){if(!this.hasPagination())return null;var e="default";this.state.pagination.size?e=this.state.pagination.size:"middle"!==this.props.size&&"small"!==this.props.size||(e="small");var t=this.state.pagination.total||this.getLocalData().length;return t>0?g["default"].createElement(k["default"],v({},this.state.pagination,{className:this.props.prefixCls+"-pagination",onChange:this.handlePageChange,total:t,size:e,onShowSizeChange:this.handleShowSizeChange})):null},t.prototype.prepareParamsArguments=function(e){var t=e.pagination,n=e.filters,r={};return e.sortColumn&&e.sortOrder&&(r.column=e.sortColumn,r.order=e.sortOrder,r.field=e.sortColumn.dataIndex,r.columnKey=this.getColumnKey(e.sortColumn)),[t,n,r]},t.prototype.findColumn=function(e){var t=this;return this.props.columns.filter(function(n){return t.getColumnKey(n)===e})[0]},t.prototype.getCurrentPageData=function(){var e=this.getLocalData(),t=void 0,n=void 0,r=this.state;return this.hasPagination()?(n=r.pagination.pageSize,t=r.pagination.current):(n=Number.MAX_VALUE,t=1),(e.length>n||n===Number.MAX_VALUE)&&(e=e.filter(function(e,r){return r>=(t-1)*n&&t*n>r})),e},t.prototype.getFlatCurrentPageData=function(){return(0,L.flatArray)(this.getCurrentPageData())},t.prototype.getLocalData=function(){var e=this,t=this.state,n=this.props.dataSource||[];n=n.slice(0);for(var r=0;r<n.length;r++)n[r].indexForSort=r;var o=this.getSorterFn();return o&&(n=n.sort(o)),t.filters&&Object.keys(t.filters).forEach(function(r){var o=e.findColumn(r);if(o){var a=t.filters[r]||[];0!==a.length&&(n=o.onFilter?n.filter(function(e){return a.some(function(t){return o.onFilter(t,e)})}):n)}}),n},t.prototype.render=function(){var e,t=this,n=this.props,r=n.style,o=n.className,s=i(n,["style","className"]),l=this.getCurrentPageData(),u=this.renderRowSelection(),c=this.props.expandedRowRender&&this.props.expandIconAsCell!==!1,p=this.getLocale(),f=(0,A["default"])((e={},a(e,"ant-table-"+this.props.size,!0),a(e,"ant-table-bordered",this.props.bordered),e));u=this.renderColumnsDropdown(u),u=u.map(function(e,n){var r=v({},e);return r.key=t.getColumnKey(r,n),r});var d=void 0,h="";l&&0!==l.length||(d=g["default"].createElement("div",{className:"ant-table-placeholder"},p.emptyText),h="ant-table-empty");var y=g["default"].createElement("div",null,g["default"].createElement(P["default"],v({},s,{data:l,columns:u,className:f,expandIconColumnIndex:u[0]&&"selection-column"===u[0].key?1:0,expandIconAsCell:c})),d),m=this.hasPagination()&&l&&0!==l.length?"ant-table-with-pagination":"ant-table-without-pagination",b=this.props.loading?m+" ant-table-spin-holder":"";return y=g["default"].createElement(M["default"],{className:b,spinning:this.props.loading},y),g["default"].createElement("div",{className:h+" "+o+" clearfix",style:r},y,this.renderPagination())},t}(g["default"].Component),d.propTypes={dataSource:g["default"].PropTypes.array,prefixCls:g["default"].PropTypes.string,useFixedHeader:g["default"].PropTypes.bool,rowSelection:g["default"].PropTypes.object,className:g["default"].PropTypes.string,size:g["default"].PropTypes.string,loading:g["default"].PropTypes.bool,bordered:g["default"].PropTypes.bool,onChange:g["default"].PropTypes.func,locale:g["default"].PropTypes.object},d.defaultProps={dataSource:[],prefixCls:"ant-table",useFixedHeader:!1,rowSelection:null,className:"",size:"large",loading:!1,bordered:!1,indentSize:20,onChange:p,locale:{}},d.contextTypes={antLocale:g["default"].PropTypes.object},y=function(){var e=this;this.handleFilter=function(t,n){var r=e.props,o=v({},e.state.pagination),i=v({},e.state.filters,a({},e.getColumnKey(t),n)),l=r.columns.map(function(t){return e.getColumnKey(t)});Object.keys(i).forEach(function(e){l.indexOf(e)<0&&delete i[e]}),r.pagination&&(o.current=1,o.onChange(o.current));var u={selectionDirty:!1,pagination:o},c=v({},i);e.getFilteredValueColumns().forEach(function(t){var n=e.getColumnKey(t);n&&delete c[n]}),Object.keys(c).length>0&&(u.filters=c),r.pagination&&"current"in r.pagination&&(u.pagination=v({},o,{current:e.state.pagination.current})),e.setState(u,function(){r.onChange.apply(r,s(e.prepareParamsArguments(v({},e.state,{selectionDirty:!1,filters:i,pagination:o}))))})},this.handleSelect=function(t,n,r){var o=r.target.checked,a=e.state.selectionDirty?[]:e.getDefaultSelection(),i=e.state.selectedRowKeys.concat(a),s=e.getRecordKey(t,n);if(o?i.push(e.getRecordKey(t,n)):i=i.filter(function(e){return s!==e}),e.setState({selectionDirty:!0}),e.setSelectedRowKeys(i),e.props.rowSelection.onSelect){var l=e.getFlatCurrentPageData(),u=l.filter(function(t,n){return i.indexOf(e.getRecordKey(t,n))>=0});e.props.rowSelection.onSelect(t,o,u)}},this.handleRadioSelect=function(t,n,r){var o=r.target.checked,a=e.state.selectionDirty?[]:e.getDefaultSelection(),i=e.state.selectedRowKeys.concat(a),s=e.getRecordKey(t,n);if(i=[s],e.setState({selectionDirty:!0}),e.setSelectedRowKeys(i),e.props.rowSelection.onSelect){var l=e.getFlatCurrentPageData(),u=l.filter(function(t,n){return i.indexOf(e.getRecordKey(t,n))>=0});e.props.rowSelection.onSelect(t,o,u)}},this.handleSelectAllRow=function(t){var n=t.target.checked,r=e.getFlatCurrentPageData(),o=e.state.selectionDirty?[]:e.getDefaultSelection(),a=e.state.selectedRowKeys.concat(o),i=r.filter(function(t){return!e.props.rowSelection.getCheckboxProps||!e.props.rowSelection.getCheckboxProps(t).disabled}).map(function(t,n){return e.getRecordKey(t,n)}),s=[];if(n?i.forEach(function(e){a.indexOf(e)<0&&(a.push(e),s.push(e))}):i.forEach(function(e){a.indexOf(e)>=0&&(a.splice(a.indexOf(e),1),s.push(e))}),e.setState({selectionDirty:!0}),e.setSelectedRowKeys(a),e.props.rowSelection.onSelectAll){var l=r.filter(function(t,n){return a.indexOf(e.getRecordKey(t,n))>=0}),u=r.filter(function(t,n){return s.indexOf(e.getRecordKey(t,n))>=0});e.props.rowSelection.onSelectAll(n,l,u)}},this.handlePageChange=function(t){var n,r=e.props,o=v({},e.state.pagination);t?o.current=t:o.current=o.current||1,o.onChange(o.current);var a={selectionDirty:!1,pagination:o};r.pagination&&"current"in r.pagination&&(a.pagination=v({},o,{current:e.state.pagination.current})),e.setState(a),(n=e.props).onChange.apply(n,s(e.prepareParamsArguments(v({},e.state,{selectionDirty:!1,pagination:o}))))},this.renderSelectionRadio=function(t,n,r){var o=e.getRecordKey(n,r),a={};e.props.rowSelection.getCheckboxProps&&(a=e.props.rowSelection.getCheckboxProps.call(e,n));var i=void 0;return i=e.state.selectionDirty?e.state.selectedRowKeys.indexOf(o)>=0:e.state.selectedRowKeys.indexOf(o)>=0||e.getDefaultSelection().indexOf(o)>=0,g["default"].createElement("span",{onClick:f},g["default"].createElement(w["default"],{disabled:a.disabled,onChange:function(t){return e.handleRadioSelect(n,o,t)},value:o,checked:i}))},this.renderSelectionCheckBox=function(t,n,r){var o=e.getRecordKey(n,r),a=void 0;a=e.state.selectionDirty?e.state.selectedRowKeys.indexOf(o)>=0:e.state.selectedRowKeys.indexOf(o)>=0||e.getDefaultSelection().indexOf(o)>=0;var i={};return e.props.rowSelection.getCheckboxProps&&(i=e.props.rowSelection.getCheckboxProps.call(e,n)), g["default"].createElement("span",{onClick:f},g["default"].createElement(C["default"],{checked:a,disabled:i.disabled,onChange:function(t){return e.handleSelect(n,o,t)}}))},this.handleShowSizeChange=function(t,n){var r,o=e.state.pagination;o.onShowSizeChange(t,n);var a=v({},o,{pageSize:n,current:t});e.setState({pagination:a}),(r=e.props).onChange.apply(r,s(e.prepareParamsArguments(v({},e.state,{pagination:a}))))}},h);t["default"]=I,e.exports=t["default"]},function(e,t,n){"use strict";n(3),n(448),n(34),n(19),n(55),n(67),n(61)},function(e,t){"use strict";function n(){var e=arguments.length<=0||void 0===arguments[0]?[]:arguments[0],t=arguments.length<=1||void 0===arguments[1]?"children":arguments[1],n=[],o=function a(e){e.forEach(function(e){var o=r({},e);delete o[t],n.push(o),e[t]&&e[t].length>0&&a(e[t])})};return o(e),n}Object.defineProperty(t,"__esModule",{value:!0});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};t.flatArray=n},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],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(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){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}),t["default"]=void 0;var u,c,p=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},f=n(366),d=r(f),h=n(1),y=r(h),v=n(2),m=r(v),g=n(7),b=r(g),P=(c=u=function(e){function t(){var n,r,o;i(this,t);for(var a=arguments.length,l=Array(a),u=0;a>u;u++)l[u]=arguments[u];return n=r=s(this,e.call.apply(e,[this].concat(l))),r.createNewTab=function(e){r.props.onEdit(e,"add")},r.removeTab=function(e,t){t.stopPropagation(),e&&r.props.onEdit(e,"remove")},r.handleChange=function(e){r.props.onChange(e)},o=n,s(r,o)}return l(t,e),t.prototype.render=function(){var e,t=this,n=this.props,r=n.prefixCls,o=n.size,i=n.tabPosition,s=n.animation,l=n.type,u=n.children,c=n.tabBarExtraContent,f=n.hideAdd,v=(0,m["default"])((e={},a(e,this.props.className,!!this.props.className),a(e,r+"-mini","small"===o||"mini"===o),a(e,r+"-vertical","left"===i||"right"===i),a(e,r+"-card",l.indexOf("card")>=0),a(e,r+"-"+l,!0),e));return("left"===i||"right"===i||l.indexOf("card")>=0)&&(s=null),"editable-card"===l&&(u=u.map(function(e,n){return(0,h.cloneElement)(e,{tab:y["default"].createElement("div",null,e.props.tab,y["default"].createElement(b["default"],{type:"cross",onClick:function(n){return t.removeTab(e.key,n)}})),key:e.key||n})}),f||(c=y["default"].createElement("span",null,y["default"].createElement(b["default"],{type:"plus",className:r+"-new-tab",onClick:this.createNewTab}),c))),c=c?y["default"].createElement("div",{className:r+"-extra-content"},c):null,y["default"].createElement(d["default"],p({},this.props,{className:v,tabBarExtraContent:c,onChange:this.handleChange,animation:s}),u)},t}(y["default"].Component),u.TabPane=d["default"].TabPane,u.defaultProps={prefixCls:"ant-tabs",animation:"slide-horizontal",type:"line",onChange:function(){},onEdit:function(){},hideAdd:!1},c);t["default"]=P,e.exports=t["default"]},[459,449],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],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(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 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}),t["default"]=void 0;var c,p,f=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),h=r(d),y=n(4),v=r(y),m=n(9),g=r(m),b=n(7),P=r(b),O=n(2),C=r(O),T=(p=c=function(e){function t(n){s(this,t);var r=l(this,e.call(this,n));return r.close=function(e){if(r.props.onClose(e),!e.defaultPrevented){var t=v["default"].findDOMNode(r),n=t.getBoundingClientRect().width;t.style.width=n+"px",t.style.width=n+"px",r.setState({closing:!0})}},r.animationEnd=function(e,t){t||r.state.closed||(r.setState({closed:!0,closing:!1}),r.props.afterClose())},r.state={closing:!1,closed:!1},r}return u(t,e),t.prototype.render=function(){var e,t=this.props,n=t.prefixCls,r=t.closable,o=t.color,s=t.className,l=t.children,u=i(t,["prefixCls","closable","color","className","children"]),c=r?h["default"].createElement(P["default"],{type:"cross",onClick:this.close}):"",p=(0,C["default"])((e={},a(e,n,!0),a(e,n+"-"+o,!!o),a(e,n+"-close",this.state.closing),a(e,s,!!s),e));return h["default"].createElement(g["default"],{component:"",showProp:"data-show",transitionName:n+"-zoom",transitionAppear:!0,onEnd:this.animationEnd},this.state.closed?null:h["default"].createElement("div",f({"data-show":!this.state.closing},u,{className:p}),h["default"].createElement("span",{className:n+"-text"},l),c))},t}(h["default"].Component),c.defaultProps={prefixCls:"ant-tag",closable:!1,onClose:function(){},afterClose:function(){}},p);t["default"]=T,e.exports=t["default"]},[459,450],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],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(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){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}),t["default"]=void 0;var u,c,p=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},f=n(1),d=r(f),h=n(27),y=r(h),v=n(105),m=r(v),g=n(68),b=r(g),P=n(2),O=r(P),C=n(10),T=r(C),w=(c=u=function(e){function t(){var n,r,o;i(this,t);for(var a=arguments.length,l=Array(a),u=0;a>u;u++)l[u]=arguments[u];return n=r=s(this,e.call.apply(e,[this].concat(l))),r.handleChange=function(e){r.props.onChange(e?new Date(e.getTime()):null,e?r.getFormatter().format(e):"")},o=n,s(r,o)}return l(t,e),t.prototype.getFormatter=function(){return new y["default"](this.props.format,this.getLocale().format)},t.prototype.getSizeClass=function(){var e="";return"large"===this.props.size?e=" ant-input-lg":"small"===this.props.size&&(e=" ant-input-sm"),e},t.prototype.parseTimeFromValue=function(e){if(e){if("string"==typeof e)return this.getFormatter().parse(e,{locale:this.getLocale().calendar,obeyCount:!0});if(e instanceof Date){var t=new T["default"](this.getLocale().calendar);return t.setTime(+e),t}}return e},t.prototype.getLocale=function(){var e=b["default"];return this.context.antLocale&&this.context.antLocale.TimePicker&&(e=this.context.antLocale.TimePicker),p({},e,this.props.locale)},t.prototype.render=function(){var e,t=this.getLocale(),n=p({},this.props);n.placeholder="placeholder"in this.props?n.placeholder:t.placeholder,n.defaultValue?n.defaultValue=this.parseTimeFromValue(n.defaultValue):delete n.defaultValue,n.value&&(n.value=this.parseTimeFromValue(n.value));var r=(0,O["default"])((e={},a(e,n.className,!!n.className),a(e,n.prefixCls+"-"+n.size,!!n.size),e));return n.format.indexOf("ss")<0&&(n.showSecond=!1),n.format.indexOf("HH")<0&&(n.showHour=!1),d["default"].createElement(m["default"],p({},n,{className:r,locale:t,formatter:this.getFormatter(),onChange:this.handleChange}))},t}(d["default"].Component),u.defaultProps={format:"HH:mm:ss",prefixCls:"ant-time-picker",onChange:function(){},locale:{},align:{offset:[0,-2]},disabled:!1,disabledHours:void 0,disabledMinutes:void 0,disabledSeconds:void 0,hideDisabledOptions:!1,placement:"bottomLeft",transitionName:"slide-up"},u.contextTypes={antLocale:d["default"].PropTypes.object},c);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){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(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 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}),t["default"]=void 0;var c,p,f=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),h=r(d),y=n(2),v=r(y),m=n(70),g=r(m),b=(p=c=function(e){function t(){return s(this,t),l(this,e.apply(this,arguments))}return u(t,e),t.prototype.render=function(){var e,t=this.props,n=t.prefixCls,r=t.children,o=t.pending,s=t.className,l=i(t,["prefixCls","children","pending","className"]),u="boolean"==typeof o?null:o,c=(0,v["default"])((e={},a(e,n,!0),a(e,n+"-pending",!!o),a(e,s,s),e));return h["default"].createElement("ul",f({},l,{className:c}),h["default"].Children.map(r,function(e,t){return h["default"].cloneElement(e,{last:t===r.length-1})}),o?h["default"].createElement(g["default"],{pending:!!o},u):null)},t}(h["default"].Component),c.defaultProps={prefixCls:"ant-timeline"},p);t["default"]=b,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(233),a=r(o),i=n(70),s=r(i);a["default"].Item=s["default"],t["default"]=a["default"],e.exports=t["default"]},[459,452],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],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(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,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}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))}function c(){}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var p,f,d=n(1),h=r(d),y=n(237),v=r(y),m=n(238),g=r(m),b=n(72),P=r(b),O=n(2),C=r(O),T=(f=p=function(e){function t(n){s(this,t);var r=l(this,e.call(this,n));return r.moveTo=function(e){var t=r.props.targetKeys,n=r.state,o=n.leftCheckedKeys,a=n.rightCheckedKeys,s="right"===e?o:a,l="right"===e?s.concat(t):t.filter(function(e){return!s.some(function(t){return e===t})});r.setState(i({},"right"===e?"leftCheckedKeys":"rightCheckedKeys",[])),r.props.onChange(l,e,s)},r.moveToLeft=function(){return r.moveTo("left")},r.moveToRight=function(){return r.moveTo("right")},r.handleSelectAll=function(e){var t=r.splitDataSource(r.props),n=t.leftDataSource,o=t.rightDataSource,a=r.state,s=a.leftFilter,l=a.rightFilter,u="left"===e?n:o,c="left"===e?s:l,p=r.getGlobalCheckStatus(e),f="all"===p?[]:r.filterDataSource(u,c).map(function(e){return e.key});r.setState(i({},e+"CheckedKeys",f))},r.handleLeftSelectAll=function(){return r.handleSelectAll("left")},r.handleRightSelectAll=function(){return r.handleSelectAll("right")},r.handleFilter=function(e,t){var n;r.setState((n={},i(n,e+"CheckedKeys",[]),i(n,e+"Filter",t.target.value),n))},r.handleLeftFilter=function(e){return r.handleFilter("left",e)},r.handleRightFilter=function(e){return r.handleFilter("right",e)},r.handleClear=function(e){r.setState(i({},e+"Filter",""))},r.handleLeftClear=function(){return r.handleClear("left")},r.handleRightClear=function(){return r.handleClear("right")},r.handleSelect=function(e,t,n){var o=r.state,a=o.leftCheckedKeys,s=o.rightCheckedKeys,l="left"===e?a:s,u=void 0;l.forEach(function(e,n){e===t.key&&(u=n)}),u>-1&&l.splice(u,1),n&&l.push(t.key),r.setState(i({},e+"CheckedKeys",l))},r.handleLeftSelect=function(e,t){return r.handleSelect("left",e,t)},r.handleRightSelect=function(e,t){return r.handleSelect("right",e,t)},r.state={leftFilter:"",rightFilter:"",leftCheckedKeys:[],rightCheckedKeys:[]},r}return u(t,e),t.prototype.componentWillReceiveProps=function(e){var t=this.state,n=t.leftCheckedKeys,r=t.rightCheckedKeys,o=this.splitDataSource(e),a=o.leftDataSource,i=o.rightDataSource;this.setState({leftCheckedKeys:n.filter(function(e){return a.filter(function(t){return t.key===e}).length}),rightCheckedKeys:r.filter(function(e){return i.filter(function(t){return t.key===e}).length})})},t.prototype.splitDataSource=function(e){var t=e.targetKeys,n=e.dataSource;e.rowKey&&(n=n.map(function(t){return t.key=e.rowKey(t),t}));var r=[].concat(a(n)),o=[];return t.length>0&&t.forEach(function(e){o.push(r.filter(function(t,n){return t.key===e?(r.splice(n,1),!0):!1})[0])}),{leftDataSource:r,rightDataSource:o}},t.prototype.getGlobalCheckStatus=function(e){var t=this.splitDataSource(this.props),n=t.leftDataSource,r=t.rightDataSource,o=this.state,a=o.leftFilter,i=o.rightFilter,s=o.leftCheckedKeys,l=o.rightCheckedKeys,u="left"===e?n:r,c="left"===e?a:i,p="left"===e?s:l,f=this.filterDataSource(u,c),d=void 0;return d=p.length>0?p.length<f.length?"part":"all":"none"},t.prototype.filterDataSource=function(e,t){var n=this;return e.filter(function(e){var r=n.props.render(e),o=void 0;return o=(0,y.isRenderResultPlainObject)(r)?r.value:r,n.matchFilter(o,t)})},t.prototype.matchFilter=function(e,t){var n=new RegExp(t);return e.match(n)},t.prototype.render=function n(){var e,t=this.props,r=t.prefixCls,o=t.titles,a=t.operations,s=t.showSearch,l=t.notFoundContent,u=t.searchPlaceholder,c=t.body,p=t.footer,f=t.listStyle,d=t.className,n=t.render,y=this.state,m=y.leftFilter,b=y.rightFilter,P=y.leftCheckedKeys,O=y.rightCheckedKeys,T=this.splitDataSource(this.props),w=T.leftDataSource,x=T.rightDataSource,E=O.length>0,S=P.length>0,k=this.getGlobalCheckStatus("left"),j=this.getGlobalCheckStatus("right"),_=(0,C["default"])((e={},i(e,d,!!d),i(e,r,!0),e));return h["default"].createElement("div",{className:_},h["default"].createElement(v["default"],{titleText:o[0],dataSource:w,filter:m,style:f,checkedKeys:P,checkStatus:k,handleFilter:this.handleLeftFilter,handleClear:this.handleLeftClear,handleSelect:this.handleLeftSelect,handleSelectAll:this.handleLeftSelectAll,position:"left",render:n,showSearch:s,searchPlaceholder:u,notFoundContent:l,body:c,footer:p,prefixCls:r+"-list"}),h["default"].createElement(g["default"],{rightActive:S,rightArrowText:a[0],moveToRight:this.moveToRight,leftActive:E,leftArrowText:a[1],moveToLeft:this.moveToLeft,className:r+"-operation"}),h["default"].createElement(v["default"],{titleText:o[1],dataSource:x,filter:b,style:f,checkedKeys:O,checkStatus:j,handleFilter:this.handleRightFilter,handleClear:this.handleRightClear,handleSelect:this.handleRightSelect,handleSelectAll:this.handleRightSelectAll,position:"right",render:n,showSearch:s,searchPlaceholder:u,notFoundContent:l,body:c,footer:p,prefixCls:r+"-list"}))},t}(h["default"].Component),p.List=v["default"],p.Operation=g["default"],p.Search=P["default"],p.defaultProps={prefixCls:"ant-transfer",dataSource:[],render:c,targetKeys:[],onChange:c,titles:["\u6e90\u5217\u8868","\u76ee\u7684\u5217\u8868"],operations:[],showSearch:!1,body:c,footer:c},p.propTypes={prefixCls:d.PropTypes.string,dataSource:d.PropTypes.array,render:d.PropTypes.func,targetKeys:d.PropTypes.array,onChange:d.PropTypes.func,height:d.PropTypes.number,listStyle:d.PropTypes.object,className:d.PropTypes.string,titles:d.PropTypes.array,operations:d.PropTypes.array,showSearch:d.PropTypes.bool,searchPlaceholder:d.PropTypes.string,notFoundContent:d.PropTypes.node,body:d.PropTypes.func,footer:d.PropTypes.func,rowKey:d.PropTypes.func},f);t["default"]=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){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(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){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))}function u(){}function c(e){return e&&!y["default"].isValidElement(e)&&"[object Object]"===Object.prototype.toString.call(e)}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var p,f,d=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.isRenderResultPlainObject=c;var h=n(1),y=r(h),v=n(18),m=r(v),g=n(72),b=r(g),P=n(2),O=r(P),C=n(9),T=r(C),w=(f=p=function(e){function t(n){i(this,t);var r=s(this,e.call(this,n));return r.handleSelectAll=function(){r.props.handleSelectAll()},r.handleSelect=function(e){var t=r.props.checkedKeys,n=t.some(function(t){return t===e.key});r.props.handleSelect(e,!n)},r.handleFilter=function(e){r.props.handleFilter(e)},r.handleClear=function(){r.props.handleClear()},r.state={mounted:!1},r}return l(t,e),t.prototype.componentDidMount=function(){var e=this;setTimeout(function(){e.setState({mounted:!0})},0)},t.prototype.renderCheckbox=function(e){var t,n=e.prefixCls,r=(0,O["default"])((t={},a(t,n+"-checkbox",!0),a(t,n+"-checkbox-indeterminate",e.checkPart),a(t,n+"-checkbox-checked",!e.checkPart&&e.checked),a(t,n+"-checkbox-disabled",!!e.disabled),t)),o=null;return"boolean"!=typeof e.checkable&&(o=e.checkable),y["default"].createElement("span",{ref:"checkbox",className:r,onClick:!e.disabled&&this.handleSelectAll},o)},t.prototype.matchFilter=function(e,t){var n=new RegExp(t);return e.match(n)},t.prototype.render=function n(){var e,t=this,r=this.props,o=r.prefixCls,i=r.dataSource,s=r.titleText,l=r.filter,u=r.checkedKeys,p=r.checkStatus,f=r.body,h=r.footer,v=r.showSearch,n=r.render,g=this.props,P=g.searchPlaceholder,C=g.notFoundContent,w=h(d({},this.props)),x=f(d({},this.props)),E=(0,O["default"])((e={},a(e,o,!0),a(e,o+"-with-footer",!!w),e)),S=i.filter(function(e){var r=n(e),o=void 0;o=c(r)?r.value:r;var a=t.matchFilter(o,l);return!!a}).map(function(e){var r=n(e),o=void 0,a=void 0;return c(r)?(o=r.value,a=r.label):(o=r,a=r),y["default"].createElement("li",{onClick:function(){t.handleSelect(e)},key:e.key,title:o},y["default"].createElement(m["default"],{checked:u.some(function(t){return t===e.key})}),y["default"].createElement("span",null,a))}),k="\u6761";return this.context.antLocale&&this.context.antLocale.Transfer&&(k=i.length>1?this.context.antLocale.Transfer.itemsUnit:this.context.antLocale.Transfer.itemUnit,P=P||this.context.antLocale.Transfer.searchPlaceholder,C=C||this.context.antLocale.Transfer.notFoundContent),y["default"].createElement("div",d({className:E},this.props),y["default"].createElement("div",{className:o+"-header"},this.renderCheckbox({prefixCls:"ant-transfer",checked:"all"===p,checkPart:"part"===p,checkable:y["default"].createElement("span",{className:"ant-transfer-checkbox-inner"})}),y["default"].createElement("span",{className:o+"-header-selected"},y["default"].createElement("span",null,(u.length>0?u.length+"/":"")+i.length," ",k),y["default"].createElement("span",{className:o+"-header-title"},s))),x||y["default"].createElement("div",{className:v?o+"-body "+o+"-body-with-search":o+"-body"},v?y["default"].createElement("div",{className:o+"-body-search-wrapper"},y["default"].createElement(b["default"],{prefixCls:o+"-search",onChange:this.handleFilter,handleClear:this.handleClear,placeholder:P||"\u8bf7\u8f93\u5165\u641c\u7d22\u5185\u5bb9",value:l})):null,y["default"].createElement(T["default"],{component:"ul",transitionName:this.state.mounted?o+"-highlight":"",transitionLeave:!1},S.length>0?S:y["default"].createElement("div",{className:o+"-body-not-found"},C||"\u5217\u8868\u4e3a\u7a7a"))),w?y["default"].createElement("div",{className:o+"-footer"},w):null)},t}(y["default"].Component),p.defaultProps={dataSource:[],titleText:"",showSearch:!1,handleFilter:u,handleSelect:u,handleSelectAll:u,render:u,body:u,footer:u},p.propTypes={prefixCls:h.PropTypes.string,dataSource:h.PropTypes.array,showSearch:h.PropTypes.bool,searchPlaceholder:h.PropTypes.string,titleText:h.PropTypes.string,style:h.PropTypes.object,handleFilter:h.PropTypes.func,handleSelect:h.PropTypes.func,handleSelectAll:h.PropTypes.func,render:h.PropTypes.func,body:h.PropTypes.func,footer:h.PropTypes.func},p.contextTypes={antLocale:y["default"].PropTypes.object},f);t["default"]=w},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],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(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 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):o(e,t))}function l(){}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var u,c,p=n(1),f=r(p),d=n(15),h=r(d),y=n(7),v=r(y),m=(c=u=function(e){function t(){return a(this,t),i(this,e.apply(this,arguments))}return s(t,e),t.prototype.render=function(){var e=this.props,t=e.moveToLeft,n=e.moveToRight,r=e.leftArrowText,o=e.rightArrowText,a=e.leftActive,i=e.rightActive,s=e.className,l=f["default"].createElement(h["default"],{type:"primary",size:"small",disabled:!a,onClick:t},f["default"].createElement("span",null,f["default"].createElement(v["default"],{type:"left"}),r)),u=f["default"].createElement(h["default"],{type:"primary",size:"small",disabled:!i,onClick:n},f["default"].createElement("span",null,o,f["default"].createElement(v["default"],{type:"right"})));return f["default"].createElement("div",{className:s},l,u)},t}(f["default"].Component),u.defaultProps={leftArrowText:"",rightArrowText:"",moveToLeft:l,moveToRight:l},u.propTypes={className:p.PropTypes.string,leftArrowText:p.PropTypes.string,rightArrowText:p.PropTypes.string,moveToLeft:p.PropTypes.func,moveToRight:p.PropTypes.func},c);t["default"]=m,e.exports=t["default"]},function(e,t,n){"use strict";n(3),n(454),n(19),n(23),n(13)},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],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(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){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}),t["default"]=void 0;var u,c,p=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},f=n(1),d=r(f),h=n(381),y=r(h),v=n(2),m=r(v),g=(c=u=function(e){function t(){return i(this,t),s(this,e.apply(this,arguments))}return l(t,e),t.prototype.render=function(){var e,t=this.props,n=this.props,r=n.size,o=n.className,i=n.combobox,s=n.notFoundContent,l=n.prefixCls,u=(0,m["default"])((e={},a(e,l+"-lg","large"===r),a(e,l+"-sm","small"===r),a(e,o,!!o),e)),c=this.context.antLocale;c&&c.Select&&(s=s||c.Select.notFoundContent),i&&(s=null);var f=t.treeCheckable;return f&&(f=d["default"].createElement("span",{className:l+"-tree-checkbox-inner"})),d["default"].createElement(y["default"],p({},this.props,{treeCheckable:f,className:u,notFoundContent:s}))},t}(d["default"].Component),u.TreeNode=h.TreeNode,u.SHOW_ALL=h.SHOW_ALL,u.SHOW_PARENT=h.SHOW_PARENT,u.SHOW_CHILD=h.SHOW_CHILD,u.defaultProps={prefixCls:"ant-select",transitionName:"slide-up",choiceTransitionName:"zoom",showSearch:!1,dropdownClassName:"ant-select-tree-dropdown"},u.contextTypes={antLocale:d["default"].PropTypes.object},c);t["default"]=g,e.exports=t["default"]},function(e,t,n){"use strict";n(3),n(455),n(26),n(19)},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],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(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 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):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var l,u,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(110),h=r(d),y=n(49),v=r(y),m=(u=l=function(e){function t(){return a(this,t),i(this,e.apply(this,arguments))}return s(t,e),t.prototype.render=function(){var e=this.props,t=e.checkable;return t&&(t=f["default"].createElement("span",{className:e.prefixCls+"-checkbox-inner"})),f["default"].createElement(h["default"],c({},e,{checkable:t}),this.props.children)},t}(f["default"].Component),l.TreeNode=h["default"].TreeNode,l.defaultProps={prefixCls:"ant-tree",checkable:!1,showIcon:!1,openAnimation:v["default"]},u);t["default"]=m,e.exports=t["default"]},function(e,t,n){"use strict";n(3),n(456),n(19)},function(e,t){"use strict";function n(e,t){var n=e.uid?"byUid":"byName",r=t.filter(function(t){return"byName"===n?t.name===e.name:t.uid===e.uid})[0];return r}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){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(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){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))}function u(){}function c(){return!0}function p(e){return{lastModified:e.lastModified,lastModifiedDate:e.lastModifiedDate,name:e.filename||e.name,size:e.size,type:e.type,uid:e.uid,response:e.response,error:e.error,percent:0,originFileObj:e}}function f(){var e=.1,t=.01,n=.98;return function(r){var o=r;return o>=n?o:(o+=e,e-=t,.001>e&&(e=.001),100*o)}}function d(e){return g["default"].createElement(k,v({},e,{type:"drag",style:{height:e.height}}))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var h,y,v=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},m=n(1),g=r(m),b=n(391),P=r(b),O=n(247),C=r(O),T=n(244),w=r(T),x=n(2),E=r(x),S="ant-upload",k=(y=h=function(e){function t(n){i(this,t);var r=s(this,e.call(this,n));return r.onStart=function(e){if(r.recentUploadStatus!==!1){var t=void 0,n=r.state.fileList.concat();e.length>0?(t=e.map(function(e){var t=p(e);return t.status="uploading",t}),n=n.concat(t)):(t=p(e),t.status="uploading",n.push(t)),r.onChange({file:t,fileList:n}),window.FormData||r.autoUpdateProgress(0,t)}},r.onSuccess=function(e,t){r.clearProgressTimer();try{"string"==typeof e&&(e=JSON.parse(e))}catch(n){}var o=r.state.fileList,a=(0,w["default"])(t,o);a&&(a.status="done",a.response=e,r.onChange({file:a,fileList:o}))},r.onProgress=function(e,t){var n=r.state.fileList,o=(0,w["default"])(t,n);o&&(o.percent=e.percent,r.onChange({event:e,file:o,fileList:r.state.fileList}))},r.onError=function(e,t,n){r.clearProgressTimer();var o=r.state.fileList,a=(0,w["default"])(n,o);a.error=e,a.response=t,a.status="error",r.handleRemove(a)},r.beforeUpload=function(e){return r.recentUploadStatus=r.props.beforeUpload(e),r.recentUploadStatus},r.handlePreview=function(e){"onPreview"in r.props&&r.props.onPreview(e)},r.handleManualRemove=function(e){e.status="removed","onRemove"in r.props?r.props.onRemove(e):r.handleRemove(e)},r.onChange=function(e){r.setState({fileList:e.fileList}),r.props.onChange(e)},r.onFileDrop=function(e){r.setState({dragState:e.type})},r.state={fileList:r.props.fileList||r.props.defaultFileList||[],dragState:"drop"},r}return l(t,e),t.prototype.autoUpdateProgress=function(e,t){var n=this,r=f(),o=0;this.progressTimer=setInterval(function(){o=r(o),n.onProgress({percent:o},t)},200)},t.prototype.removeFile=function(e){var t=this.state.fileList,n=(0,w["default"])(e,t),r=t.indexOf(n);return-1!==r?(t.splice(r,1),t):null},t.prototype.handleRemove=function(e){var t=this.removeFile(e);t&&this.onChange({file:e,fileList:t})},t.prototype.componentWillReceiveProps=function(e){"fileList"in e&&this.setState({fileList:e.fileList||[]})},t.prototype.clearProgressTimer=function(){clearInterval(this.progressTimer)},t.prototype.render=function(){var e,t=this.props.type||"select",n=v({},this.props,{onStart:this.onStart,onError:this.onError,onProgress:this.onProgress,onSuccess:this.onSuccess,beforeUpload:this.beforeUpload}),r=void 0;if(this.props.showUploadList&&(r=g["default"].createElement(C["default"],{listType:this.props.listType,items:this.state.fileList,onPreview:this.handlePreview,onRemove:this.handleManualRemove})),"drag"===t){var o=this.state.fileList.some(function(e){return"uploading"===e.status})?S+"-drag-uploading":"",i="dragover"===this.state.dragState?S+"-drag-hover":"";return g["default"].createElement("span",{className:this.props.className},g["default"].createElement("div",{className:S+" "+S+"-drag "+o+" "+i,onDrop:this.onFileDrop,onDragOver:this.onFileDrop,onDragLeave:this.onFileDrop},g["default"].createElement(P["default"],n,g["default"].createElement("div",{className:S+"-drag-container"},this.props.children))),r)}var s=(0,E["default"])((e={},a(e,S,!0),a(e,S+"-select",!0),a(e,S+"-select-"+this.props.listType,!0),e)),l=this.props.children?g["default"].createElement("div",{className:s},g["default"].createElement(P["default"],n)):null;return"picture-card"===this.props.listType?g["default"].createElement("span",{className:this.props.className},r,l):g["default"].createElement("span",{className:this.props.className},l,r)},t}(g["default"].Component),h.Dragger=d,h.defaultProps={type:"select",multiple:!1,action:"",data:{},accept:"",onChange:u,beforeUpload:c,showUploadList:!0,listType:"text",className:""},y);t["default"]=k,e.exports=t["default"]},function(e,t,n){"use strict";n(3),n(457),n(64)},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],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(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){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}),t["default"]=void 0;var u,c,p=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},f=n(1),d=r(f),h=n(9),y=r(h),v=n(7),m=r(v),g=n(63),b=r(g),P=n(2),O=r(P),C="ant-upload",T=function(e,t){var n=new FileReader;n.onloadend=function(){return t(n.result)},n.readAsDataURL(e)},w=(c=u=function(e){function t(){var n,r,o;i(this,t);for(var a=arguments.length,l=Array(a),u=0;a>u;u++)l[u]=arguments[u];return n=r=s(this,e.call.apply(e,[this].concat(l))),r.handleClose=function(e){r.props.onRemove(e)},r.handlePreview=function(e,t){return t.preventDefault(),r.props.onPreview(e)},o=n,s(r,o)}return l(t,e),t.prototype.componentDidUpdate=function(){var e=this;"picture"!==this.props.listType&&"picture-card"!==this.props.listType||this.props.items.forEach(function(t){"undefined"!=typeof document&&"undefined"!=typeof window&&window.FileReader&&window.File&&t.originFileObj instanceof File&&void 0===t.thumbUrl&&(t.thumbUrl="",T(t.originFileObj,function(n){t.thumbUrl=n,e.forceUpdate()}))})},t.prototype.render=function(){var e,t=this,n=this.props.items.map(function(e){var n,r=void 0,o=d["default"].createElement(m["default"],{type:"paper-clip"});"picture"!==t.props.listType&&"picture-card"!==t.props.listType||(o="uploading"===e.status||!e.thumbUrl&&!e.url?"picture-card"===t.props.listType?d["default"].createElement("div",{className:C+"-list-item-uploading-text"},"\u6587\u4ef6\u4e0a\u4f20\u4e2d"):d["default"].createElement(m["default"],{className:C+"-list-item-thumbnail",type:"picture"}):d["default"].createElement("a",{className:C+"-list-item-thumbnail",onClick:function(n){return t.handlePreview(e,n)},href:e.url,target:"_blank"},d["default"].createElement("img",{src:e.thumbUrl||e.url,alt:e.name}))),"uploading"===e.status&&(r=d["default"].createElement("div",{className:C+"-list-item-progress"},d["default"].createElement(b["default"],p({type:"line"},t.props.progressAttr,{percent:e.percent}))));var i=(0,O["default"])((n={},a(n,C+"-list-item",!0),a(n,C+"-list-item-"+e.status,!0),n));return d["default"].createElement("div",{className:i,key:e.uid},d["default"].createElement("div",{className:C+"-list-item-info"},o,e.url?d["default"].createElement("a",{onClick:function(n){return t.handlePreview(e,n)},href:e.url,target:"_blank",className:C+"-list-item-name"},e.name):d["default"].createElement("span",{className:C+"-list-item-name"},e.name),"picture-card"===t.props.listType&&"uploading"!==e.status?d["default"].createElement("span",null,d["default"].createElement("a",{onClick:function(n){return t.handlePreview(e,n)},href:e.url,target:"_blank",style:{pointerEvents:e.url?"":"none"}},d["default"].createElement(m["default"],{type:"eye-o"})),d["default"].createElement(m["default"],{type:"delete",onClick:function(){return t.handleClose(e)}})):d["default"].createElement(m["default"],{type:"cross",onClick:function(){return t.handleClose(e)}})),r)}),r=(0,O["default"])((e={},a(e,C+"-list",!0),a(e,C+"-list-"+this.props.listType,!0),e));return d["default"].createElement("div",{className:r},d["default"].createElement(y["default"],{transitionName:C+"-margin-top"},n))},t}(d["default"].Component),u.defaultProps={listType:"text",items:[],progressAttr:{strokeWidth:3,showInfo:!1}},c);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){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(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 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):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var l=n(1),u=r(l),c=n(17),p=r(c),f=function(e){function t(){return a(this,t),i(this,e.apply(this,arguments))}return s(t,e),t.prototype.componentDidMount=function(){(0,p["default"])(!1,"`Validation` is removed, please use `Form` which has supported validation after [email protected], or you can just import Validation from 'rc-form-validation' for compatibility")},t.prototype.render=function(){return null},t}(u["default"].Component);t["default"]=f,f.Validator=function(){},f.FieldMixin={setField:function(){}},e.exports=t["default"]},193,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(121);o.keys().forEach(function(e){var n=o(e),a=e.match(/^\.\/([^_][\w-]+)\/index\.jsx?$/);a&&a[1]&&("message"===a[1]||"notification"===a[1]?t[a[1]]=n:t[r(a[1])]=n)})},function(e,t){var n=!("undefined"==typeof window||!window.document||!window.document.createElement);e.exports=n},function(e,t){"use strict";function n(){var e=document.createElement("div"),t=e.style;"AnimationEvent"in window||delete a.animationend.animation,"TransitionEvent"in window||delete a.transitionend.transition;for(var n in a)if(a.hasOwnProperty(n)){var r=a[n];for(var o in r)if(o in t){i.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 a={transitionend:{transition:"transitionend",WebkitTransition:"webkitTransitionEnd",MozTransition:"mozTransitionEnd",OTransition:"oTransitionEnd",msTransition:"MSTransitionEnd"},animationend:{animation:"animationend",WebkitAnimation:"webkitAnimationEnd",MozAnimation:"mozAnimationEnd",OAnimation:"oAnimationEnd",msAnimation:"MSAnimationEnd"}},i=[];"undefined"!=typeof window&&"undefined"!=typeof document&&n();var s={addEndEventListener:function(e,t){return 0===i.length?void window.setTimeout(t,0):void i.forEach(function(n){r(e,n,t)})},endEvents:i,removeEndEventListener:function(e,t){0!==i.length&&i.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=i["default"].clone(e),a={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+a.width>n.right&&(a.width-=o.left+a.width-n.right),r.adjustX&&o.left+a.width>n.right&&(o.left=Math.max(n.right-a.width,n.left)),r.adjustY&&o.top<n.top&&(o.top=n.top),r.resizeHeight&&o.top>=n.top&&o.top+a.height>n.bottom&&(a.height-=o.top+a.height-n.bottom),r.adjustY&&o.top+a.height>n.bottom&&(o.top=Math.max(n.bottom-a.height,n.top)),i["default"].mix(o,a)}Object.defineProperty(t,"__esModule",{value:!0});var a=n(20),i=r(a);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,a=e.height,i=void 0,s=void 0;return i=e.left,s=e.top,"c"===n?s+=a/2:"b"===n&&(s+=a),"c"===r?i+=o/2:"r"===r&&(i+=o),{left:i,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 a=void 0,s=void 0,l=void 0,u=void 0;return a={left:e.left,top:e.top},l=(0,i["default"])(t,n[1]),u=(0,i["default"])(e,n[0]),s=[u.left-l.left,u.top-l.top],{left:a.left-s[0]+r[0]-o[0],top:a.top-s[1]+r[1]-o[1]}}Object.defineProperty(t,"__esModule",{value:!0});var a=n(254),i=r(a);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(i["default"].isWindow(e)||9===e.nodeType){var o=i["default"].getWindow(e);t={left:i["default"].getWindowScrollLeft(o),top:i["default"].getWindowScrollTop(o)},n=i["default"].viewportWidth(o),r=i["default"].viewportHeight(o)}else t=i["default"].offset(e),n=i["default"].outerWidth(e),r=i["default"].outerHeight(e);return t.width=n,t.height=r,t}Object.defineProperty(t,"__esModule",{value:!0});var a=n(20),i=r(a);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,a=void 0,s=e.ownerDocument,u=s.defaultView||s.parentWindow,c=s.body,p=s.documentElement;n;){if(-1!==navigator.userAgent.indexOf("MSIE")&&0===n.clientWidth||n===c||n===p||"visible"===i["default"].css(n,"overflow")){if(n===c||n===p)break}else{var f=i["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=i["default"].getWindowScrollLeft(u),o=i["default"].getWindowScrollTop(u),t.left=Math.max(t.left,r),t.top=Math.max(t.top,o),a={width:i["default"].viewportWidth(u),height:i["default"].viewportHeight(u)},t.right=Math.min(t.right,r+a.width),t.bottom=Math.min(t.bottom,o+a.height),t.top>=0&&t.left>=0&&t.bottom>t.top&&t.right>t.left?t:null}Object.defineProperty(t,"__esModule",{value:!0});var a=n(20),i=r(a),s=n(75),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 a(e,t,n){return e.top<n.top||e.top+t.height>n.bottom}function i(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 p(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],d=n.overflow,y=n.target||t,v=n.source||e;c=[].concat(c),f=[].concat(f),d=d||{};var m={},b=0,O=(0,g["default"])(v),T=(0,C["default"])(v),x=(0,C["default"])(y);p(c,T),p(f,x);var E=(0,w["default"])(T,x,r,c,f),S=h["default"].merge(T,E);if(O&&(d.adjustX||d.adjustY)){if(d.adjustX&&o(E,T,O)){var k=l(r,/[lr]/gi,{l:"r",r:"l"}),j=u(c,0),_=u(f,0),N=(0,w["default"])(T,x,k,j,_);i(N,T,O)||(b=1,r=k,c=j,f=_)}if(d.adjustY&&a(E,T,O)){var k=l(r,/[tb]/gi,{t:"b",b:"t"}),j=u(c,1),_=u(f,1),N=(0,w["default"])(T,x,k,j,_);s(N,T,O)||(b=1,r=k,c=j,f=_)}b&&(E=(0,w["default"])(T,x,r,c,f),h["default"].mix(S,E)),m.adjustX=d.adjustX&&o(E,T,O),m.adjustY=d.adjustY&&a(E,T,O),(m.adjustX||m.adjustY)&&(S=(0,P["default"])(E,T,O,m))}return S.width!==T.width&&h["default"].css(v,"width",v.width()+S.width-T.width),S.height!==T.height&&h["default"].css(v,"height",v.height()+S.height-T.height),h["default"].offset(v,{left:S.left,top:S.top},{useCssRight:n.useCssRight,useCssBottom:n.useCssBottom}),{points:r,offset:c,targetOffset:f,overflow:m}}Object.defineProperty(t,"__esModule",{value:!0});var d=n(20),h=r(d),y=n(75),v=r(y),m=n(257),g=r(m),b=n(253),P=r(b),O=n(256),C=r(O),T=n(255),w=r(T);f.__getOffsetParent=v["default"],f.__getVisibleRectForElement=g["default"],t["default"]=f,e.exports=t["default"]},function(e,t,n){"use strict";function r(e,t,n){n=n||{},9===t.nodeType&&(t=o.getWindow(t));var r=n.allowHorizontalScroll,a=n.onlyScrollIfNeeded,i=n.alignWithTop,s=n.alignWithLeft,l=n.offsetTop||0,u=n.offsetLeft||0,c=n.offsetBottom||0,p=n.offsetRight||0;r=void 0===r?!0:r;var f=o.isWindow(t),d=o.offset(e),h=o.outerHeight(e),y=o.outerWidth(e),v=void 0,m=void 0,g=void 0,b=void 0,P=void 0,O=void 0,C=void 0,T=void 0,w=void 0,x=void 0;f?(C=t,x=o.height(C),w=o.width(C),T={left:o.scrollLeft(C),top:o.scrollTop(C)},P={left:d.left-T.left-u,top:d.top-T.top-l},O={left:d.left+y-(T.left+w)+p,top:d.top+h-(T.top+x)+c},b=T):(v=o.offset(t),m=t.clientHeight,g=t.clientWidth,b={left:t.scrollLeft,top:t.scrollTop},P={left:d.left-(v.left+(parseFloat(o.css(t,"borderLeftWidth"))||0))-u,top:d.top-(v.top+(parseFloat(o.css(t,"borderTopWidth"))||0))-l},O={left:d.left+y-(v.left+g+(parseFloat(o.css(t,"borderRightWidth"))||0))+p,top:d.top+h-(v.top+m+(parseFloat(o.css(t,"borderBottomWidth"))||0))+c}),P.top<0||O.top>0?i===!0?o.scrollTop(t,b.top+P.top):i===!1?o.scrollTop(t,b.top+O.top):P.top<0?o.scrollTop(t,b.top+P.top):o.scrollTop(t,b.top+O.top):a||(i=void 0===i?!0:!!i,i?o.scrollTop(t,b.top+P.top):o.scrollTop(t,b.top+O.top)),r&&(P.left<0||O.left>0?s===!0?o.scrollLeft(t,b.left+P.left):s===!1?o.scrollLeft(t,b.left+O.left):P.left<0?o.scrollLeft(t,b.left+P.left):o.scrollLeft(t,b.left+O.left):a||(s=void 0===s?!0:!!s,s?o.scrollLeft(t,b.left+P.left):o.scrollLeft(t,b.left+O.left)))}var o=n(260);e.exports=r},function(e,t){"use strict";function n(e){var t=void 0,n=void 0,r=void 0,o=e.ownerDocument,a=o.body,i=o&&o.documentElement;return t=e.getBoundingClientRect(),n=t.left,r=t.top,n-=i.clientLeft||a.clientLeft||0,r-=i.clientTop||a.clientTop||0,{left:n,top:r}}function r(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 o(e){return r(e)}function a(e){return r(e,!0)}function i(e){var t=n(e),r=e.ownerDocument,i=r.defaultView||r.parentWindow;return t.left+=o(i),t.top+=a(i),t}function s(e,t,n){var r="",o=e.ownerDocument,a=n||o.defaultView.getComputedStyle(e,null);return a&&(r=a.getPropertyValue(t)||a[t]),r}function l(e,t){var n=e[T]&&e[T][t];if(O.test(n)&&!C.test(t)){var r=e.style,o=r[x],a=e[w][x];e[w][x]=e[T][x],r[x]="fontSize"===t?"1em":n||0,n=r.pixelLeft+E,r[x]=o,e[w][x]=a}return""===n?"auto":n}function u(e,t){for(var n=0;n<e.length;n++)t(e[n])}function c(e){return"border-box"===S(e,"boxSizing")}function p(e,t,n){var r={},o=e.style,a=void 0;for(a in t)t.hasOwnProperty(a)&&(r[a]=o[a],o[a]=t[a]);n.call(e);for(a in t)t.hasOwnProperty(a)&&(o[a]=r[a])}function f(e,t,n){var r=0,o=void 0,a=void 0,i=void 0;for(a=0;a<t.length;a++)if(o=t[a])for(i=0;i<n.length;i++){var s=void 0;s="border"===o?o+n[i]+"Width":o+n[i],r+=parseFloat(S(e,s))||0}return r}function d(e){return null!=e&&e==e.window}function h(e,t,n){if(d(e))return"width"===t?D.viewportWidth(e):D.viewportHeight(e);if(9===e.nodeType)return"width"===t?D.docWidth(e):D.docHeight(e);var r="width"===t?["Left","Right"]:["Top","Bottom"],o="width"===t?e.offsetWidth:e.offsetHeight,a=S(e),i=c(e,a),s=0;(null==o||0>=o)&&(o=void 0,s=S(e,t),(null==s||Number(s)<0)&&(s=e.style[t]||0),s=parseFloat(s)||0),void 0===n&&(n=i?N:j);var l=void 0!==o||i,u=o||s;if(n===j)return l?u-f(e,["border","padding"],r,a):s;if(l){var p=n===_?-f(e,["border"],r,a):f(e,["margin"],r,a);return u+(n===N?0:p)}return s+f(e,k.slice(n),r,a)}function y(e){var t=void 0,n=arguments;return 0!==e.offsetWidth?t=h.apply(void 0,n):p(e,A,function(){t=h.apply(void 0,n)}),t}function v(e,t,n){var r=n;{if("object"!==("undefined"==typeof t?"undefined":b(t)))return"undefined"!=typeof r?("number"==typeof r&&(r+="px"),void(e.style[t]=r)):S(e,t);for(var o in t)t.hasOwnProperty(o)&&v(e,o,t[o])}}function m(e,t){"static"===v(e,"position")&&(e.style.position="relative");var n=i(e),r={},o=void 0,a=void 0;for(a in t)t.hasOwnProperty(a)&&(o=parseFloat(v(e,a))||0,r[a]=o+t[a]-n[a]);v(e,r)}var g=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},b="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=/[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,O=new RegExp("^("+P+")(?!px)[a-z%]+$","i"),C=/^(top|right|bottom|left)$/,T="currentStyle",w="runtimeStyle",x="left",E="px",S=void 0;"undefined"!=typeof window&&(S=window.getComputedStyle?s:l);var k=["margin","border","padding"],j=-1,_=2,N=1,M=0,D={};u(["Width","Height"],function(e){D["doc"+e]=function(t){var n=t.document;return Math.max(n.documentElement["scroll"+e],n.body["scroll"+e],D["viewport"+e](n))},D["viewport"+e]=function(t){var n="client"+e,r=t.document,o=r.body,a=r.documentElement,i=a[n];return"CSS1Compat"===r.compatMode&&i||o&&o[n]||i}});var A={position:"absolute",visibility:"hidden",display:"block"};u(["width","height"],function(e){var t=e.charAt(0).toUpperCase()+e.slice(1);D["outer"+t]=function(t,n){return t&&y(t,e,n?M:N)};var n="width"===e?["Left","Right"]:["Top","Bottom"];D[e]=function(t,r){if(void 0===r)return t&&y(t,e,j);if(t){var o=S(t),a=c(t);return a&&(r+=f(t,["padding","border"],n,o)),v(t,e,r)}}}),e.exports=g({getWindow:function(e){var t=e.ownerDocument||e;return t.defaultView||t.parentWindow},offset:function(e,t){return"undefined"==typeof t?i(e):void m(e,t)},isWindow:d,each:u,css:v,clone:function(e){var t={};for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n]);var r=e.overflow;if(r)for(var n in e)e.hasOwnProperty(n)&&(t.overflow[n]=e.overflow[n]);return t},scrollLeft:function(e,t){if(d(e)){if(void 0===t)return o(e);window.scrollTo(t,a(e))}else{if(void 0===t)return e.scrollLeft;e.scrollLeft=t}},scrollTop:function(e,t){if(d(e)){if(void 0===t)return a(e);window.scrollTo(o(e),t)}else{if(void 0===t)return e.scrollTop;e.scrollTop=t}},viewportWidth:0,viewportHeight:0},D)},function(e,t,n){var r;!function(o,a,i){var s=window.matchMedia;"undefined"!=typeof e&&e.exports?e.exports=i(s):(r=function(){return a[o]=i(s)}.call(t,n,t,e),!(void 0!==r&&(e.exports=r)))}("enquire",this,function(e){"use strict";function t(e,t){var n,r=0,o=e.length;for(r;o>r&&(n=t(e[r],r),n!==!1);r++);}function n(e){return"[object Array]"===Object.prototype.toString.apply(e)}function r(e){return"function"==typeof e}function o(e){this.options=e,!e.deferSetup&&this.setup()}function a(t,n){this.query=t,this.isUnconditional=n,this.handlers=[],this.mql=e(t);var r=this;this.listener=function(e){r.mql=e,r.assess()},this.mql.addListener(this.listener)}function i(){if(!e)throw new Error("matchMedia not present, legacy browsers require a polyfill");this.queries={},this.browserIsIncapable=!e("only all").matches}return o.prototype={setup:function(){this.options.setup&&this.options.setup(),this.initialised=!0},on:function(){!this.initialised&&this.setup(),this.options.match&&this.options.match()},off:function(){this.options.unmatch&&this.options.unmatch()},destroy:function(){this.options.destroy?this.options.destroy():this.off()},equals:function(e){return this.options===e||this.options.match===e}},a.prototype={addHandler:function(e){var t=new o(e);this.handlers.push(t),this.matches()&&t.on()},removeHandler:function(e){var n=this.handlers;t(n,function(t,r){return t.equals(e)?(t.destroy(),!n.splice(r,1)):void 0})},matches:function(){return this.mql.matches||this.isUnconditional},clear:function(){t(this.handlers,function(e){e.destroy()}),this.mql.removeListener(this.listener),this.handlers.length=0},assess:function(){var e=this.matches()?"on":"off";t(this.handlers,function(t){t[e]()})}},i.prototype={register:function(e,o,i){var s=this.queries,l=i&&this.browserIsIncapable;return s[e]||(s[e]=new a(e,l)),r(o)&&(o={match:o}),n(o)||(o=[o]),t(o,function(t){s[e].addHandler(t)}),this},unregister:function(e,t){var n=this.queries[e];return n&&(t?n.removeHandler(t):(n.clear(),delete this.queries[e])),this}},new i})},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),a=Object.keys(t);if(r.length!==a.length)return!1;for(var i=0;i<r.length;i++)if(!o.call(t,r[i])||!n(e[r[i]],t[r[i]]))return!1;return!0}var o=Object.prototype.hasOwnProperty;e.exports=r},17,function(e,t,n){"use strict";function r(e,t,n){return n+(h.isLeapYear(e)?u[t]:l[t])}function o(e){return e>=0?e%7:h.mod(e,7)}function a(e){var t=void 0,n=void 0,r=void 0,o=void 0,a=void 0,i=void 0,l=void 0,u=void 0,y=void 0;return t=e-1,a=s(t/d),n=h.mod(t,d),i=s(n/f),r=h.mod(n,f),l=s(r/p),o=h.mod(r,p),u=s(o/c),y=400*a+100*i+4*l+u,4!==i&&4!==u&&++y,y}var i=n(78),s=Math.floor,l=[0,31,59,90,120,151,181,212,243,273,304,334],u=[0,31,60,91,121,152,182,213,244,274,305,335],c=365,p=1461,f=25*p-1,d=4*f+1,h={};h=e.exports={each:function(e,t){for(var n=0,r=e.length;r>n&&t(e[n],n,e)!==!1;n++);},mix:function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},isLeapYear:function(e){return 0!==(3&e)?!1:e%100!==0||e%400===0},mod:function(e,t){return e-t*s(e/t)},getFixedDate:function(e,t,n){var o=e-1;return c*o+s(o/4)-s(o/100)+s(o/400)+r(e,t,n)},getGregorianDateFromFixedDate:function(e){for(var t=a(e),n=h.getFixedDate(t,i.JANUARY,1),r=h.isLeapYear(t),s=r?u:l,c=e-n,p=void 0,f=0;f<s.length&&s[f]<=c;f++)p=f;var d=e-n-s[p]+1,y=o(e);return{year:t,month:p,dayOfMonth:d,dayOfWeek:y,isLeap:r}}}},function(e,t){"use strict";var n={childContextTypes:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,mixins:!0,propTypes:!0,type:!0},r={name:!0,length:!0,prototype:!0,caller:!0,arguments:!0,arity:!0};e.exports=function(e,t){if("string"!=typeof t)for(var o=Object.getOwnPropertyNames(t),a=0;a<o.length;++a)if(!n[o[a]]&&!r[o[a]])try{e[o[a]]=t[o[a]]}catch(i){}return e}},function(e,t,n){(function(e,n){function r(e,t){return e.set(t[0],t[1]),e}function o(e,t){return e.add(t),e}function a(e,t){for(var n=-1,r=e.length;++n<r&&t(e[n],n,e)!==!1;);return e}function i(e,t){for(var n=-1,r=t.length,o=e.length;++n<r;)e[o+n]=t[n];return e}function s(e,t,n,r){var o=-1,a=e.length;for(r&&a&&(n=e[++o]);++o<a;)n=t(n,e[o],o,e);return n}function l(e,t){for(var n=-1,r=Array(e);++n<e;)r[n]=t(n);return r}function u(e){return e&&e.Object===Object?e:null}function c(e){var t=!1;if(null!=e&&"function"!=typeof e.toString)try{t=!!(e+"")}catch(n){}return t}function p(e){var t=-1,n=Array(e.size);return e.forEach(function(e,r){n[++t]=[r,e]}),n}function f(e){var t=-1,n=Array(e.size);return e.forEach(function(e){n[++t]=e}),n}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 h(){this.__data__=Rt?Rt(null):{}}function y(e){return this.has(e)&&delete this.__data__[e]}function v(e){var t=this.__data__;if(Rt){var n=t[e];return n===_e?void 0:n}return Ct.call(t,e)?t[e]:void 0}function m(e){var t=this.__data__;return Rt?void 0!==t[e]:Ct.call(t,e)}function g(e,t){var n=this.__data__;return n[e]=Rt&&void 0===t?_e:t,this}function b(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 P(){this.__data__=[]}function O(e){var t=this.__data__,n=I(t,e);if(0>n)return!1;var r=t.length-1;return n==r?t.pop():Nt.call(t,n,1),!0}function C(e){var t=this.__data__,n=I(t,e);return 0>n?void 0:t[n][1]}function T(e){return I(this.__data__,e)>-1}function w(e,t){var n=this.__data__,r=I(n,e);return 0>r?n.push([e,t]):n[r][1]=t,this}function x(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 E(){this.__data__={hash:new d,map:new(Lt||b),string:new d}}function S(e){return oe(this,e)["delete"](e)}function k(e){return oe(this,e).get(e)}function j(e){return oe(this,e).has(e)}function _(e,t){return oe(this,e).set(e,t),this}function N(e){this.__data__=new b(e)}function M(){this.__data__=new b}function D(e){return this.__data__["delete"](e)}function A(e){return this.__data__.get(e)}function L(e){return this.__data__.has(e)}function V(e,t){var n=this.__data__;return n instanceof b&&n.__data__.length==je&&(n=this.__data__=new x(n.__data__)),n.set(e,t),this}function F(e,t,n){var r=e[t];Ct.call(e,t)&&me(r,n)&&(void 0!==n||t in e)||(e[t]=n)}function I(e,t){for(var n=e.length;n--;)if(me(e[n][0],t))return n;return-1}function R(e,t){return e&&te(t,Se(t),e)}function K(e,t,n,r,o,i,s){var l;if(r&&(l=i?r(e,o,i,s):r(e)),void 0!==l)return l;if(!Te(e))return e;var u=Gt(e);if(u){if(l=ue(e),!t)return ee(e,l)}else{var p=le(e),f=p==Fe||p==Ie;if(Xt(e))return Y(e,t);if(p==We||p==Me||f&&!i){if(c(e))return i?e:{};if(l=ce(f?{}:e),!t)return ne(e,R(l,e))}else{if(!ut[p])return i?e:{};l=pe(e,p,K,t)}}s||(s=new N);var d=s.get(e);if(d)return d;if(s.set(e,l),!u)var h=n?re(e):Se(e);return a(h||e,function(o,a){h&&(a=o,o=e[a]),F(l,a,K(o,t,n,r,a,e,s))}),l}function W(e){return Te(e)?jt(e):{}}function H(e,t,n){var r=t(e);return Gt(e)?r:i(r,n(e))}function z(e,t){return Ct.call(e,t)||"object"==typeof e&&t in e&&null===ie(e)}function B(e){return Dt(Object(e))}function U(e){return function(t){return null==t?void 0:t[e]}}function Y(e,t){if(t)return e.slice();var n=new e.constructor(e.length);return e.copy(n),n}function q(e){var t=new e.constructor(e.byteLength);return new St(t).set(new St(e)),t}function G(e,t){var n=t?q(e.buffer):e.buffer;return new e.constructor(n,e.byteOffset,e.byteLength)}function X(e,t,n){var o=t?n(p(e),!0):p(e);return s(o,r,new e.constructor)}function $(e){var t=new e.constructor(e.source,it.exec(e));return t.lastIndex=e.lastIndex,t}function Q(e,t,n){var r=t?n(f(e),!0):f(e);return s(r,o,new e.constructor)}function Z(e){return Yt?Object(Yt.call(e)):{}}function J(e,t){var n=t?q(e.buffer):e.buffer;return new e.constructor(n,e.byteOffset,e.length)}function ee(e,t){var n=-1,r=e.length;for(t||(t=Array(r));++n<r;)t[n]=e[n];return t}function te(e,t,n,r){n||(n={});for(var o=-1,a=t.length;++o<a;){var i=t[o],s=r?r(n[i],e[i],i,n,e):e[i];F(n,i,s)}return n}function ne(e,t){return te(e,se(e),t)}function re(e){return H(e,Se,se)}function oe(e,t){var n=e.__data__;return he(t)?n["string"==typeof t?"string":"hash"]:n.map}function ae(e,t){var n=e[t];return xe(n)?n:void 0}function ie(e){return Mt(Object(e))}function se(e){return kt(Object(e))}function le(e){return Tt.call(e)}function ue(e){var t=e.length,n=e.constructor(t);return t&&"string"==typeof e[0]&&Ct.call(e,"index")&&(n.index=e.index,n.input=e.input),n}function ce(e){return"function"!=typeof e.constructor||ye(e)?{}:W(ie(e))}function pe(e,t,n,r){var o=e.constructor;switch(t){case Ge:return q(e);case Ae:case Le:return new o(+e);case Xe:return G(e,r);case $e:case Qe:case Ze:case Je:case et:case tt:case nt:case rt:case ot:return J(e,r);case Re:return X(e,r,n);case Ke:case Ue:return new o(e);case ze:return $(e);case Be:return Q(e,r,n);case Ye:return Z(e)}}function fe(e){var t=e?e.length:void 0;return Ce(t)&&(Gt(e)||Ee(e)||ge(e))?l(t,String):null}function de(e,t){return t=null==t?Ne:t,!!t&&("number"==typeof e||lt.test(e))&&e>-1&&e%1==0&&t>e}function he(e){var t=typeof e;return"string"==t||"number"==t||"symbol"==t||"boolean"==t?"__proto__"!==e:null===e}function ye(e){var t=e&&e.constructor,n="function"==typeof t&&t.prototype||Pt;return e===n}function ve(e){if(null!=e){try{return Ot.call(e)}catch(t){}try{return e+""}catch(t){}}return""}function me(e,t){return e===t||e!==e&&t!==t}function ge(e){return Pe(e)&&Ct.call(e,"callee")&&(!_t.call(e,"callee")||Tt.call(e)==Me)}function be(e){return null!=e&&Ce(qt(e))&&!Oe(e)}function Pe(e){return we(e)&&be(e)}function Oe(e){var t=Te(e)?Tt.call(e):"";return t==Fe||t==Ie}function Ce(e){return"number"==typeof e&&e>-1&&e%1==0&&Ne>=e; }function Te(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function we(e){return!!e&&"object"==typeof e}function xe(e){if(!Te(e))return!1;var t=Oe(e)||c(e)?wt:st;return t.test(ve(e))}function Ee(e){return"string"==typeof e||!Gt(e)&&we(e)&&Tt.call(e)==Ue}function Se(e){var t=ye(e);if(!t&&!be(e))return B(e);var n=fe(e),r=!!n,o=n||[],a=o.length;for(var i in e)!z(e,i)||r&&("length"==i||de(i,a))||t&&"constructor"==i||o.push(i);return o}function ke(e){return function(){return e}}var je=200,_e="__lodash_hash_undefined__",Ne=9007199254740991,Me="[object Arguments]",De="[object Array]",Ae="[object Boolean]",Le="[object Date]",Ve="[object Error]",Fe="[object Function]",Ie="[object GeneratorFunction]",Re="[object Map]",Ke="[object Number]",We="[object Object]",He="[object Promise]",ze="[object RegExp]",Be="[object Set]",Ue="[object String]",Ye="[object Symbol]",qe="[object WeakMap]",Ge="[object ArrayBuffer]",Xe="[object DataView]",$e="[object Float32Array]",Qe="[object Float64Array]",Ze="[object Int8Array]",Je="[object Int16Array]",et="[object Int32Array]",tt="[object Uint8Array]",nt="[object Uint8ClampedArray]",rt="[object Uint16Array]",ot="[object Uint32Array]",at=/[\\^$.*+?()[\]{}|]/g,it=/\w*$/,st=/^\[object .+?Constructor\]$/,lt=/^(?:0|[1-9]\d*)$/,ut={};ut[Me]=ut[De]=ut[Ge]=ut[Xe]=ut[Ae]=ut[Le]=ut[$e]=ut[Qe]=ut[Ze]=ut[Je]=ut[et]=ut[Re]=ut[Ke]=ut[We]=ut[ze]=ut[Be]=ut[Ue]=ut[Ye]=ut[tt]=ut[nt]=ut[rt]=ut[ot]=!0,ut[Ve]=ut[Fe]=ut[qe]=!1;var ct={"function":!0,object:!0},pt=ct[typeof t]&&t&&!t.nodeType?t:void 0,ft=ct[typeof e]&&e&&!e.nodeType?e:void 0,dt=ft&&ft.exports===pt?pt:void 0,ht=u(pt&&ft&&"object"==typeof n&&n),yt=u(ct[typeof self]&&self),vt=u(ct[typeof window]&&window),mt=u(ct[typeof this]&&this),gt=ht||vt!==(mt&&mt.window)&&vt||yt||mt||Function("return this")(),bt=Array.prototype,Pt=Object.prototype,Ot=Function.prototype.toString,Ct=Pt.hasOwnProperty,Tt=Pt.toString,wt=RegExp("^"+Ot.call(Ct).replace(at,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),xt=dt?gt.Buffer:void 0,Et=gt.Symbol,St=gt.Uint8Array,kt=Object.getOwnPropertySymbols,jt=Object.create,_t=Pt.propertyIsEnumerable,Nt=bt.splice,Mt=Object.getPrototypeOf,Dt=Object.keys,At=ae(gt,"DataView"),Lt=ae(gt,"Map"),Vt=ae(gt,"Promise"),Ft=ae(gt,"Set"),It=ae(gt,"WeakMap"),Rt=ae(Object,"create"),Kt=ve(At),Wt=ve(Lt),Ht=ve(Vt),zt=ve(Ft),Bt=ve(It),Ut=Et?Et.prototype:void 0,Yt=Ut?Ut.valueOf:void 0;d.prototype.clear=h,d.prototype["delete"]=y,d.prototype.get=v,d.prototype.has=m,d.prototype.set=g,b.prototype.clear=P,b.prototype["delete"]=O,b.prototype.get=C,b.prototype.has=T,b.prototype.set=w,x.prototype.clear=E,x.prototype["delete"]=S,x.prototype.get=k,x.prototype.has=j,x.prototype.set=_,N.prototype.clear=M,N.prototype["delete"]=D,N.prototype.get=A,N.prototype.has=L,N.prototype.set=V;var qt=U("length");kt||(se=function(){return[]}),(At&&le(new At(new ArrayBuffer(1)))!=Xe||Lt&&le(new Lt)!=Re||Vt&&le(Vt.resolve())!=He||Ft&&le(new Ft)!=Be||It&&le(new It)!=qe)&&(le=function(e){var t=Tt.call(e),n=t==We?e.constructor:void 0,r=n?ve(n):void 0;if(r)switch(r){case Kt:return Xe;case Wt:return Re;case Ht:return He;case zt:return Be;case Bt:return qe}return t});var Gt=Array.isArray,Xt=xt?function(e){return e instanceof xt}:ke(!1);e.exports=K}).call(t,n(44)(e),function(){return this}())},function(e,t){function n(e){return!!e&&"object"==typeof e}function r(e,t){var n=null==e?void 0:e[t];return i(n)?n:void 0}function o(e){return a(e)&&f.call(e)==s}function a(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function i(e){return null==e?!1:o(e)?d.test(c.call(e)):n(e)&&l.test(e)}var s="[object Function]",l=/^\[object .+?Constructor\]$/,u=Object.prototype,c=Function.prototype.toString,p=u.hasOwnProperty,f=u.toString,d=RegExp("^"+c.call(p).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");e.exports=r},function(e,t,n){(function(e,n){function r(e){return e&&e.Object===Object?e:null}var o={"function":!0,object:!0},a=o[typeof t]&&t&&!t.nodeType?t:void 0,i=o[typeof e]&&e&&!e.nodeType?e:void 0,s=r(a&&i&&"object"==typeof n&&n),l=r(o[typeof self]&&self),u=r(o[typeof window]&&window),c=r(o[typeof this]&&this),p=s||u!==(c&&c.window)&&u||l||c||Function("return this")();e.exports=p}).call(t,n(44)(e),function(){return this}())},function(e,t){function n(e){return function(t){return null==t?void 0:t[e]}}function r(e){return a(e)&&y.call(e,"callee")&&(!m.call(e,"callee")||v.call(e)==p)}function o(e){return null!=e&&s(g(e))&&!i(e)}function a(e){return u(e)&&o(e)}function i(e){var t=l(e)?v.call(e):"";return t==f||t==d}function s(e){return"number"==typeof e&&e>-1&&e%1==0&&c>=e}function l(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function u(e){return!!e&&"object"==typeof e}var c=9007199254740991,p="[object Arguments]",f="[object Function]",d="[object GeneratorFunction]",h=Object.prototype,y=h.hasOwnProperty,v=h.toString,m=h.propertyIsEnumerable,g=n("length");e.exports=r},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&&m>=e}function a(e){return i(e)&&h.call(e)==u}function i(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function s(e){return null==e?!1:a(e)?y.test(f.call(e)):n(e)&&c.test(e)}var l="[object Array]",u="[object Function]",c=/^\[object .+?Constructor\]$/,p=Object.prototype,f=Function.prototype.toString,d=p.hasOwnProperty,h=p.toString,y=RegExp("^"+f.call(d).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),v=r(Array,"isArray"),m=9007199254740991,g=v||function(e){return n(e)&&o(e.length)&&h.call(e)==l};e.exports=g},function(e,t){function n(e){var t=!1;if(null!=e&&"function"!=typeof e.toString)try{t=!!(e+"")}catch(n){}return t}function r(e){return f(Object(e))}function o(e){return!!e&&"object"==typeof e}function a(e){if(!o(e)||p.call(e)!=i||n(e))return!1;var t=r(e);if(null===t)return!0;var a=u.call(t,"constructor")&&t.constructor;return"function"==typeof a&&a instanceof a&&l.call(a)==c}var i="[object Object]",s=Object.prototype,l=Function.prototype.toString,u=s.hasOwnProperty,c=l.call(Object),p=s.toString,f=Object.getPrototypeOf;e.exports=a},function(e,t,n){function r(e){return function(t){return null==t?void 0:t[e]}}function o(e){return null!=e&&i(g(e))}function a(e,t){return e="number"==typeof e||d.test(e)?+e:-1,t=null==t?m:t,e>-1&&e%1==0&&t>e}function i(e){return"number"==typeof e&&e>-1&&e%1==0&&m>=e}function s(e){for(var t=u(e),n=t.length,r=n&&e.length,o=!!r&&i(r)&&(f(e)||p(e)),s=-1,l=[];++s<n;){var c=t[s];(o&&a(c,r)||y.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&&i(t)&&(f(e)||p(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&&a(c,t)||"constructor"==c&&(o||!y.call(e,c))||s.push(c);return s}var c=n(267),p=n(269),f=n(270),d=/^\d+$/,h=Object.prototype,y=h.hasOwnProperty,v=c(Object,"keys"),m=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){(function(e,n){function r(e,t){for(var n=-1,r=Array(e);++n<e;)r[n]=t(n);return r}function o(e){return e&&e.Object===Object?e:null}function a(e){for(var t,n=[];!(t=e.next()).done;)n.push(t.value);return n}function i(e){e=null==e?e:Object(e);var t=[];for(var n in e)t.push(n);return t}function s(e){return function(t){return null==t?void 0:t[e]}}function l(e){var t=e?e.length:void 0;return y(t)&&(W(e)||g(e)||p(e))?r(t,String):null}function u(e,t){return t=null==t?P:t,!!t&&("number"==typeof e||x.test(e))&&e>-1&&e%1==0&&t>e}function c(e){var t=e&&e.constructor,n="function"==typeof t&&t.prototype||A;return e===n}function p(e){return d(e)&&L.call(e,"callee")&&(!R.call(e,"callee")||V.call(e)==O)}function f(e){return null!=e&&y(K(e))&&!h(e)}function d(e){return m(e)&&f(e)}function h(e){var t=v(e)?V.call(e):"";return t==C||t==T}function y(e){return"number"==typeof e&&e>-1&&e%1==0&&P>=e}function v(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function m(e){return!!e&&"object"==typeof e}function g(e){return"string"==typeof e||!W(e)&&m(e)&&V.call(e)==w}function b(e){for(var t=-1,n=c(e),r=i(e),o=r.length,a=l(e),s=!!a,p=a||[],f=p.length;++t<o;){var d=r[t];s&&("length"==d||u(d,f))||"constructor"==d&&(n||!L.call(e,d))||p.push(d)}return p}var P=9007199254740991,O="[object Arguments]",C="[object Function]",T="[object GeneratorFunction]",w="[object String]",x=/^(?:0|[1-9]\d*)$/,E={"function":!0,object:!0},S=E[typeof t]&&t&&!t.nodeType?t:void 0,k=E[typeof e]&&e&&!e.nodeType?e:void 0,j=o(S&&k&&"object"==typeof n&&n),_=o(E[typeof self]&&self),N=o(E[typeof window]&&window),M=o(E[typeof this]&&this),D=j||N!==(M&&M.window)&&N||_||M||Function("return this")(),A=Object.prototype,L=A.hasOwnProperty,V=A.toString,F=D.Reflect,I=F?F.enumerate:void 0,R=A.propertyIsEnumerable;I&&!R.call({valueOf:1},"valueOf")&&(i=function(e){return a(I(e))});var K=s("length"),W=Array.isArray;e.exports=b}).call(t,n(44)(e),function(){return this}())},function(e,t,n){function r(e,t){for(var n=-1,r=e.length;++n<r&&t(e[n],n,e)!==!1;);return e}function o(e){var t=!1;if(null!=e&&"function"!=typeof e.toString)try{t=!!(e+"")}catch(n){}return t}function a(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 i(){this.__data__=qe?qe(null):{}}function s(e){return this.has(e)&&delete this.__data__[e]}function l(e){var t=this.__data__;if(qe){var n=t[e];return n===se?void 0:n}return We.call(t,e)?t[e]:void 0}function u(e){var t=this.__data__;return qe?void 0!==t[e]:We.call(t,e)}function c(e,t){var n=this.__data__;return n[e]=qe&&void 0===t?se:t,this}function p(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 f(){this.__data__=[]}function d(e){var t=this.__data__,n=N(t,e);if(0>n)return!1;var r=t.length-1;return n==r?t.pop():Ue.call(t,n,1),!0}function h(e){var t=this.__data__,n=N(t,e);return 0>n?void 0:t[n][1]}function y(e){return N(this.__data__,e)>-1}function v(e,t){var n=this.__data__,r=N(n,e);return 0>r?n.push([e,t]):n[r][1]=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 g(){this.__data__={hash:new a,map:new(Ye||p),string:new a}}function b(e){return I(this,e)["delete"](e)}function P(e){return I(this,e).get(e)}function O(e){return I(this,e).has(e)}function C(e,t){return I(this,e).set(e,t),this}function T(e){this.__data__=new p(e)}function w(){this.__data__=new p}function x(e){return this.__data__["delete"](e)}function E(e){return this.__data__.get(e)}function S(e){return this.__data__.has(e)}function k(e,t){var n=this.__data__;return n instanceof p&&n.__data__.length==ie&&(n=this.__data__=new m(n.__data__)),n.set(e,t),this}function j(e,t,n){(void 0===n||B(e[t],n))&&("number"!=typeof t||void 0!==n||t in e)||(e[t]=n)}function _(e,t,n){var r=e[t];We.call(e,t)&&B(r,n)&&(void 0!==n||t in e)||(e[t]=n)}function N(e,t){for(var n=e.length;n--;)if(B(e[n][0],t))return n;return-1}function M(e,t,n,o,a){if(e!==t){if(!Xe(t)&&!J(t))var i=re(t);r(i||t,function(r,s){if(i&&(s=r,r=t[s]),$(r))a||(a=new T),D(e,t,s,n,M,o,a);else{var l=o?o(e[s],r,s+"",e,t,a):void 0;void 0===l&&(l=r),j(e,s,l)}})}}function D(e,t,n,r,o,a,i){var s=e[n],l=t[n],u=i.get(l);if(u)return void j(e,n,u);var c=a?a(s,l,n+"",e,t,i):void 0,p=void 0===c;p&&(c=l,Xe(l)||J(l)?Xe(s)?c=s:q(s)?c=L(s):(p=!1,c=te(l,!0)):ne(l)||U(l)?U(s)?c=ee(s):!$(s)||r&&G(s)?(p=!1,c=te(l,!0)):c=s:p=!1),i.set(l,c),p&&o(c,l,r,a,i),i["delete"](l),j(e,n,c)}function A(e){return function(t){return null==t?void 0:t[e]}}function L(e,t){var n=-1,r=e.length;for(t||(t=Array(r));++n<r;)t[n]=e[n];return t}function V(e,t,n,r){n||(n={});for(var o=-1,a=t.length;++o<a;){var i=t[o],s=r?r(n[i],e[i],i,n,e):e[i];_(n,i,s)}return n}function F(e){return oe(function(t,n){var r=-1,o=n.length,a=o>1?n[o-1]:void 0,i=o>2?n[2]:void 0;for(a=e.length>3&&"function"==typeof a?(o--,a):void 0,i&&W(n[0],n[1],i)&&(a=3>o?void 0:a,o=1),t=Object(t);++r<o;){var s=n[r];s&&e(t,s,r,a)}return t})}function I(e,t){var n=e.__data__;return H(t)?n["string"==typeof t?"string":"hash"]:n.map}function R(e,t){var n=e[t];return Z(n)?n:void 0}function K(e,t){return t=null==t?le:t,!!t&&("number"==typeof e||Ve.test(e))&&e>-1&&e%1==0&&t>e}function W(e,t,n){if(!$(n))return!1;var r=typeof t;return("number"==r?Y(n)&&K(t,n.length):"string"==r&&t in n)?B(n[t],e):!1}function H(e){var t=typeof e;return"string"==t||"number"==t||"symbol"==t||"boolean"==t?"__proto__"!==e:null===e}function z(e){if(null!=e){try{return Ke.call(e)}catch(t){}try{return e+""}catch(t){}}return""}function B(e,t){return e===t||e!==e&&t!==t}function U(e){return q(e)&&We.call(e,"callee")&&(!Be.call(e,"callee")||He.call(e)==ue)}function Y(e){return null!=e&&X(Ge(e))&&!G(e)}function q(e){return Q(e)&&Y(e)}function G(e){var t=$(e)?He.call(e):"";return t==he||t==ye}function X(e){return"number"==typeof e&&e>-1&&e%1==0&&le>=e}function $(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function Q(e){return!!e&&"object"==typeof e}function Z(e){if(!$(e))return!1;var t=G(e)||o(e)?ze:Le;return t.test(z(e))}function J(e){return Q(e)&&X(e.length)&&!!Fe[He.call(e)]}function ee(e){return V(e,re(e))}var te=n(266),ne=n(271),re=n(273),oe=n(275),ae=n(268),ie=200,se="__lodash_hash_undefined__",le=9007199254740991,ue="[object Arguments]",ce="[object Array]",pe="[object Boolean]",fe="[object Date]",de="[object Error]",he="[object Function]",ye="[object GeneratorFunction]",ve="[object Map]",me="[object Number]",ge="[object Object]",be="[object RegExp]",Pe="[object Set]",Oe="[object String]",Ce="[object WeakMap]",Te="[object ArrayBuffer]",we="[object DataView]",xe="[object Float32Array]",Ee="[object Float64Array]",Se="[object Int8Array]",ke="[object Int16Array]",je="[object Int32Array]",_e="[object Uint8Array]",Ne="[object Uint8ClampedArray]",Me="[object Uint16Array]",De="[object Uint32Array]",Ae=/[\\^$.*+?()[\]{}|]/g,Le=/^\[object .+?Constructor\]$/,Ve=/^(?:0|[1-9]\d*)$/,Fe={};Fe[xe]=Fe[Ee]=Fe[Se]=Fe[ke]=Fe[je]=Fe[_e]=Fe[Ne]=Fe[Me]=Fe[De]=!0,Fe[ue]=Fe[ce]=Fe[Te]=Fe[pe]=Fe[we]=Fe[fe]=Fe[de]=Fe[he]=Fe[ve]=Fe[me]=Fe[ge]=Fe[be]=Fe[Pe]=Fe[Oe]=Fe[Ce]=!1;var Ie=Array.prototype,Re=Object.prototype,Ke=Function.prototype.toString,We=Re.hasOwnProperty,He=Re.toString,ze=RegExp("^"+Ke.call(We).replace(Ae,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Be=Re.propertyIsEnumerable,Ue=Ie.splice,Ye=R(ae,"Map"),qe=R(Object,"create");a.prototype.clear=i,a.prototype["delete"]=s,a.prototype.get=l,a.prototype.has=u,a.prototype.set=c,p.prototype.clear=f,p.prototype["delete"]=d,p.prototype.get=h,p.prototype.has=y,p.prototype.set=v,m.prototype.clear=g,m.prototype["delete"]=b,m.prototype.get=P,m.prototype.has=O,m.prototype.set=C,T.prototype.clear=w,T.prototype["delete"]=x,T.prototype.get=E,T.prototype.has=S,T.prototype.set=k;var Ge=A("length"),Xe=Array.isArray,$e=F(function(e,t,n,r){M(e,t,n,r)});e.exports=$e},function(e,t){function n(e,t,n){var r=n.length;switch(r){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)}function r(e,t){if("function"!=typeof e)throw new TypeError(p);return t=x(void 0===t?e.length-1:u(t),0),function(){for(var r=arguments,o=-1,a=x(r.length-t,0),i=Array(a);++o<a;)i[o]=r[t+o];switch(t){case 0:return e.call(this,i);case 1:return e.call(this,r[0],i);case 2:return e.call(this,r[0],r[1],i)}var s=Array(t+1);for(o=-1;++o<t;)s[o]=r[o];return s[t]=i,n(e,this,s)}}function o(e){var t=a(e)?w.call(e):"";return t==y||t==v}function a(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function i(e){return!!e&&"object"==typeof e}function s(e){return"symbol"==typeof e||i(e)&&w.call(e)==m}function l(e){if(!e)return 0===e?e:0;if(e=c(e),e===f||e===-f){var t=0>e?-1:1;return t*d}return e===e?e:0}function u(e){var t=l(e),n=t%1;return t===t?n?t-n:t:0}function c(e){if("number"==typeof e)return e;if(s(e))return h;if(a(e)){var t=o(e.valueOf)?e.valueOf():e;e=a(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=e.replace(g,"");var n=P.test(e);return n||O.test(e)?C(e.slice(2),n?2:8):b.test(e)?h:+e}var p="Expected a function",f=1/0,d=1.7976931348623157e308,h=NaN,y="[object Function]",v="[object GeneratorFunction]",m="[object Symbol]",g=/^\s+|\s+$/g,b=/^[-+]0x[0-9a-f]+$/i,P=/^0b[01]+$/i,O=/^0o[0-7]+$/i,C=parseInt,T=Object.prototype,w=T.toString,x=Math.max;e.exports=r},function(e,t,n){var r,o,a;!function(n,i){"use strict";"object"==typeof e&&"object"==typeof e.exports?e.exports=i():(o=[],r=i,a="function"==typeof r?r.apply(t,o):r,!(void 0!==a&&(e.exports=a)))}(this,function(){"use strict";function e(e){if(!e)return!0;if(a(e)&&0===e.length)return!0;if(!r(e)){for(var t in e)if(p.call(e,t))return!1;return!0}return!1}function t(e){return c.call(e)}function n(e){return"number"==typeof e||"[object Number]"===t(e)}function r(e){return"string"==typeof e||"[object String]"===t(e)}function o(e){return"object"==typeof e&&"[object Object]"===t(e)}function a(e){return"object"==typeof e&&"number"==typeof e.length&&"[object Array]"===t(e)}function i(e){return"boolean"==typeof e||"[object Boolean]"===t(e)}function s(e){var t=parseInt(e);return t.toString()===e?t:e}function l(t,o,a,i){if(n(o)&&(o=[o]),e(o))return t;if(r(o))return l(t,o.split(".").map(s),a,i);var u=o[0];if(1===o.length){var c=t[u];return void 0!==c&&i||(t[u]=a),c}return void 0===t[u]&&(n(o[1])?t[u]=[]:t[u]={}),l(t[u],o.slice(1),a,i)}function u(t,o){if(n(o)&&(o=[o]),!e(t)){if(e(o))return t;if(r(o))return u(t,o.split("."));var i=s(o[0]),l=t[i];if(1===o.length)void 0!==l&&(a(t)?t.splice(i,1):delete t[i]);else if(void 0!==t[i])return u(t[i],o.slice(1));return t}}var c=Object.prototype.toString,p=Object.prototype.hasOwnProperty,f=function(e){return Object.keys(f).reduce(function(t,n){return"function"==typeof f[n]&&(t[n]=f[n].bind(f,e)),t},{})};return f.has=function(t,i){if(e(t))return!1;if(n(i)?i=[i]:r(i)&&(i=i.split(".")),e(i)||0===i.length)return!1;for(var s=0;s<i.length;s++){var l=i[s];if(!o(t)&&!a(t)||!p.call(t,l))return!1;t=t[l]}return!0},f.ensureExists=function(e,t,n){return l(e,t,n,!0)},f.set=function(e,t,n,r){return l(e,t,n,r)},f.insert=function(e,t,n,r){var o=f.get(e,t);r=~~r,a(o)||(o=[],f.set(e,t,o)),o.splice(r,0,n)},f.empty=function(t,s){if(e(s))return t;if(!e(t)){var l,u;if(!(l=f.get(t,s)))return t;if(r(l))return f.set(t,s,"");if(i(l))return f.set(t,s,!1);if(n(l))return f.set(t,s,0);if(a(l))l.length=0;else{if(!o(l))return f.set(t,s,null);for(u in l)p.call(l,u)&&delete l[u]}}},f.push=function(e,t){var n=f.get(e,t);a(n)||(n=[],f.set(e,t,n)),n.push.apply(n,Array.prototype.slice.call(arguments,2))},f.coalesce=function(e,t,n){for(var r,o=0,a=t.length;a>o;o++)if(void 0!==(r=f.get(e,t[o])))return r;return n},f.get=function(t,o,a){if(n(o)&&(o=[o]),e(o))return t;if(e(t))return a;if(r(o))return f.get(t,o.split("."),a);var i=s(o[0]);return 1===o.length?void 0===t[i]?a:t[i]:f.get(t[i],o.slice(1),a)},f.del=function(e,t){return u(e,t)},f})},function(e,t){function n(){p&&i&&(p=!1,i.length?c=i.concat(c):f=-1,c.length&&r())}function r(){if(!p){var e=l(n);p=!0;for(var t=c.length;t;){for(i=c,c=[];++f<t;)i&&i[f].run();f=-1,t=c.length}i=null,p=!1,u(e)}}function o(e,t){this.fun=e,this.array=t}function a(){}var i,s=e.exports={},l=setTimeout,u=clearTimeout,c=[],p=!1,f=-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];c.push(new o(e,t)),1!==c.length||p||l(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=a,s.addListener=a,s.once=a,s.off=a,s.removeListener=a,s.removeAllListeners=a,s.emit=a,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}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var n=void 0;return function(){n&&clearTimeout(n),n=setTimeout(e,t)}}Object.defineProperty(t,"__esModule",{value:!0});var a=n(1),i=r(a),s=n(4),l=r(s),u=n(258),c=r(u),p=n(6),f=n(280),d=r(f),h=i["default"].createClass({displayName:"Align",propTypes:{childrenProps:a.PropTypes.object,align:a.PropTypes.object.isRequired,target:a.PropTypes.func,onAlign:a.PropTypes.func,monitorBufferTime:a.PropTypes.number,monitorWindowResize:a.PropTypes.bool,disabled:a.PropTypes.bool,children:a.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,d["default"])(r)&&(0,d["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.resizeHandler=p.Dom.addEventListener(window,"resize",o(this.forceAlign,this.props.monitorBufferTime)))},stopMonitorWindowResize:function(){this.resizeHandler&&(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=i["default"].Children.only(n);if(t){var o={};for(var a in t)t.hasOwnProperty(a)&&(o[a]=this.props[t[a]]);return i["default"].cloneElement(r,o)}return r}});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(278),a=r(o);t["default"]=a["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 a(e){var t=e.children;return l["default"].isValidElement(t)&&!t.key?l["default"].cloneElement(t,{key:h}):t}function i(){}Object.defineProperty(t,"__esModule",{value:!0});var s=n(1),l=r(s),u=n(283),c=n(282),p=r(c),f=n(82),d=r(f),h="rc_animate_"+Date.now(),y=l["default"].createClass({displayName:"Animate",propTypes:{component:l["default"].PropTypes.any,animation:l["default"].PropTypes.object,transitionName:l["default"].PropTypes.string,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:i,onEnter:i,onLeave:i,onAppear:i}},getInitialState:function(){return this.currentlyAnimatingKeys={},this.keysToEnter=[],this.keysToLeave=[],{children:(0,u.toArrayChildren)(a(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){e.performAppear(t.key)})},componentWillReceiveProps:function(e){var t=this;this.nextProps=e;var n=(0,u.toArrayChildren)(a(e)),r=this.props;r.exclusive&&Object.keys(this.currentlyAnimatingKeys).forEach(function(e){t.stop(e)});var i=r.showProp,s=this.currentlyAnimatingKeys,c=r.exclusive?(0,u.toArrayChildren)(a(r)):this.state.children,p=[];i?(c.forEach(function(e){var t=(0,u.findChildInChildrenByKey)(n,e.key),r=void 0;r=t&&t.props[i]||!e.props[i]?t:l["default"].cloneElement(t||e,o({},i,!0)),r&&p.push(r)}),n.forEach(function(e){(0,u.findChildInChildrenByKey)(c,e.key)||p.push(e)})):p=(0,u.mergeChildren)(c,n),this.setState({children:p}),n.forEach(function(e){var n=e.key;if(!s[n]){var r=(0,u.findChildInChildrenByKey)(c,n);if(i){var o=e.props[i];if(r){var a=(0,u.findShownChildInChildrenByKey)(c,n,i);!a&&o&&t.keysToEnter.push(n)}else o&&t.keysToEnter.push(n)}else r||t.keysToEnter.push(n)}}),c.forEach(function(e){var r=e.key;if(!s[r]){var o=(0,u.findChildInChildrenByKey)(n,r);if(i){var a=e.props[i];if(o){var l=(0,u.findShownChildInChildrenByKey)(n,r,i);!l&&a&&t.keysToLeave.push(r)}else a&&t.keysToLeave.push(r)}else o||t.keysToLeave.push(r)}})},componentDidUpdate:function(){if(this.isMounted()){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)(a(n));this.isValidChildByKey(r,e)?"appear"===t?d["default"].allowAppearCallback(n)&&(n.onAppear(e),n.onEnd(e,!0)):d["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)(a(t));this.isValidChildByKey(n,e)?this.performEnter(e):(this.isMounted()&&!(0,u.isSameChildren)(this.state.children,n,t.showProp)&&this.setState({children:n}),d["default"].allowLeaveCallback(t)&&(t.onLeave(e),t.onEnd(e,!1)))}},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)return t;if(!t.key)throw new Error("must set key for <rc-animate> children");return l["default"].createElement(p["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;return r?l["default"].createElement(r,this.props,n):n[0]||null}});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),a=r(o),i=n(4),s=r(i),l=n(36),u=r(l),c=n(82),p=r(c),f={enter:"transitionEnter",appear:"transitionAppear",leave:"transitionLeave"},d=a["default"].createClass({displayName:"AnimateChild",propTypes:{children:a["default"].PropTypes.any},componentWillUnmount:function(){this.stop()},componentWillEnter:function(e){p["default"].isEnterSupported(this.props)?this.transition("enter",e):e()},componentWillAppear:function(e){p["default"].isAppearSupported(this.props)?this.transition("appear",e):e()},componentWillLeave:function(e){p["default"].isLeaveSupported(this.props)?this.transition("leave",e):e()},transition:function(e,t){var n=this,r=s["default"].findDOMNode(this),o=this.props,a=o.transitionName;this.stop();var i=function(){n.stopper=null,t()};(l.isCssAnimationSupported||!o.animation[e])&&a&&o[f[e]]?this.stopper=(0,u["default"])(r,a+"-"+e,i):this.stopper=o.animation[e](r,i)},stop:function(){var e=this.stopper;e&&(this.stopper=null,e.stop())},render:function(){return this.props.children}});t["default"]=d,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 p["default"].Children.forEach(e,function(e){t.push(e)}),t}function a(e,t){var n=null;return e&&e.forEach(function(e){n||e.key===t&&(n=e)}),n}function i(e,t,n){var r=null;return e&&e.forEach(function(e){if(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.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 a=t[o];e.key!==a.key?r=!1:n&&e.props[n]!==a.props[n]&&(r=!1)}),r}function u(e,t){var n=[],r={},o=[];return e.forEach(function(e){a(t,e.key)?o.length&&(r[e.key]=o,o=[]):o.push(e)}),t.forEach(function(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=a,t.findShownChildInChildrenByKey=i,t.findHiddenChildInChildrenByKey=s,t.isSameChildren=l,t.mergeChildren=u;var c=n(1),p=r(c)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){}function a(){var e=this.state.value.clone();e.setDayOfMonth(1),this.setValue(e)}function i(){var e=this.state.value.clone();e.setDayOfMonth(e.getActualMaximum(h["default"].MONTH)),this.setValue(e)}function s(e){var t=this.state.value.clone();t.addMonth(e),this.setValue(t)}function l(e){var t=this.state.value.clone();t.addYear(e),this.setValue(t)}function u(e){var t=this.state.value.clone();t.addWeekOfYear(e),this.setValue(t)}function c(e){var t=this.state.value.clone();t.addDayOfMonth(e),this.setValue(t)}Object.defineProperty(t,"__esModule",{value:!0});var p=n(1),f=r(p),d=n(10),h=r(d),y=n(6),v=n(39),m=r(v),g=n(85),b=r(g),P=n(287),O=r(P),C=n(40),T=r(C),w=n(28),x=r(w),E=n(89),S=r(E),k=f["default"].createClass({displayName:"Calendar",propTypes:{disabledDate:p.PropTypes.func,disabledTime:p.PropTypes.any,value:p.PropTypes.object,selectedValue:p.PropTypes.object,defaultValue:p.PropTypes.object,className:p.PropTypes.string,locale:p.PropTypes.object,showWeekNumber:p.PropTypes.bool,style:p.PropTypes.object,showToday:p.PropTypes.bool,showDateInput:p.PropTypes.bool,visible:p.PropTypes.bool,onSelect:p.PropTypes.func,onOk:p.PropTypes.func,showOk:p.PropTypes.bool,prefixCls:p.PropTypes.string,onKeyDown:p.PropTypes.func,timePicker:p.PropTypes.element,dateInputPlaceholder:p.PropTypes.any,onClear:p.PropTypes.func,onChange:p.PropTypes.func},mixins:[x["default"],T["default"]],getDefaultProps:function(){return{showToday:!0,showDateInput:!0,timePicker:null,onOk:o}},getInitialState:function(){return this.nextMonth=s.bind(this,1),this.previousMonth=s.bind(this,-1),this.nextYear=l.bind(this,1),this.previousYear=l.bind(this,-1),{}},onKeyDown:function(e){if("input"!==e.target.nodeName.toLowerCase()){var t=e.keyCode,n=e.ctrlKey||e.metaKey;switch(t){case y.KeyCode.DOWN:return u.call(this,1),e.preventDefault(),1;case y.KeyCode.UP:return u.call(this,-1),e.preventDefault(),1;case y.KeyCode.LEFT:return n?this.previousYear():c.call(this,-1),e.preventDefault(),1;case y.KeyCode.RIGHT:return n?this.nextYear():c.call(this,1),e.preventDefault(),1;case y.KeyCode.HOME:return a.call(this),e.preventDefault(),1;case y.KeyCode.END:return i.call(this),e.preventDefault(),1;case y.KeyCode.PAGE_DOWN:return this.nextMonth(),e.preventDefault(),1;case y.KeyCode.PAGE_UP:return this.previousMonth(),e.preventDefault(),1;case y.KeyCode.ENTER: return this.onSelect(this.state.value),e.preventDefault(),1;default:return this.props.onKeyDown(e),1}}},onClear:function(){this.onSelect(null),this.props.onClear()},onOk:function(){var e=this.state.selectedValue;this.isAllowedDate(e)&&this.props.onOk(e)},onDateInputChange:function(e){this.onSelect(e,{source:"dateInput"})},onDateTableSelect:function(e){this.onSelect(e)},chooseToday:function(){var e=this.state.value.clone();e.setTime(Date.now()),this.onSelect(e,{source:"todayButton"})},render:function(){var e=this.props,t=e.locale,n=e.prefixCls,r=e.disabledDate,o=e.dateInputPlaceholder,a=e.timePicker,i=e.disabledTime,s=this.state,l=s.value,u=s.selectedValue,c=e.showDateInput?f["default"].createElement(S["default"],{formatter:this.getFormatter(),key:"date-input",timePicker:a,gregorianCalendarLocale:l.locale,locale:t,placeholder:o,showClear:!0,disabledTime:i,disabledDate:r,onClear:this.onClear,prefixCls:n,selectedValue:u,onChange:this.onDateInputChange}):null,p=[c,f["default"].createElement("div",{key:"date-panel",className:n+"-date-panel"},f["default"].createElement(b["default"],{locale:t,onValueChange:this.setValue,value:l,prefixCls:n}),f["default"].createElement("div",{className:n+"-calendar-body"},f["default"].createElement(m["default"],{locale:t,value:l,selectedValue:u,prefixCls:n,dateRender:e.dateRender,onSelect:this.onDateTableSelect,disabledDate:r,showWeekNumber:e.showWeekNumber})),f["default"].createElement(O["default"],{showOk:e.showOk,locale:t,prefixCls:n,showToday:e.showToday,disabledTime:i,gregorianCalendarLocale:l.locale,showDateInput:e.showDateInput,timePicker:a,selectedValue:u,value:l,disabledDate:r,onOk:this.onOk,onSelect:this.onSelect,onToday:this.chooseToday}))];return this.renderRoot({children:p,className:e.showWeekNumber?n+"-week-number":""})}});t["default"]=k,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},a=n(1),i=r(a),s=n(39),l=r(s),u=n(93),c=r(u),p=n(40),f=r(p),d=n(28),h=r(d),y=n(291),v=r(y),m=i["default"].createClass({displayName:"FullCalendar",propTypes:{defaultType:a.PropTypes.string,type:a.PropTypes.string,prefixCls:a.PropTypes.string,locale:a.PropTypes.object,onTypeChange:a.PropTypes.func,fullscreen:a.PropTypes.bool,monthCellRender:a.PropTypes.func,dateCellRender:a.PropTypes.func,showTypeSwitch:a.PropTypes.bool,Select:a.PropTypes.func.isRequired,headerComponents:a.PropTypes.array,headerComponent:a.PropTypes.object,headerRender:a.PropTypes.func,showHeader:a.PropTypes.bool},mixins:[h["default"],f["default"]],getDefaultProps:function(){return{defaultType:"date",fullscreen:!1,showTypeSwitch:!0,showHeader:!0,onTypeChange:function(){}}},getInitialState:function(){var e=void 0;return e="type"in this.props?this.props.type:this.props.defaultType,{type:e}},componentWillReceiveProps:function(e){"type"in e&&this.setState({type:e.type})},onMonthSelect:function(e){this.onSelect(e,{target:"month"})},setType:function(e){"type"in this.props||this.setState({type:e}),this.props.onTypeChange(e)},render:function(){var e=this.props,t=e.locale,n=e.prefixCls,r=e.fullscreen,a=e.showHeader,s=e.headerComponent,u=e.headerRender,p=this.state,f=p.value,d=p.type,h=null;if(a)if(u)h=u(f,d,t);else{var y=s||v["default"];h=i["default"].createElement(y,o({key:"calendar-header"},e,{prefixCls:n+"-full",type:d,value:f,onTypeChange:this.setType,onValueChange:this.setValue}))}var m="date"===d?i["default"].createElement(l["default"],{dateRender:e.dateCellRender,contentRender:e.dateCellContentRender,locale:t,prefixCls:n,onSelect:this.onSelect,value:f}):i["default"].createElement(c["default"],{cellRender:e.monthCellRender,contentRender:e.monthCellContentRender,locale:t,onSelect:this.onMonthSelect,prefixCls:n+"-month-panel",value:f}),g=[h,i["default"].createElement("div",{key:"calendar-body",className:n+"-calendar-body"},m)],b=[n+"-full"];return r&&b.push(n+"-fullscreen"),this.renderRoot({children:g,className:b.join(" ")})}});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 t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(){}function i(){var e=new y["default"];return e.setTime(Date.now()),e}function s(e,t){var n=void 0;n=t,"right"===e&&n.addMonth(-1),this.fireValueChange(n)}function l(e,t){var n=e.selectedValue||t&&e.defaultSelectedValue||[],r=e.value;Array.isArray(r)&&(r=r[0]);var o=e.defaultValue;return Array.isArray(o)&&(o=o[0]),r||t&&o||n[0]||t&&i()}function u(e,t){if(t){var n=this.state.selectedValue,r=n.concat(),o="left"===e?0:1;r[o]=t,r[0]&&r[1]&&this.compare(r[0],r[1])>0&&(r[1-o]=void 0),this.fireSelectValueChange(r)}}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},p=function(){function e(e,t){var n=[],r=!0,o=!1,a=void 0;try{for(var i,s=e[Symbol.iterator]();!(r=(i=s.next()).done)&&(n.push(i.value),!t||n.length!==t);r=!0);}catch(l){o=!0,a=l}finally{try{!r&&s["return"]&&s["return"]()}finally{if(o)throw a}}return n}return function(t,n){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return e(t,n);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),f=n(1),d=r(f),h=n(10),y=r(h),v=n(2),m=r(v),g=n(294),b=r(g),P=n(12),O=n(87),C=r(O),T=n(86),w=r(T),x=n(28),E=r(x),S=d["default"].createClass({displayName:"RangeCalendar",propTypes:{prefixCls:f.PropTypes.string,dateInputPlaceholder:f.PropTypes.any,defaultValue:f.PropTypes.any,timePicker:f.PropTypes.any,value:f.PropTypes.any,showOk:f.PropTypes.bool,selectedValue:f.PropTypes.array,defaultSelectedValue:f.PropTypes.array,onOk:f.PropTypes.func,onChange:f.PropTypes.func,onSelect:f.PropTypes.func,onValueChange:f.PropTypes.func,formatter:f.PropTypes.oneOfType([f.PropTypes.object,f.PropTypes.string]),onClear:f.PropTypes.func},mixins:[E["default"]],getDefaultProps:function(){return{defaultSelectedValue:[],onValueChange:a}},getInitialState:function(){var e=this.props,t=e.selectedValue||e.defaultSelectedValue,n=l(e,1);return{selectedValue:t,value:n}},componentWillReceiveProps:function(e){var t={};"value"in e&&(e.value?t.value=e.value:t.value=l(e,0),this.setState(t)),"selectedValue"in e&&(t.selectedValue=e.selectedValue,this.setState(t))},onSelect:function(e){var t=this.state.selectedValue,n=t.concat(),r=!1;!n.length||2===n.length&&!t.hovering?(n.length=1,n[0]=e,r=!0):this.compare(n[0],e)<=0?(n[1]=e,r=!0):this.compare(n[0],e)>0&&(n.length=1,n[0]=e,r=!0),r&&this.fireSelectValueChange(n)},onDayHover:function(e){var t=this.state.selectedValue;t.length&&(2!==t.length||t.hovering)&&(this.compare(e,t[0])<0||(t=t.concat(),t[1]=e,t.hovering=1,this.fireSelectValueChange(t)))},onToday:function(){this.setState({value:(0,P.getTodayTime)(this.state.value)})},onOk:function(){this.props.onOk(this.state.selectedValue)},getStartValue:function(){var e=this.state.value,t=this.state.selectedValue;return t[0]&&this.props.timePicker&&(e=e.clone(),(0,P.syncTime)(t[0],e)),e},getEndValue:function(){var e=this.state.value.clone();e.addMonth(1);var t=this.state.selectedValue;return t[1]&&this.props.timePicker&&(0,P.syncTime)(t[1],e),e},compare:function(e,t){return this.props.timePicker?e.getTime()-t.getTime():e.compareToDay(t)},fireSelectValueChange:function(e,t){"selectedValue"in this.props||this.setState({selectedValue:e}),this.props.onChange(e),(t||e[0]&&e[1]&&!e.hovering)&&this.props.onSelect(e)},fireValueChange:function(e){var t=this.props;"value"in t||this.setState({value:e}),t.onValueChange(e)},clear:function(){this.fireSelectValueChange([],!0),this.props.onClear()},render:function(){var e,t=this.props,n=this.state,r=t.prefixCls,a=t.dateInputPlaceholder,i=t.timePicker,l=t.showOk,f=(e={},o(e,t.className,!!t.className),o(e,r,1),o(e,r+"-hidden",!t.visible),o(e,r+"-range",1),o(e,r+"-week-number",t.showWeekNumber),e),h=(0,m["default"])(f),y={selectedValue:n.selectedValue,onSelect:this.onSelect,onDayHover:this.onDayHover},v=void 0,g=void 0;if(a)if(Array.isArray(a)){var P=p(a,2);v=P[0],g=P[1]}else v=g=a;return d["default"].createElement("div",{className:h,style:t.style,tabIndex:"0"},d["default"].createElement("a",{className:r+"-clear-btn",role:"button",title:"\u6e05\u9664",onClick:this.clear}),d["default"].createElement(b["default"],c({},t,y,{direction:"left",formatter:this.getFormatter(),value:this.getStartValue(),placeholder:v,onInputSelect:u.bind(this,"left"),onValueChange:s.bind(this,"left")})),d["default"].createElement("span",{className:r+"-range-middle"},"~"),d["default"].createElement(b["default"],c({},t,y,{direction:"right",formatter:this.getFormatter(),placeholder:g,value:this.getEndValue(),onInputSelect:u.bind(this,"right"),onValueChange:s.bind(this,"right")})),d["default"].createElement("div",{className:r+"-range-bottom"},d["default"].createElement(C["default"],c({},t,{value:n.value,onToday:this.onToday})),l===!0||l!==!1&&i?d["default"].createElement(w["default"],c({},t,{value:n.value,onOk:this.onOk,okDisabled:2!==n.selectedValue.length||n.selectedValue.hovering})):null))}});t["default"]=S,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},a=n(1),i=r(a),s=n(4),l=r(s),u=n(6),c=r(u),p=n(87),f=r(p),d=n(86),h=r(d),y=n(12),v=c["default"].Children.mapSelf,m=i["default"].createClass({displayName:"CalendarFooter",propTypes:{prefixCls:a.PropTypes.string,showDateInput:a.PropTypes.bool,disabledTime:a.PropTypes.any,gregorianCalendarLocale:a.PropTypes.object,selectedValue:a.PropTypes.any,showOk:a.PropTypes.bool,onSelect:a.PropTypes.func,value:a.PropTypes.object,defaultValue:a.PropTypes.object},onSelect:function(e){this.props.onSelect(e)},getRootDOMNode:function(){return l["default"].findDOMNode(this)},render:function(){var e=this.props,t=e.value,n=e.prefixCls,r=e.showDateInput,a=e.disabledTime,s=e.gregorianCalendarLocale,l=e.selectedValue,u=e.showOk,c=!r&&e.timePicker||null,p=a&&c?(0,y.getTimeConfig)(l,a):null,d=null;if(e.showToday||c){var m=void 0;e.showToday&&(m=i["default"].createElement(f["default"],o({},e,{value:t})));var g=void 0;(u===!0||u!==!1&&e.timePicker)&&(g=i["default"].createElement(h["default"],e));var b=void 0;(m||g)&&(b=i["default"].createElement("span",{className:n+"-footer-btn"},v([m,g]))),c&&(c=i["default"].cloneElement(c,o({onChange:this.onSelect,allowEmpty:!1,gregorianCalendarLocale:s},p,{getPopupContainer:this.getRootDOMNode,value:l}))),d=i["default"].createElement("div",{className:n+"-footer"},c,b)}return 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,t){return e&&t&&0===e.compareToDay(t)}function a(e,t){return e.getYear()<t.getYear()?1:e.getYear()===t.getYear()&&e.getMonth()<t.getMonth()}function i(e,t){return e.getYear()>t.getYear()?1:e.getYear()===t.getYear()&&e.getMonth()>t.getMonth()}function s(e){return"rc-calendar-"+e.getYear()+"-"+e.getMonth()+"-"+e.getDayOfMonth()}function l(){}function u(e){this.props.onSelect(e)}function c(e){this.props.onDayHover(e)}Object.defineProperty(t,"__esModule",{value:!0});var p=n(1),f=r(p),d=n(88),h=r(d),y=n(12),v=f["default"].createClass({displayName:"DateTBody",propTypes:{contentRender:p.PropTypes.func,dateRender:p.PropTypes.func,disabledDate:p.PropTypes.func,prefixCls:p.PropTypes.string,selectedValue:p.PropTypes.oneOfType([p.PropTypes.object,p.PropTypes.arrayOf(p.PropTypes.object)]),value:p.PropTypes.object,showWeekNumber:p.PropTypes.bool},getDefaultProps:function(){return{onDayHover:l}},render:function(){var e=this.props,t=e.contentRender,n=e.prefixCls,r=e.selectedValue,p=e.value,d=e.showWeekNumber,v=e.dateRender,m=e.disabledDate,g=void 0,b=void 0,P=void 0,O=[],C=p.clone(),T=n+"-cell",w=n+"-week-number-cell",x=n+"-date",E=n+"-today",S=n+"-selected-day",k=n+"-in-range-cell",j=n+"-last-month-cell",_=n+"-next-month-btn-day",N=n+"-disabled-cell",M=n+"-disabled-cell-first-of-row",D=n+"-disabled-cell-last-of-row";C.setTime(Date.now());var A=p.clone();A.set(p.getYear(),p.getMonth(),1);var L=A.getDayOfWeek(),V=(L+7-p.getFirstDayOfWeek())%7,F=A.clone();F.addDayOfMonth(0-V);var I=0;for(g=0;g<h["default"].DATE_ROW_COUNT;g++)for(b=0;b<h["default"].DATE_COL_COUNT;b++)P=F,I&&(P=P.clone(),P.addDayOfMonth(I)),O.push(P),I++;var R=[];for(I=0,g=0;g<h["default"].DATE_ROW_COUNT;g++){var K=void 0,W=[];for(d&&(K=f["default"].createElement("td",{key:O[I].getWeekOfYear(),role:"gridcell",className:w},O[I].getWeekOfYear())),b=0;b<h["default"].DATE_COL_COUNT;b++){var H=null,z=null;P=O[I],b<h["default"].DATE_COL_COUNT-1&&(H=O[I+1]),b>0&&(z=O[I-1]);var B=T,U=!1,Y=!1;o(P,C)&&(B+=" "+E);var q=a(P,p),G=i(P,p);if(r&&Array.isArray(r)){if(!q&&!G){var X=r[0],$=r[1];X&&o(P,X)&&(Y=!0),X&&$&&(o(P,$)&&!r.hovering?Y=!0:P.compareToDay(X)>0&&P.compareToDay($)<0&&(B+=" "+k))}}else o(P,r)&&(Y=!0);q&&(B+=" "+j),G&&(B+=" "+_),m&&m(P,p)&&(U=!0,z&&m(z,p)||(B+=" "+M),H&&m(H,p)||(B+=" "+D)),Y&&(B+=" "+S),U&&(B+=" "+N);var Q=void 0;if(v)Q=v(P,p);else{var Z=t?t(P,p):P.getDayOfMonth();Q=f["default"].createElement("div",{key:s(P),className:x,"aria-selected":Y,"aria-disabled":U},Z)}W.push(f["default"].createElement("td",{key:I,onClick:U?l:u.bind(this,P),onMouseEnter:U?l:c.bind(this,P),role:"gridcell",title:(0,y.getTitleString)(P),className:B},Q)),I++}R.push(f["default"].createElement("tr",{key:g,role:"row"},K,W))}return f["default"].createElement("tbody",{className:n+"tbody"},R)}});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){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 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)}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(88),p=r(c),f=function(e){function t(){return o(this,t),a(this,Object.getPrototypeOf(t).apply(this,arguments))}return i(t,e),s(t,[{key:"render",value:function(){for(var e=this.props,t=e.value,n=e.locale,r=e.prefixCls,o=[],a=[],i=t.getFirstDayOfWeek(),s=void 0,l=0;l<p["default"].DATE_COL_COUNT;l++){var c=(i+l)%p["default"].DATE_COL_COUNT;o[l]=n.format.veryShortWeekdays[c],a[l]=n.format.weekdays[c]}e.showWeekNumber&&(s=u["default"].createElement("th",{role:"columnheader",className:r+"-column-header "+r+"-week-number-header"},u["default"].createElement("span",{className:r+"-column-header-inner"},"x")));var f=a.map(function(e,t){return u["default"].createElement("th",{key:t,role:"columnheader",title:e,className:r+"-column-header"},u["default"].createElement("span",{className:r+"-column-header-inner"},o[t]))});return u["default"].createElement("thead",null,u["default"].createElement("tr",{role:"row"},s,f))}}]),t}(u["default"].Component);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}function a(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 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)}function l(e){var t=this.state.value.clone();t.addYear(e),this.setState({value:t})}function u(e,t){var n=this.state.value.clone();n.setYear(e),n.rollSetMonth(this.state.value.getMonth()),this.props.onSelect(n),t.preventDefault()}Object.defineProperty(t,"__esModule",{value:!0});var c=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}}(),p=n(1),f=r(p),d=n(2),h=r(d),y=4,v=3,m=function(e){function t(e){a(this,t);var n=i(this,Object.getPrototypeOf(t).call(this,e));return n.state={value:e.value||e.defaultValue},n.prefixCls=e.rootPrefixCls+"-decade-panel",n.nextCentury=l.bind(n,100),n.previousCentury=l.bind(n,-100),n}return s(t,e),c(t,[{key:"render",value:function(){for(var e=this,t=this.state.value,n=this.props.locale,r=t.getYear(),a=100*parseInt(r/100,10),i=a-10,s=a+99,l=[],c=0,p=this.prefixCls,d=0;y>d;d++){l[d]=[];for(var m=0;v>m;m++){var g=i+10*c,b=i+10*c+9;l[d][m]={startDecade:g,endDecade:b},c++}}var P=l.map(function(t,n){var i=t.map(function(t){var n,i=t.startDecade,l=t.endDecade,c=a>i,d=l>s,y=(n={},o(n,p+"-cell",1),o(n,p+"-selected-cell",r>=i&&l>=r),o(n,p+"-last-century-cell",c),o(n,p+"-next-century-cell",d),n),v=void 0,m=void 0;return c?m=e.previousCentury:d?m=e.nextCentury:(v=i+"-"+l,m=u.bind(e,i)),f["default"].createElement("td",{key:i,onClick:m,role:"gridcell",className:(0,h["default"])(y)},f["default"].createElement("a",{className:p+"-decade"},v))});return f["default"].createElement("tr",{key:n,role:"row"},i)});return f["default"].createElement("div",{className:this.prefixCls},f["default"].createElement("div",{className:p+"-header"},f["default"].createElement("a",{className:p+"-prev-century-btn",role:"button",onClick:this.previousCentury,title:n.previousCentury},"\xab"),f["default"].createElement("div",{className:p+"-century"},a,"-",s),f["default"].createElement("a",{className:p+"-next-century-btn",role:"button",onClick:this.nextCentury,title:n.nextCentury},"\xbb")),f["default"].createElement("div",{className:p+"-body"},f["default"].createElement("table",{className:p+"-table",cellSpacing:"0",role:"grid"},f["default"].createElement("tbody",{className:p+"-tbody"},P))))}}]),t}(f["default"].Component);t["default"]=m,m.propTypes={locale:p.PropTypes.object,value:p.PropTypes.object,defaultValue:p.PropTypes.object,rootPrefixCls:p.PropTypes.string},m.defaultProps={onSelect:function(){}},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 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 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 s(){}Object.defineProperty(t,"__esModule",{value:!0});var 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}}(),u=n(1),c=r(u),p=function(e){function t(){return o(this,t),a(this,Object.getPrototypeOf(t).apply(this,arguments))}return i(t,e),l(t,[{key:"onYearChange",value:function(e){var t=this.props.value.clone();t.setYear(parseInt(e,10)),this.props.onValueChange(t)}},{key:"onMonthChange",value:function(e){var t=this.props.value.clone();t.setMonth(parseInt(e,10)),this.props.onValueChange(t)}},{key:"getYearSelectElement",value:function(e){for(var t=this.props,n=t.yearSelectOffset,r=t.yearSelectTotal,o=t.locale,a=t.prefixCls,i=t.Select,s=e-n,l=s+r,u="\u5e74"===o.year?"\u5e74":"",p=[],f=s;l>f;f++)p.push(c["default"].createElement(i.Option,{key:""+f},f+u));return c["default"].createElement(i,{className:a+"-header-year-select",onChange:this.onYearChange.bind(this),dropdownStyle:{zIndex:2e3},dropdownMenuStyle:{maxHeight:250,overflow:"auto",fontSize:12},optionLabelProp:"children",value:String(e),showSearch:!1},p)}},{key:"getMonthSelectElement",value:function(e){for(var t=this.props,n=t.locale.format.months,r=t.prefixCls,o=[],a=t.Select,i=0;12>i;i++)o.push(c["default"].createElement(a.Option,{key:""+i},n[i]));return c["default"].createElement(a,{className:r+"-header-month-select",dropdownStyle:{zIndex:2e3},dropdownMenuStyle:{maxHeight:250,overflow:"auto",overflowX:"hidden",fontSize:12},optionLabelProp:"children",value:String(e),showSearch:!1,onChange:this.onMonthChange.bind(this)},o)}},{key:"changeTypeToDate",value:function(){this.props.onTypeChange("date")}},{key:"changeTypeToMonth",value:function(){this.props.onTypeChange("month")}},{key:"render",value:function(){var e=this.props,t=e.value,n=e.locale,r=e.prefixCls,o=e.type,a=e.showTypeSwitch,i=e.headerComponents,s=t.getYear(),l=t.getMonth(),u=this.getYearSelectElement(s),p="month"===o?null:this.getMonthSelectElement(l),f=r+"-header-switcher",d=a?c["default"].createElement("span",{className:f},"date"===o?c["default"].createElement("span",{className:f+"-focus"},n.month):c["default"].createElement("span",{onClick:this.changeTypeToDate.bind(this),className:f+"-normal"},n.month),"month"===o?c["default"].createElement("span",{className:f+"-focus"},n.year):c["default"].createElement("span",{onClick:this.changeTypeToMonth.bind(this),className:f+"-normal"},n.year)):null;return c["default"].createElement("div",{className:r+"-header"},d,p,u,i)}}]),t}(u.Component);p.propTypes={value:u.PropTypes.object,locale:u.PropTypes.object,yearSelectOffset:u.PropTypes.number,yearSelectTotal:u.PropTypes.number,onValueChange:u.PropTypes.func,onTypeChange:u.PropTypes.func,Select:u.PropTypes.func,prefixCls:u.PropTypes.string,type:u.PropTypes.string,showTypeSwitch:u.PropTypes.bool,headerComponents:u.PropTypes.array},p.defaultProps={yearSelectOffset:10,yearSelectTotal:20,onValueChange:s,onTypeChange:s},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(38),a=r(o);t["default"]={today:"Today",now:"Now",ok:"Ok",clear:"Clear",month:"Month",year:"Year",monthSelect:"Choose a month",yearSelect:"Choose a year",decadeSelect:"Choose a decade",yearFormat:"yyyy",dateFormat:"M/d/yyyy",monthFormat:"MMMM",monthBeforeYear:!0,previousMonth:"Previous month (PageUp)",nextMonth:"Next month (PageDown)",previousYear:"Last year (Control + left)",nextYear:"Next year (Control + right)",previousDecade:"Last decade",nextDecade:"Next decade",previousCentury:"Last century",nextCentury:"Next century",format:a["default"]},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={bottomLeft:{points:["tl","tl"],overflow:n,offset:[0,-3],targetOffset:r},bottomRight:{points:["tr","tr"],overflow:n,offset:[0,-3],targetOffset:r},topRight:{points:["br","br"],overflow:n,offset:[0,3],targetOffset:r},topLeft:{points:["bl","bl"],overflow:n,offset:[0,3],targetOffset:r}};t["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});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},a=n(1),i=r(a),s=n(85),l=r(s),u=n(39),c=r(u),p=n(89),f=r(p),d=i["default"].createClass({displayName:"CalendarPart",propTypes:{value:a.PropTypes.any,direction:a.PropTypes.any,prefixCls:a.PropTypes.any,locale:a.PropTypes.any,selectedValue:a.PropTypes.any,formatter:a.PropTypes.any,placeholder:a.PropTypes.any,disabledDate:a.PropTypes.any,timePicker:a.PropTypes.any,disabledTime:a.PropTypes.any},render:function(){var e=this.props,t=e.value,n=e.direction,r=e.prefixCls,a=e.locale,s=e.selectedValue,u=e.formatter,p=e.placeholder,d=e.disabledDate,h=e.timePicker,y=e.disabledTime,v=r+"-range",m={locale:a,value:t,prefixCls:r},g="left"===n?0:1;return i["default"].createElement("div",{className:v+"-part "+v+"-"+n},i["default"].createElement(f["default"],{formatter:u,locale:a,prefixCls:r,timePicker:h,disabledDate:d,placeholder:p,disabledTime:y,gregorianCalendarLocale:t.locale,showClear:!1,selectedValue:s[g],onChange:e.onInputSelect}),i["default"].createElement("div",{style:{outline:"none"}},i["default"].createElement(l["default"],o({},m,{enableNext:"right"===n,enablePrev:"left"===n,onValueChange:e.onValueChange})),i["default"].createElement("div",{className:r+"-calendar-body"},i["default"].createElement(c["default"],o({},m,{selectedValue:s,dateRender:e.dateRender,onSelect:e.onSelect,onDayHover:e.onDayHover,disabledDate:d,showWeekNumber:e.showWeekNumber})))))}});t["default"]=d,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 a(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)}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},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}}(),u=function(e,t,n){for(var r=!0;r;){var o=e,a=t,i=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,a);if(void 0!==s){if("value"in s)return s.value;var l=s.get;if(void 0===l)return;return l.call(i)}var u=Object.getPrototypeOf(o);if(null===u)return;e=u,t=a,n=i,r=!0,s=u=void 0}},c=n(1),p=r(c),f=n(14),d=r(f),h=n(296),y=r(h),v={bottomLeft:{points:["tl","bl"],offset:[0,4],overflow:{adjustX:1,adjustY:1}},topLeft:{points:["bl","tl"],offset:[0,-4],overflow:{adjustX:1,adjustY:1}},bottomRight:{points:["tr","br"],offset:[0,4],overflow:{adjustX:1,adjustY:1}},topRight:{points:["br","tr"],offset:[0,-4],overflow:{adjustX:1,adjustY:1}}},m=function(e){function t(e){var n=this;a(this,t),u(Object.getPrototypeOf(t.prototype),"constructor",this).call(this,e);var r=[];"value"in e?r=e.value||[]:"defaultValue"in e&&(r=e.defaultValue||[]),this.state={popupVisible:e.popupVisible,activeValue:r,value:r},["handleChange","handleSelect","handlePopupVisibleChange","setPopupVisible","getPopupDOMNode"].forEach(function(e){return n[e]=n[e].bind(n)})}return i(t,e),l(t,[{key:"componentWillReceiveProps",value:function(e){"value"in e&&this.setState({value:e.value||[]}),"popupVisible"in e&&this.setState({popupVisible:e.popupVisible})}},{key:"getPopupDOMNode",value:function(){return this.refs.trigger.getPopupDomNode()}},{key:"setPopupVisible",value:function(e){"popupVisible"in this.props||this.setState({popupVisible:e}),e&&!this.state.visible&&this.setState({activeValue:this.state.value}),this.props.onPopupVisibleChange(e)}},{key:"handleChange",value:function(e,t){this.props.onChange(e.map(function(e){return e.value}),e),this.setPopupVisible(t.visible)}},{key:"handlePopupVisibleChange",value:function(e){this.setPopupVisible(e)}},{key:"handleSelect",value:function(e){var t=o(e,[]);"value"in this.props&&delete t.value,this.setState(t)}},{key:"render",value:function(){var e=this.props,t=e.prefixCls,n=e.transitionName,r=e.popupClassName,a=e.popupPlacement,i=o(e,["prefixCls","transitionName","popupClassName","popupPlacement"]),l=p["default"].createElement("div",null),u="";return e.options&&e.options.length>0?l=p["default"].createElement(y["default"],s({},e,{value:this.state.value,activeValue:this.state.activeValue,onSelect:this.handleSelect,onChange:this.handleChange,visible:this.state.popupVisible})):u=" "+t+"-menus-empty",p["default"].createElement(d["default"],s({ref:"trigger"},i,{popupPlacement:a,builtinPlacements:v,popupTransitionName:n,action:e.disabled?[]:["click"],popupVisible:e.disabled?!1:this.state.popupVisible,onPopupVisibleChange:this.handlePopupVisibleChange,prefixCls:t+"-menus",popupClassName:r+u,popup:l}),e.children)}}]),t}(p["default"].Component);m.defaultProps={options:[],onChange:function(){},onPopupVisibleChange:function(){},disabled:!1,transitionName:"",prefixCls:"rc-cascader",popupClassName:"",popupPlacement:"bottomLeft"},m.propTypes={value:p["default"].PropTypes.array,defaultValue:p["default"].PropTypes.array,options:p["default"].PropTypes.array.isRequired,onChange:p["default"].PropTypes.func,onPopupVisibleChange:p["default"].PropTypes.func,popupVisible:p["default"].PropTypes.bool,disabled:p["default"].PropTypes.bool,transitionName:p["default"].PropTypes.string,popupClassName:p["default"].PropTypes.string,popupPlacement:p["default"].PropTypes.string,prefixCls:p["default"].PropTypes.string},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){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}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 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},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=function(e,t,n){for(var r=!0;r;){var o=e,a=t,i=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,a);if(void 0!==s){if("value"in s)return s.value;var l=s.get;if(void 0===l)return;return l.call(i)}var u=Object.getPrototypeOf(o);if(null===u)return;e=u,t=a,n=i,r=!0,s=u=void 0}},u=n(1),c=r(u),p=n(46),f=r(p),d=n(4),h=function(e){function t(){o(this,t),l(Object.getPrototypeOf(t.prototype),"constructor",this).apply(this,arguments)}return a(t,e),s(t,[{key:"componentDidMount",value:function(){this.scrollActiveItemToView()}},{key:"componentDidUpdate",value:function(e){!e.visible&&this.props.visible&&this.scrollActiveItemToView()}},{key:"onSelect",value:function(e,t){if(e&&!e.disabled){var n=this.props.activeValue; n=n.slice(0,t+1),n[t]=e.value;var r=this.getActiveOptions(n);if(e.isLeaf===!1&&!e.children&&this.props.loadData)return this.props.onSelect({activeValue:n}),void this.props.loadData(r);var o={};e.children&&e.children.length?this.props.changeOnSelect&&(this.props.onChange(r,{visible:!0}),o.value=n):(this.props.onChange(r,{visible:!1}),o.value=n),o.activeValue=n,this.props.onSelect(o)}}},{key:"getOption",value:function(e,t){var n=this.props,r=n.prefixCls,o=n.expandTrigger,a=this.onSelect.bind(this,e,t),s={onClick:a},l=r+"-menu-item";"hover"===o&&e.children&&e.children.length>0&&(s={onMouseEnter:this.delayOnSelect.bind(this,a),onMouseLeave:this.delayOnSelect.bind(this)},l+=" "+r+"-menu-item-expand"),this.isActiveOption(e)&&(l+=" "+r+"-menu-item-active",s.ref="activeItem"+t),e.disabled&&(l+=" "+r+"-menu-item-disabled");var u="";return e.title?u=e.title:"string"==typeof e.label&&(u=e.label),c["default"].createElement("li",i({key:e.value,className:l,title:u},s),e.label)}},{key:"getActiveOptions",value:function(e){var t=e||this.props.activeValue,n=this.props.options;return(0,f["default"])(n,function(e,n){return e.value===t[n]})}},{key:"getShowOptions",value:function(){var e=this.props.options,t=this.getActiveOptions().map(function(e){return e.children}).filter(function(e){return!!e});return t.unshift(e),t}},{key:"delayOnSelect",value:function(e){var t=this;this.delayTimer&&(clearTimeout(this.delayTimer),this.delayTimer=null),"function"==typeof e&&(this.delayTimer=setTimeout(function(){e(),t.delayTimer=null},150))}},{key:"scrollActiveItemToView",value:function(){for(var e=this.getShowOptions().length,t=0;e>t;t++){var n=this.refs["activeItem"+t];if(n){var r=(0,d.findDOMNode)(n);r.parentNode.scrollTop=r.offsetTop}}}},{key:"isActiveOption",value:function(e){return this.props.activeValue.some(function(t){return t===e.value})}},{key:"render",value:function(){var e=this,t=this.props.prefixCls;return c["default"].createElement("div",null,this.getShowOptions().map(function(n,r){return c["default"].createElement("ul",{className:t+"-menu",key:r},n.map(function(t){return e.getOption(t,r)}))}))}}]),t}(c["default"].Component);h.defaultProps={options:[],value:[],activeValue:[],onChange:function(){},onSelect:function(){},prefixCls:"rc-cascader-menus",visible:!1,expandTrigger:"click",changeOnSelect:!1},h.propTypes={value:c["default"].PropTypes.array,activeValue:c["default"].PropTypes.array,options:c["default"].PropTypes.array.isRequired,prefixCls:c["default"].PropTypes.string,expandTrigger:c["default"].PropTypes.string,onChange:c["default"].PropTypes.func,onSelect:c["default"].PropTypes.func,loadData:c["default"].PropTypes.func,visible:c["default"].PropTypes.bool,changeOnSelect:c["default"].PropTypes.bool},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(295),a=r(o);t["default"]=a["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){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 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 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),p=r(c),f=n(2),d=r(f),h=function(e){function t(e){a(this,t);var n=i(this,Object.getPrototypeOf(t).call(this,e));y.call(n);var r=!1;return r="checked"in e?e.checked:e.defaultChecked,n.state={checked:r,focus:!1},n}return s(t,e),u(t,[{key:"componentWillReceiveProps",value:function(e){"checked"in e&&this.setState({checked:e.checked})}},{key:"render",value:function(){var e,t=l({},this.props);delete t.defaultChecked;var n=this.state,r=t.prefixCls,a=n.checked;"boolean"==typeof a&&(a=a?1:0);var i=(0,d["default"])((e={},o(e,t.className,!!t.className),o(e,r,1),o(e,r+"-checked",a),o(e,r+"-checked-"+a,!!a),o(e,r+"-focused",n.focus),o(e,r+"-disabled",t.disabled),e));return p["default"].createElement("span",{className:i,style:t.style},p["default"].createElement("span",{className:r+"-inner"}),p["default"].createElement("input",{name:t.name,type:t.type,readOnly:t.readOnly,disabled:t.disabled,className:r+"-input",checked:!!a,onFocus:this.handleFocus,onBlur:this.handleBlur,onChange:this.handleChange}))}}]),t}(p["default"].Component),y=function(){var e=this;this.handleFocus=function(t){e.setState({focus:!0}),e.props.onFocus(t)},this.handleBlur=function(t){e.setState({focus:!1}),e.props.onBlur(t)},this.handleChange=function(t){var n=e.state.checked;"checked"in e.props||e.setState({checked:!n}),e.props.onChange({target:l({},e.props,{checked:!n}),stopPropagation:function(){t.stopPropagation()},preventDefault:function(){t.preventDefault()}})}};t["default"]=h,h.propTypes={name:p["default"].PropTypes.string,prefixCls:p["default"].PropTypes.string,style:p["default"].PropTypes.object,type:p["default"].PropTypes.string,className:p["default"].PropTypes.string,defaultChecked:p["default"].PropTypes.oneOfType([p["default"].PropTypes.number,p["default"].PropTypes.bool]),checked:p["default"].PropTypes.oneOfType([p["default"].PropTypes.number,p["default"].PropTypes.bool]),onFocus:p["default"].PropTypes.func,onBlur:p["default"].PropTypes.func,onChange:p["default"].PropTypes.func},h.defaultProps={prefixCls:"rc-checkbox",style:{},type:"checkbox",className:"",defaultChecked:!1,onFocus:function(){},onBlur:function(){},onChange:function(){}},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 a(e){var t=e;return Array.isArray(t)||(t=t?[t]:[]),t}Object.defineProperty(t,"__esModule",{value:!0});var i=n(1),s=r(i),l=n(300),u=r(l),c=n(303),p=r(c),f=s["default"].createClass({displayName:"Collapse",propTypes:{children:i.PropTypes.any,prefixCls:i.PropTypes.string,activeKey:i.PropTypes.oneOfType([i.PropTypes.string,i.PropTypes.arrayOf(i.PropTypes.string)]),defaultActiveKey:i.PropTypes.oneOfType([i.PropTypes.string,i.PropTypes.arrayOf(i.PropTypes.string)]),openAnimation:i.PropTypes.object,onChange:i.PropTypes.func,accordion:i.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,p["default"])(this.props.prefixCls),activeKey:a(r)}},componentWillReceiveProps:function(e){"activeKey"in e&&this.setState({activeKey:a(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),a=r>-1;a?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 i.Children.map(this.props.children,function(n,a){var i=n.key||String(a),l=n.props.header,c=!1;c=o?t[0]===i:t.indexOf(i)>-1;var p={key:i,header:l,isActive:c,prefixCls:r,openAnimation:e.state.openAnimation,children:n.props.children,onItemClick:e.onClickItem(i).bind(e)};return s["default"].createElement(u["default"],p)})},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}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(1),a=r(o),i=n(301),s=r(i),l=n(9),u=r(l),c=a["default"].createClass({displayName:"CollapsePanel",propTypes:{children:o.PropTypes.any,openAnimation:o.PropTypes.object,prefixCls:o.PropTypes.string,header:o.PropTypes.oneOfType([o.PropTypes.string,o.PropTypes.number,o.PropTypes.node]),isActive:o.PropTypes.bool,onItemClick:o.PropTypes.func},getDefaultProps:function(){return{isActive:!1,onItemClick:function(){}}},handleItemClick:function(){this.props.onItemClick()},render:function(){var e=this.props,t=e.prefixCls,n=e.header,r=e.children,o=e.isActive,i=t+"-header";return a["default"].createElement("div",{className:t+"-item"},a["default"].createElement("div",{className:i,onClick:this.handleItemClick,role:"tab","aria-expanded":o},a["default"].createElement("i",{className:"arrow"}),n),a["default"].createElement(u["default"],{showProp:"isActive",exclusive:!0,component:"",animation:this.props.openAnimation},a["default"].createElement(s["default"],{prefixCls:t,isActive:o},r)))}});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,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 a=n(1),i=r(a),s=n(2),l=r(s),u=i["default"].createClass({displayName:"PanelContent",propTypes:{prefixCls:a.PropTypes.string,isActive:a.PropTypes.bool,children:a.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,a=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 i["default"].createElement("div",{className:s,role:"tabpanel"},i["default"].createElement("div",{className:n+"-content-box"},a))}});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(299),a=r(o);t["default"]=a["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 a(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 i=n(36),s=r(i);t["default"]=a,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){}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 i(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+=a(o),n.top+=a(o,1),n}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=n(1),c=r(u),p=n(4),f=r(p),d=n(114),h=r(d),y=n(9),v=r(y),m=n(306),g=r(m),b=0,P=0,O={position:"absolute",top:"-9999px",width:"50px",height:"50px",overflow:"scroll"},C=c["default"].createClass({displayName:"Dialog",propTypes:{onAfterClose:u.PropTypes.func,onClose:u.PropTypes.func,closable:u.PropTypes.bool,maskClosable:u.PropTypes.bool,visible:u.PropTypes.bool,mousePosition:u.PropTypes.object,wrapStyle:u.PropTypes.object,prefixCls:u.PropTypes.string,wrapClassName:u.PropTypes.string},getDefaultProps:function(){return{onAfterClose:o,onClose:o}},componentWillMount:function(){this.titleId="rcDialogTitle"+b++},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=f["default"].findDOMNode(this.refs.dialog);if(n){var o=s(r);i(r,n.x-o.left+"px "+(n.y-o.top)+"px")}else i(r,"")}}else if(e.visible&&t.mask&&this.lastOutSideFocusNode){try{this.lastOutSideFocusNode.focus()}catch(a){this.lastOutSideFocusNode=null}this.lastOutSideFocusNode=null}},onAnimateLeave:function(){this.refs.wrap&&(this.refs.wrap.style.display="none"),this.removeScrollingEffect(),this.props.onAfterClose()},onMaskClick:function(e){e.target===e.currentTarget&&this.props.closable&&this.props.maskClosable&&this.close(e)},onKeyDown:function(e){var t=this.props;if(t.closable&&t.keyboard&&e.keyCode===h["default"].ESC&&this.close(e),t.visible&&e.keyCode===h["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=c["default"].createElement("div",{className:n+"-footer",ref:"footer"},e.footer));var a=void 0;e.title&&(a=c["default"].createElement("div",{className:n+"-header",ref:"header"},c["default"].createElement("div",{className:n+"-title",id:this.titleId},e.title)));var i=void 0;t&&(i=c["default"].createElement("button",{onClick:this.close,"aria-label":"Close",className:n+"-close"},c["default"].createElement("span",{className:n+"-close-x"})));var s=l({},e.style,r),u=this.getTransitionName(),p=c["default"].createElement(g["default"],{role:"document",ref:"dialog",style:s,className:n+" "+(e.className||""),visible:e.visible},c["default"].createElement("div",{className:n+"-content"},i,a,c["default"].createElement("div",{className:n+"-body",style:e.bodyStyle,ref:"body"},e.children),o),c["default"].createElement("div",{tabIndex:"0",ref:"sentinel",style:{width:0,height:0,overflow:"hidden"}},"sentinel"));return c["default"].createElement(v["default"],{key:"dialog",showProp:"visible",onLeave:this.onAnimateLeave,transitionName:u,component:"",transitionAppear:!0},p)},getZIndexStyle:function(){var e={},t=this.props;return void 0!==t.zIndex&&(e.zIndex=t.zIndex),e},getWrapStyle:function(){return l({},this.getZIndexStyle(),this.props.wrapStyle)},getMaskElement:function(){var e=this.props,t=void 0;if(e.mask){var n=this.getMaskTransitionName();t=c["default"].createElement(g["default"],{style:this.getZIndexStyle(),key:"mask",className:e.prefixCls+"-mask",hiddenClassName:e.prefixCls+"-mask-hidden",visible:e.visible}),n&&(t=c["default"].createElement(v["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&&this.scrollbarWidth&&(document.body.style.paddingRight=this.scrollbarWidth+"px")},addScrollingEffect:function(){if(P++,1===P){this.checkScrollbar(),this.setScrollbar();var e=this.props.prefixCls+"-open";document.body.className+=" "+e}},removeScrollingEffect:function(){if(P--,0===P){var e=this.props.prefixCls+"-open",t=document.body;t.className=t.className.replace(e,""),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=this.measureScrollbar())},resetScrollbar:function(){document.body.style.paddingRight=""},measureScrollbar:function(){if(void 0!==this.scrollbarWidth)return this.scrollbarWidth;var e=document.createElement("div");for(var t in O)O.hasOwnProperty(t)&&(e.style[t]=O[t]);document.body.appendChild(e);var n=e.offsetWidth-e.clientWidth;return document.body.removeChild(e),this.scrollbarWidth=n,n},adjustDialog:function(){if(this.refs.wrap&&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),c["default"].createElement("div",null,this.getMaskElement(),c["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"]=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){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 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 s(){}function l(e,t){var n={};return t.forEach(function(t){void 0!==e[t]&&(n[t]=e[t])}),n}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=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}}(),p=n(1),f=r(p),d=n(4),h=r(d),y=n(304),v=r(y),m=function(e){function t(e){o(this,t);var n=a(this,Object.getPrototypeOf(t).call(this,e));return n.state={visible:e.visible},["onClose","cleanDialogContainer"].forEach(function(e){n[e]=n[e].bind(n)}),n}return i(t,e),c(t,[{key:"componentDidMount",value:function(){this.componentDidUpdate()}},{key:"componentWillReceiveProps",value:function(e){"visible"in e&&this.setState({visible:e.visible})}},{key:"shouldComponentUpdate",value:function(e,t){return!(!this.state.visible&&!t.visible)}},{key:"componentDidUpdate",value:function(){this.dialogRendered&&(this.dialogInstance=h["default"].unstable_renderSubtreeIntoContainer(this,this.getDialogElement(),this.getDialogContainer()))}},{key:"componentWillUnmount",value:function(){this.dialogContainer&&(this.state.visible?h["default"].unstable_renderSubtreeIntoContainer(this,this.getDialogElement({onAfterClose:this.cleanDialogContainer,onClose:s,visible:!1}),this.dialogContainer):this.cleanDialogContainer())}},{key:"onClose",value:function(e){this.props.onClose(e)}},{key:"getDialogContainer",value:function(){return this.dialogContainer||(this.dialogContainer=document.createElement("div"),document.body.appendChild(this.dialogContainer)),this.dialogContainer}},{key:"getDialogElement",value:function(e){var t=this.props,n=l(t,["className","closable","maskClosable","title","footer","mask","keyboard","animation","transitionName","maskAnimation","maskTransitionName","mousePosition","prefixCls","style","width","wrapStyle","height","zIndex","bodyStyle","wrapClassName"]);return n=u({},n,{onClose:this.onClose,visible:this.state.visible},e),f["default"].createElement(v["default"],u({},n,{key:"dialog"}),t.children)}},{key:"getElement",value:function(e){return this.dialogInstance.getElement(e)}},{key:"cleanDialogContainer",value:function(){this.dialogContainer&&(h["default"].unmountComponentAtNode(this.dialogContainer),document.body.removeChild(this.dialogContainer),this.dialogContainer=null)}},{key:"render",value:function(){return this.dialogRendered=this.dialogRendered||this.state.visible,null}}]),t}(f["default"].Component);m.defaultProps={className:"",mask:!0,keyboard:!0,closable:!0,maskClosable:!0,prefixCls:"rc-dialog",onClose:s},m.propTypes={className:p.PropTypes.string,keyboard:p.PropTypes.bool,wrapStyle:p.PropTypes.object,style:p.PropTypes.object,mask:p.PropTypes.bool,closable:p.PropTypes.bool,maskClosable:p.PropTypes.bool,prefixCls:p.PropTypes.string,visible:p.PropTypes.bool,onClose:p.PropTypes.func},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=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),i=r(a),s=i["default"].createClass({displayName:"LazyRenderBox",propTypes:{className:a.PropTypes.string,visible:a.PropTypes.bool,hiddenClassName:a.PropTypes.string},shouldComponentUpdate:function(e){return e.hiddenClassName||e.visible},render:function(){var e=this.props.className;return this.props.hiddenClassName&&!this.props.visible&&(e+=" "+this.props.hiddenClassName),i["default"].createElement("div",o({},this.props,{className:e}))}});t["default"]=s,e.exports=t["default"]},function(e,t,n){"use strict";e.exports=n(305)},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 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}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},s=n(1),l=r(s),u=n(4),c=r(u),p=n(14),f=r(p),d=n(310),h=r(d),y=l["default"].createClass({displayName:"Dropdown",propTypes:{minOverlayWidthMatchTrigger:s.PropTypes.bool,onVisibleChange:s.PropTypes.func,prefixCls:s.PropTypes.string,children:s.PropTypes.any,transitionName:s.PropTypes.string,overlayClassName:s.PropTypes.string,animation:s.PropTypes.any,align:s.PropTypes.object,overlayStyle:s.PropTypes.object,placement:s.PropTypes.string,trigger:s.PropTypes.array,showAction:s.PropTypes.array,hideAction:s.PropTypes.array,getPopupContainer:s.PropTypes.func},getDefaultProps:function(){return{minOverlayWidthMatchTrigger:!0,prefixCls:"rc-dropdown",trigger:["hover"],showAction:[],hideAction:[],overlayClassName:"",overlayStyle:{},defaultVisible:!1,onVisibleChange:function(){},placement:"bottomLeft"}},getInitialState:function(){var e=this.props;return"visible"in e?{visible:e.visible}:{visible:e.defaultVisible}},componentWillReceiveProps:function(e){"visible"in e&&this.setState({visible:e.visible})},onClick:function(e){var t=this.props,n=t.overlay.props;"visible"in t||this.setState({visible:!1}),n.onClick&&n.onClick(e)},onVisibleChange:function(e){var t=this.props;"visible"in t||this.setState({visible:e}),t.onVisibleChange(e)},getMenuElement:function(){var e=this.props;return l["default"].cloneElement(e.overlay,{prefixCls:e.prefixCls+"-menu",onClick:this.onClick})},getPopupDomNode:function(){return this.refs.trigger.getPopupDomNode()},afterVisibleChange:function(e){if(e&&this.props.minOverlayWidthMatchTrigger){var t=this.getPopupDomNode(),n=c["default"].findDOMNode(this);n.offsetWidth>t.offsetWidth&&(t.style.width=n.offsetWidth+"px")}},render:function(){var e,t=this.props,n=t.prefixCls,r=t.children,s=t.transitionName,u=t.animation,c=t.align,p=t.placement,d=t.getPopupContainer,y=t.showAction,v=t.hideAction,m=t.overlayClassName,g=t.overlayStyle,b=t.trigger,P=a(t,["prefixCls","children","transitionName","animation","align","placement","getPopupContainer","showAction","hideAction","overlayClassName","overlayStyle","trigger"]);return l["default"].createElement(f["default"],i({},P,(e={prefixCls:n,ref:"trigger",popupClassName:m,popupStyle:g,builtinPlacements:h["default"],action:b,showAction:y},o(e,"showAction",y),o(e,"hideAction",v),o(e,"popupPlacement",p),o(e,"popupAlign",c),o(e,"popupTransitionName",s),o(e,"popupAnimation",u),o(e,"popupVisible",this.state.visible),o(e,"afterPopupVisibleChange",this.afterVisibleChange),o(e,"popup",this.getMenuElement()),o(e,"onPopupVisibleChange",this.onVisibleChange),o(e,"getPopupContainer",d),e)),r)}});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(308),a=r(o);t["default"]=a["default"],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={topLeft:{points:["bl","tl"],overflow:n,offset:[0,-4],targetOffset:r},bottomLeft:{points:["tl","bl"],overflow:n,offset:[0,4],targetOffset:r}};t["default"]=o},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var n=window.getComputedStyle,r=n?n(e):e.currentStyle;return r?r[t.replace(/-(\w)/gi,function(e,t){return t.toUpperCase()})]:void 0}function a(e){for(var t=e,n=void 0;"body"!==(n=t.nodeName.toLowerCase());){var r=o(t,"overflowY");if("auto"===r||"scroll"===r)return t;t=t.parentNode}return"body"===n?t.ownerDocument:t}function i(e){return(0,u["default"])(s({},e),[v])}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},l=n(96),u=r(l),c=n(312),p=n(97),f=n(4),d=r(f),h=n(37),y=r(h),v={getForm:function(){return s({},c.mixin.getForm.call(this),{validateFieldsAndScroll:this.validateFieldsAndScroll})},validateFieldsAndScroll:function(e,t,n){var r=this,o=(0,p.getParams)(e,t,n),i=o.names,l=o.callback,u=o.options,c=function(e,t){if(e){var n=void 0,o=void 0;for(var i in e)if(e.hasOwnProperty(i)){var c=r.getFieldInstance(i);if(c){var p=d["default"].findDOMNode(c),f=p.getBoundingClientRect().top;(void 0===o||o>f)&&(o=f,n=p)}}if(n){var h=u.container||a(n);(0,y["default"])(n,h,s({onlyScrollIfNeeded:!0},u.scroll))}}"function"==typeof l&&l(e,t)};return this.validateFields(i,u,c)}};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){return(0,i["default"])(e,[s])}Object.defineProperty(t,"__esModule",{value:!0}),t.mixin=void 0;var a=n(96),i=r(a),s=t.mixin={getForm:function(){return{getFieldsValue:this.getFieldsValue,getFieldValue:this.getFieldValue,getFieldInstance:this.getFieldInstance,setFieldsValue:this.setFieldsValue,setFields:this.setFields,setFieldsInitialValue:this.setFieldsInitialValue,getFieldProps:this.getFieldProps,getFieldError:this.getFieldError,isFieldValidating:this.isFieldValidating,isFieldsValidating:this.isFieldsValidating,isSubmitting:this.isSubmitting,submit:this.submit,validateFields:this.validateFields,resetFields:this.resetFields}}};t["default"]=o},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 a(){}function i(e){e.preventDefault()}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(2),p=r(c),f=u["default"].createClass({displayName:"InputNumber",propTypes:{onChange:u["default"].PropTypes.func,onKeyDown:u["default"].PropTypes.func,onFocus:u["default"].PropTypes.func,onBlur:u["default"].PropTypes.func,max:u["default"].PropTypes.number,min:u["default"].PropTypes.number,step:u["default"].PropTypes.oneOfType([u["default"].PropTypes.number,u["default"].PropTypes.string])},getDefaultProps:function(){return{prefixCls:"rc-input-number",max:1/0,min:-(1/0),step:1,style:{},defaultValue:"",onChange:a,onKeyDown:a,onFocus:a,onBlur:a}},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}},componentDidMount:function(){this.componentDidUpdate()},componentWillReceiveProps:function(e){if("value"in e){var t=this.toPrecisionAsStep(e.value);this.setState({inputValue:t,value:t})}},componentDidUpdate:function(){this.state.focused&&document.activeElement!==this.refs.input&&this.refs.input.focus()},onChange:function(e){this.setInputValue(e.target.value.trim())},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;n>o;o++)r[o-1]=arguments[o];(t=this.props).onKeyDown.apply(t,[e].concat(r))},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(e.target.value.trim());this.setValue(n);for(var r=arguments.length,o=Array(r>1?r-1:0),a=1;r>a;a++)o[a-1]=arguments[a];(t=this.props).onBlur.apply(t,[e].concat(o))},onStepMouseDown:function(e){e.preventDefault();var t=this.getCurrentValidValue(this.state.inputValue);this.setState({value:t})},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}),this.props.onChange(isNaN(e)||""===e?void 0:e)},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-")),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(t))},upStep:function(e){var t=this.props,n=t.step,r=t.min,o=this.getPrecisionFactor(),a=void 0;return a="number"==typeof e?(o*e+o*n)/o:r===-(1/0)?n:r,this.toPrecisionAsStep(a)},downStep:function(e){var t=this.props,n=t.step,r=t.min,o=this.getPrecisionFactor(),a=void 0;return a="number"==typeof e?(o*e-o*n)/o:r===-(1/0)?-n:r,this.toPrecisionAsStep(a)},step:function(e,t){t&&t.preventDefault();var n=this.props;if(!n.disabled){var r=this.state.value;if(!isNaN(r)){var o=this[e+"Step"](r);o>n.max||o<n.min||(this.setValue(o),this.setState({focused:!0}))}}},down:function(e){this.step("down",e)},up:function(e){this.step("up",e)},focus:function(){this.refs.input.focus()}, render:function(){var e,t=s({},this.props);delete t.defaultValue;var n=t.prefixCls,r=(0,p["default"])((e={},o(e,n,!0),o(e,t.className,!!t.className),o(e,n+"-disabled",t.disabled),o(e,n+"-focused",this.state.focused),e)),l="",c="",f=this.state.value;if(isNaN(f))l=n+"-handler-up-disabled",c=n+"-handler-down-disabled";else{var d=Number(f);d>=t.max&&(l=n+"-handler-up-disabled"),d<=t.min&&(c=n+"-handler-down-disabled")}var h=void 0;return h=this.state.focused?this.state.inputValue:this.state.value,u["default"].createElement("div",{className:r,style:t.style},u["default"].createElement("div",{className:n+"-handler-wrap"},u["default"].createElement("a",{unselectable:"unselectable",ref:"up",onClick:l?a:this.up,onMouseDown:this.onStepMouseDown,className:n+"-handler "+n+"-handler-up "+l},u["default"].createElement("span",{unselectable:"unselectable",className:n+"-handler-up-inner",onClick:i})),u["default"].createElement("a",{unselectable:"unselectable",ref:"down",onMouseDown:this.onStepMouseDown,onClick:c?a:this.down,className:n+"-handler "+n+"-handler-down "+c},u["default"].createElement("span",{unselectable:"unselectable",className:n+"-handler-down-inner",onClick:i}))),u["default"].createElement("div",{className:n+"-input-wrap"},u["default"].createElement("input",s({},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:h}))))}});e.exports=f},function(e,t,n){"use strict";e.exports=n(313)},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),a=r(o),i=n(11),s=r(i),l=a["default"].createClass({displayName:"DOMWrap",propTypes:{tag:o.PropTypes.string},getDefaultProps:function(){return{tag:"div"}},render:function(){var e=(0,s["default"])({},this.props);e.visible||(e.className=e.className||"",e.className+=" "+e.hiddenClassName);var t=e.tag;return a["default"].createElement(t,e)}});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=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),i=r(a),s=i["default"].createClass({displayName:"Divider",getDefaultProps:function(){return{disabled:!0}},render:function(){var e=this.props,t=e.className||"",n=e.rootPrefixCls;return t+=" "+(n+"-item-divider"),i["default"].createElement("li",o({},e,{className:t}))}});t["default"]=s,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),a=r(o),i=n(98),s=r(i),l=n(11),u=r(l),c=n(22),p=a["default"].createClass({displayName:"Menu",propTypes:{openSubMenuOnMouseEnter:o.PropTypes.bool,closeSubMenuOnMouseLeave:o.PropTypes.bool,selectedKeys:o.PropTypes.arrayOf(o.PropTypes.string),defaultSelectedKeys:o.PropTypes.arrayOf(o.PropTypes.string),defaultOpenKeys:o.PropTypes.arrayOf(o.PropTypes.string),openKeys:o.PropTypes.arrayOf(o.PropTypes.string),mode:o.PropTypes.string,onClick:o.PropTypes.func,onSelect:o.PropTypes.func,onDeselect:o.PropTypes.func,onDestroy:o.PropTypes.func,openTransitionName:o.PropTypes.string,openAnimation:o.PropTypes.oneOfType([o.PropTypes.string,o.PropTypes.object]),level:o.PropTypes.number,eventKey:o.PropTypes.string,selectable:o.PropTypes.bool,children:o.PropTypes.any},mixins:[s["default"]],getDefaultProps:function(){return{openSubMenuOnMouseEnter:!0,closeSubMenuOnMouseLeave:!0,selectable:!0,onClick:c.noop,onSelect:c.noop,onOpen:c.noop,onClose:c.noop,onDeselect:c.noop,defaultSelectedKeys:[],defaultOpenKeys:[]}},getInitialState:function(){var e=this.props,t=e.defaultSelectedKeys,n=e.defaultOpenKeys;return"selectedKeys"in e&&(t=e.selectedKeys||[]),"openKeys"in e&&(n=e.openKeys||[]),{selectedKeys:t,openKeys:n}},componentWillReceiveProps:function(e){var t={};"selectedKeys"in e&&(t.selectedKeys=e.selectedKeys),"openKeys"in e&&(t.openKeys=e.openKeys),this.setState(t)},onDestroy:function(e){var t=this.state,n=this.props,r=t.selectedKeys,o=t.openKeys,a=r.indexOf(e);"selectedKeys"in n||-1===a||r.splice(a,1),a=o.indexOf(e),"openKeys"in n||-1===a||o.splice(a,1)},onItemHover:function(e){var t=this,n=e.item;"inline"!==this.props.mode&&!this.props.closeSubMenuOnMouseLeave&&n.isSubMenu&&!function(){var r=t.state.activeKey,o=t.getFlatInstanceArray().filter(function(e){return e&&e.props.eventKey===r})[0];o&&o.props.open&&t.onOpenChange({key:n.props.eventKey,item:e.item,open:!0})}(),this.onCommonItemHover(e)},onSelect:function(e){var t=this.props;if(t.selectable){var n=this.state.selectedKeys,r=e.key;n=t.multiple?n.concat([r]):[r],"selectedKeys"in t||this.setState({selectedKeys:n}),t.onSelect((0,u["default"])({},e,{selectedKeys:n}))}},onClick:function(e){var t=this.props;t.onClick(e)},onOpenChange:function(e){var t=this.props,n=this.state.openKeys,r=!0;if(e.open)r=-1===n.indexOf(e.key),r&&(n=n.concat(e.key));else{var o=n.indexOf(e.key);r=-1!==o,r&&(n=n.concat(),n.splice(o,1))}if(r){this.state.openKeys=n,"openKeys"in this.props||this.setState({openKeys:n});var a=(0,u["default"])({openKeys:n},e);e.open?t.onOpen(a):t.onClose(a)}},onDeselect:function(e){var t=this.props;if(t.selectable){var n=this.state.selectedKeys.concat(),r=e.key,o=n.indexOf(r);-1!==o&&n.splice(o,1),"selectedKeys"in t||this.setState({selectedKeys:n}),t.onDeselect((0,u["default"])({},e,{selectedKeys:n}))}},getOpenTransitionName:function(){var e=this.props,t=e.openTransitionName,n=e.openAnimation;return t||"string"!=typeof n||(t=e.prefixCls+"-open-"+n),t},isInlineMode:function(){return"inline"===this.props.mode},lastOpenSubMenu:function(){var e=this,t=[];return this.state.openKeys.length&&(t=this.getFlatInstanceArray().filter(function(t){return t&&-1!==e.state.openKeys.indexOf(t.props.eventKey)})),t[0]},renderMenuItem:function(e,t,n){if(!e)return null;var r=(0,c.getKeyFromChildrenIndex)(e,this.props.eventKey,t),o=this.state,a={openKeys:o.openKeys,open:-1!==o.openKeys.indexOf(r),selectedKeys:o.selectedKeys,selected:-1!==o.selectedKeys.indexOf(r),openSubMenuOnMouseEnter:this.props.openSubMenuOnMouseEnter};return this.renderCommonMenuItem(e,t,n,a)},render:function(){var e=(0,u["default"])({},this.props);return e.className+=" "+e.prefixCls+"-root",this.renderRoot(e)}});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=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),i=r(a),s=n(6),l=n(2),u=r(l),c=n(22),p=i["default"].createClass({displayName:"MenuItem",propTypes:{rootPrefixCls:a.PropTypes.string,eventKey:a.PropTypes.string,active:a.PropTypes.bool,selected:a.PropTypes.bool,disabled:a.PropTypes.bool,title:a.PropTypes.string,onSelect:a.PropTypes.func,onClick:a.PropTypes.func,onDeselect:a.PropTypes.func,parentMenu:a.PropTypes.object,onItemHover:a.PropTypes.func,onDestroy:a.PropTypes.func,onMouseEnter:a.PropTypes.func,onMouseLeave:a.PropTypes.func},getDefaultProps:function(){return{onSelect:c.noop,onMouseEnter:c.noop,onMouseLeave:c.noop}},componentWillUnmount:function(){var e=this.props;e.onDestroy&&e.onDestroy(e.eventKey),e.parentMenu.menuItemInstance===this&&this.clearMenuItemMouseLeaveTimer()},onKeyDown:function(e){var t=e.keyCode;return t===s.KeyCode.ENTER?(this.onClick(e),!0):void 0},onMouseLeave:function(e){var t=this,n=this.props,r=n.eventKey,o=n.parentMenu;o.menuItemInstance=this,o.menuItemMouseLeaveFn=function(){t.isMounted()&&n.active&&n.onItemHover({key:r,item:t,hover:!1,trigger:"mouseleave"})},o.menuItemMouseLeaveTimer=setTimeout(o.menuItemMouseLeaveFn,30),n.onMouseLeave({key:r,domEvent:e})},onMouseEnter:function(e){var t=this.props,n=t.parentMenu;this.clearMenuItemMouseLeaveTimer(n.menuItemInstance!==this),n.subMenuInstance&&n.subMenuInstance.clearSubMenuTimers(!0);var r=t.eventKey;t.onItemHover({key:r,item:this,hover:!0,trigger:"mouseenter"}),t.onMouseEnter({key:r,domEvent:e})},onClick:function(e){var t=this.props,n=t.eventKey,r={key:n,keyPath:[n],item:this,domEvent:e};t.onClick(r),t.multiple?t.selected?t.onDeselect(r):t.onSelect(r):t.selected||t.onSelect(r)},getPrefixCls:function(){return this.props.rootPrefixCls+"-item"},getActiveClassName:function(){return this.getPrefixCls()+"-active"},getSelectedClassName:function(){return this.getPrefixCls()+"-selected"},getDisabledClassName:function(){return this.getPrefixCls()+"-disabled"},clearMenuItemMouseLeaveTimer:function(e){var t=this.props,n=t.parentMenu;n.menuItemMouseLeaveTimer&&(clearTimeout(n.menuItemMouseLeaveTimer),n.menuItemMouseLeaveTimer=null,e&&n.menuItemMouseLeaveFn&&n.menuItemMouseLeaveFn(),n.menuItemMouseLeaveFn=null)},render:function(){var e=this.props,t={};t[this.getActiveClassName()]=!e.disabled&&e.active,t[this.getSelectedClassName()]=e.selected,t[this.getDisabledClassName()]=e.disabled,t[this.getPrefixCls()]=!0,t[e.className]=!!e.className;var n=o({},e.attribute,{title:e.title,className:(0,u["default"])(t),role:"menuitem","aria-selected":e.selected,"aria-disabled":e.disabled}),r={};e.disabled||(r={onClick:this.onClick,onMouseLeave:this.onMouseLeave,onMouseEnter:this.onMouseEnter});var a=o({},e.style);return"inline"===e.mode&&(a.paddingLeft=e.inlineIndent*e.level),i["default"].createElement("li",o({style:a},n,r),e.children)}});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),a=r(o),i=a["default"].createClass({displayName:"MenuItemGroup",propTypes:{renderMenuItem:o.PropTypes.func,index:o.PropTypes.number},getDefaultProps:function(){return{disabled:!0}},renderInnerMenuItem:function(e,t){var n=this.props.renderMenuItem;return n(e,this.props.index,t)},render:function(){var e=this.props,t=e.className||"",n=e.rootPrefixCls;t+=" "+n+"-item-group";var r=n+"-item-group-title",o=n+"-item-group-list";return a["default"].createElement("li",{className:t},a["default"].createElement("div",{className:r},e.title),a["default"].createElement("ul",{className:o},a["default"].Children.map(e.children,this.renderInnerMenuItem)))}});i.isMenuItemGroup=!0,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){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 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},i=n(322),s=r(i),l=n(1),u=r(l),c=n(6),p=n(2),f=r(p),d=n(22),h=u["default"].createClass({displayName:"SubMenu",propTypes:{parentMenu:l.PropTypes.object,title:l.PropTypes.node,onClick:l.PropTypes.func,onOpenChange:l.PropTypes.func,rootPrefixCls:l.PropTypes.string,eventKey:l.PropTypes.string,multiple:l.PropTypes.bool,active:l.PropTypes.bool,open:l.PropTypes.bool,onSelect:l.PropTypes.func,closeSubMenuOnMouseLeave:l.PropTypes.bool,openSubMenuOnMouseEnter:l.PropTypes.bool,onDeselect:l.PropTypes.func,onDestroy:l.PropTypes.func,onItemHover:l.PropTypes.func,onMouseEnter:l.PropTypes.func,onMouseLeave:l.PropTypes.func,onTitleMouseEnter:l.PropTypes.func,onTitleMouseLeave:l.PropTypes.func,onTitleClick:l.PropTypes.func},mixins:[n(321)],getDefaultProps:function(){return{onMouseEnter:d.noop,onMouseLeave:d.noop,onTitleMouseEnter:d.noop,onTitleMouseLeave:d.noop,onTitleClick:d.noop,title:""}},getInitialState:function(){return this.isSubMenu=1,{defaultActiveFirst:!1}},componentWillUnmount:function(){var e=this.props;e.onDestroy&&e.onDestroy(e.eventKey),e.parentMenu.subMenuInstance===this&&this.clearSubMenuTimers()},onDestroy:function(e){this.props.onDestroy(e)},onKeyDown:function(e){var t=e.keyCode,n=this.menuInstance;if(t===c.KeyCode.ENTER)return this.onTitleClick(e),this.setState({defaultActiveFirst:!0}),!0;if(t===c.KeyCode.RIGHT)return this.props.open?n.onKeyDown(e):(this.triggerOpenChange(!0),this.setState({defaultActiveFirst:!0})),!0;if(t===c.KeyCode.LEFT){var r=void 0;if(!this.props.open)return;return r=n.onKeyDown(e),r||(this.triggerOpenChange(!1),r=!0),r}return!this.props.open||t!==c.KeyCode.UP&&t!==c.KeyCode.DOWN?void 0:n.onKeyDown(e)},onOpenChange:function(e){this.props.onOpenChange(this.addKeyPath(e))},onMouseEnter:function(e){var t=this.props;this.clearSubMenuLeaveTimer(t.parentMenu.subMenuInstance!==this),t.onMouseEnter({key:t.eventKey,domEvent:e})},onTitleMouseEnter:function(e){var t=this.props,n=t.parentMenu;this.clearSubMenuTitleLeaveTimer(n.subMenuInstance!==this),n.menuItemInstance&&n.menuItemInstance.clearMenuItemMouseLeaveTimer(!0),t.onItemHover({key:t.eventKey,item:this,hover:!0,trigger:"mouseenter"}),t.openSubMenuOnMouseEnter&&this.triggerOpenChange(!0),this.setState({defaultActiveFirst:!1}),t.onTitleMouseEnter({key:t.eventKey,domEvent:e})},onTitleMouseLeave:function(e){var t=this,n=this.props,r=n.parentMenu;r.subMenuInstance=this,r.subMenuTitleLeaveFn=function(){var r=n.eventKey;t.isMounted()&&("inline"===n.mode&&n.active&&n.onItemHover({key:r,item:t,hover:!1,trigger:"mouseleave"}),n.onTitleMouseLeave({key:n.eventKey,domEvent:e}))},r.subMenuTitleLeaveTimer=setTimeout(r.subMenuTitleLeaveFn,100)},onMouseLeave:function(e){var t=this,n=this.props,r=n.parentMenu;r.subMenuInstance=this,r.subMenuLeaveFn=function(){var r=n.eventKey;t.isMounted()&&("inline"!==n.mode&&(n.active&&n.onItemHover({key:r,item:t,hover:!1,trigger:"mouseleave"}),n.open&&n.closeSubMenuOnMouseLeave&&t.triggerOpenChange(!1)),n.onMouseLeave({key:r,domEvent:e}))},r.subMenuLeaveTimer=setTimeout(r.subMenuLeaveFn,100)},onTitleClick:function(e){var t=this.props;t.onTitleClick({key:t.eventKey,domEvent:e}),t.openSubMenuOnMouseEnter||(this.triggerOpenChange(!t.open,"click"),this.setState({defaultActiveFirst:!1}))},onSubMenuClick:function(e){this.props.onClick(this.addKeyPath(e))},onSelect:function(e){this.props.onSelect(e)},onDeselect:function(e){this.props.onDeselect(e)},getPrefixCls:function(){return this.props.rootPrefixCls+"-submenu"},getActiveClassName:function(){return this.getPrefixCls()+"-active"},getDisabledClassName:function(){return this.getPrefixCls()+"-disabled"},getOpenClassName:function(){return this.props.rootPrefixCls+"-submenu-open"},saveMenuInstance:function(e){this.menuInstance=e},addKeyPath:function(e){return a({},e,{keyPath:(e.keyPath||[]).concat(this.props.eventKey)})},triggerOpenChange:function(e,t){var n=this.props.eventKey;this.onOpenChange({key:n,item:this,trigger:t,open:e})},clearSubMenuTimers:function(e){this.clearSubMenuLeaveTimer(e),this.clearSubMenuTitleLeaveTimer(e)},clearSubMenuTitleLeaveTimer:function(e){var t=this.props.parentMenu;t.subMenuTitleLeaveTimer&&(clearTimeout(t.subMenuTitleLeaveTimer),t.subMenuTitleLeaveTimer=null,e&&t.subMenuTitleLeaveFn&&t.subMenuTitleLeaveFn(),t.subMenuTitleLeaveFn=null)},clearSubMenuLeaveTimer:function(e){var t=this.props.parentMenu;t.subMenuLeaveTimer&&(clearTimeout(t.subMenuLeaveTimer),t.subMenuLeaveTimer=null,e&&t.subMenuLeaveFn&&t.subMenuLeaveFn(),t.subMenuLeaveFn=null)},renderChildren:function(e){var t=this.props,n={mode:"horizontal"===t.mode?"vertical":t.mode,visible:t.open,level:t.level+1,inlineIndent:t.inlineIndent,focusable:!1,onClick:this.onSubMenuClick,onSelect:this.onSelect,onDeselect:this.onDeselect,onDestroy:this.onDestroy,selectedKeys:t.selectedKeys,eventKey:t.eventKey+"-menu-",openKeys:t.openKeys,openTransitionName:t.openTransitionName,openAnimation:t.openAnimation,onOpenChange:this.onOpenChange,closeSubMenuOnMouseLeave:t.closeSubMenuOnMouseLeave,defaultActiveFirst:this.state.defaultActiveFirst,multiple:t.multiple,prefixCls:t.rootPrefixCls,id:this._menuId,ref:this.saveMenuInstance};return u["default"].createElement(s["default"],n,e)},render:function(){var e;this.haveOpen=this.haveOpen||this.props.open;var t=this.props,n=this.getPrefixCls(),r=(e={},o(e,t.className,!!t.className),o(e,n+"-"+t.mode,1),e);r[this.getOpenClassName()]=this.props.open,r[this.getActiveClassName()]=t.active,r[this.getDisabledClassName()]=t.disabled,this._menuId=this._menuId||(0,c.guid)(),r[n]=!0,r[n+"-"+t.mode]=1;var i={},s={},l={};t.disabled||(i={onClick:this.onTitleClick},s={onMouseLeave:this.onMouseLeave,onMouseEnter:this.onMouseEnter},l={onMouseEnter:this.onTitleMouseEnter,onMouseLeave:this.onTitleMouseLeave});var p={};return"inline"===t.mode&&(p.paddingLeft=t.inlineIndent*t.level),u["default"].createElement("li",a({className:(0,f["default"])(r)},s),u["default"].createElement("div",a({style:p,className:n+"-title"},l,i,{"aria-open":t.open,"aria-owns":this._menuId,"aria-haspopup":"true"}),t.title),this.renderChildren(t.children))}});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(6),a=r(o),i=n(4),s=r(i);t["default"]={componentDidMount:function(){this.componentDidUpdate()},componentDidUpdate:function(){"inline"!==this.props.mode&&(this.props.open?this.bindRootCloseHandlers():this.unbindRootCloseHandlers())},handleDocumentKeyUp:function(e){e.keyCode===o.KeyCode.ESC&&this.props.onItemHover({key:this.props.eventKey,item:this,hover:!1})},handleDocumentClick:function(e){if(!a["default"].Dom.contains(s["default"].findDOMNode(this),e.target)){var t=this.props;t.onItemHover({hover:!1,item:this,key:this.props.eventKey}),this.triggerOpenChange(!1)}},bindRootCloseHandlers:function(){this._onDocumentClickListener||(this._onDocumentClickListener=a["default"].Dom.addEventListener(document,"click",this.handleDocumentClick),this._onDocumentKeyupListener=a["default"].Dom.addEventListener(document,"keyup",this.handleDocumentKeyUp))},unbindRootCloseHandlers:function(){this._onDocumentClickListener&&(this._onDocumentClickListener.remove(),this._onDocumentClickListener=null),this._onDocumentKeyupListener&&(this._onDocumentKeyupListener.remove(),this._onDocumentKeyupListener=null)},componentWillUnmount:function(){this.unbindRootCloseHandlers()}},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},a="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),s=r(i),l=n(98),u=r(l),c=n(11),p=r(c),f=n(22),d=n(9),h=r(d),y=s["default"].createClass({displayName:"SubPopupMenu",propTypes:{onSelect:i.PropTypes.func,onClick:i.PropTypes.func,onDeselect:i.PropTypes.func,onOpenChange:i.PropTypes.func,onDestroy:i.PropTypes.func,openTransitionName:i.PropTypes.string,openAnimation:i.PropTypes.oneOfType([i.PropTypes.string,i.PropTypes.object]),openKeys:i.PropTypes.arrayOf(i.PropTypes.string),closeSubMenuOnMouseLeave:i.PropTypes.bool,visible:i.PropTypes.bool,children:i.PropTypes.any},mixins:[u["default"]],onDeselect:function(e){this.props.onDeselect(e)},onSelect:function(e){this.props.onSelect(e)},onClick:function(e){this.props.onClick(e)},onOpenChange:function(e){this.props.onOpenChange(e)},onDestroy:function(e){this.props.onDestroy(e)},onItemHover:function(e){this.onCommonItemHover(e)},getOpenTransitionName:function(){return this.props.openTransitionName},renderMenuItem:function(e,t,n){var r=this.props,o=(0,f.getKeyFromChildrenIndex)(e,r.eventKey,t),a={openKeys:r.openKeys,selectedKeys:r.selectedKeys,open:-1!==r.openKeys.indexOf(o),selected:-1!==r.selectedKeys.indexOf(o),openSubMenuOnMouseEnter:!0};return this.renderCommonMenuItem(e,t,n,a)},render:function(){var e=this.renderFirst;if(this.renderFirst=1,this.haveOpened=this.haveOpened||this.props.visible,!this.haveOpened)return null;var t=!0;!e&&this.props.visible&&(t=!1);var n=(0,p["default"])({},this.props);n.className+=" "+n.prefixCls+"-sub";var r={};return n.openTransitionName?r.transitionName=n.openTransitionName:"object"===a(n.openAnimation)&&(r.animation=(0,p["default"])({},n.openAnimation),t||delete r.animation.appear),s["default"].createElement(h["default"],o({},r,{showProp:"visible",component:"",transitionAppear:t}),this.renderRoot(n))}});t["default"]=y,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 a=n(1),i=r(a),s=n(2),l=r(s),u=i["default"].createClass({displayName:"Notice",propTypes:{duration:a.PropTypes.number,onClose:a.PropTypes.func,children:a.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 i["default"].createElement("div",{className:(0,l["default"])(r),style:t.style},i["default"].createElement("div",{className:n+"-content"},t.children),t.closable?i["default"].createElement("a",{tabIndex:"0",onClick:this.close,className:n+"-close"},i["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 a(){return"rcNotification_"+b+"_"+g++}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},s=n(1),l=r(s),u=n(4),c=r(u),p=n(9),f=r(p),d=n(6),h=n(2),y=r(h),v=n(323),m=r(v),g=0,b=Date.now(),P=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||a();this.setState(function(n){var r=n.notices;return r.filter(function(e){return e.key===t}).length?void 0:{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,d.createChainedFunction)(t.remove.bind(t,e.key),e.onClose);return l["default"].createElement(m["default"],i({prefixCls:n.prefixCls},e,{onClose:r}),e.content)}),a=(e={},o(e,n.prefixCls,1),o(e,n.className,!!n.className),e);return l["default"].createElement("div",{className:(0,y["default"])(a),style:n.style},l["default"].createElement(f["default"],{transitionName:this.getTransitionName()},r))}});P.newInstance=function(e){var t=e||{},n=document.createElement("div");document.body.appendChild(n);var r=c["default"].render(l["default"].createElement(P,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"]=P,e.exports=t["default"]},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("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 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}}(),i=function(e,t,n){for(var r=!0;r;){var o=e,a=t,i=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,a);if(void 0!==s){if("value"in s)return s.value;var l=s.get;if(void 0===l)return;return l.call(i)}var u=Object.getPrototypeOf(o);if(null===u)return;e=u,t=a,n=i,r=!0,s=u=void 0}},s=n(1),l=n(100),u=function(e){function t(e){var n=this;r(this,t),i(Object.getPrototypeOf(t.prototype),"constructor",this).call(this,e),this.state={current:e.current,_current:e.current},["_handleChange","_changeSize","_go","_buildOptionText"].forEach(function(e){return n[e]=n[e].bind(n)})}return o(t,e),a(t,[{key:"_buildOptionText",value:function(e){return e+" "+this.props.locale.items_per_page}},{key:"_changeSize",value:function(e){this.props.changeSize(Number(e))}},{key:"_handleChange",value:function(e){var t=e.target.value;this.setState({_current:t})}},{key:"_go",value:function(e){var t=e.target.value;if(""!==t){var n=Number(this.state._current);if(isNaN(n)&&(n=this.state.current),e.keyCode===l.ENTER){var r=this.props.quickGo(n);this.setState({_current:r,current:r})}}}},{key:"render",value:function(){var e=this,t=this.props,n=this.state,r=t.locale,o=t.rootPrefixCls+"-options",a=t.changeSize,i=t.quickGo,l=t.buildOptionText||this._buildOptionText,u=t.selectComponentClass,c=null,p=null;return a||i?(a&&u&&!function(){var n=u.Option,r=t.pageSize||t.pageSizeOptions[0],a=t.pageSizeOptions.map(function(e,t){return s.createElement(n,{key:t,value:e},l(e))});c=s.createElement(u,{prefixCls:t.selectPrefixCls,showSearch:!1,className:o+"-size-changer",optionLabelProp:"children",dropdownMatchSelectWidth:!1,value:r+"",onChange:e._changeSize},a)}(),i&&(p=s.createElement("div",{className:o+"-quick-jumper"},r.jump_to,s.createElement("input",{type:"text",value:n._current,onChange:this._handleChange.bind(this),onKeyUp:this._go.bind(this)}),r.page)),s.createElement("div",{className:""+o},c,p)):null}}]),t}(s.Component);u.propTypes={changeSize:s.PropTypes.func,quickGo:s.PropTypes.func,selectComponentClass:s.PropTypes.func,current:s.PropTypes.number,pageSizeOptions:s.PropTypes.arrayOf(s.PropTypes.string),pageSize:s.PropTypes.number,buildOptionText:s.PropTypes.func,locale:s.PropTypes.object},u.defaultProps={pageSizeOptions:["10","20","30","40"]},e.exports=u},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("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 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}}(),i=function(e,t,n){for(var r=!0;r;){var o=e,a=t,i=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,a);if(void 0!==s){if("value"in s)return s.value;var l=s.get;if(void 0===l)return;return l.call(i)}var u=Object.getPrototypeOf(o);if(null===u)return;e=u,t=a,n=i,r=!0,s=u=void 0}},s=n(1),l=function(e){function t(){r(this,t),i(Object.getPrototypeOf(t.prototype),"constructor",this).apply(this,arguments)}return o(t,e),a(t,[{key:"render",value:function(){var e=this.props,t=e.locale,n=e.rootPrefixCls+"-item",r=n+" "+n+"-"+e.page;e.active&&(r=r+" "+n+"-active");var o=void 0;return o=1===e.page?t.first_page:e.last?t.last_page+": "+e.page:e.page,s.createElement("li",{title:o,className:r,onClick:e.onClick},s.createElement("a",null,e.page))}}]),t}(s.Component);l.propTypes={page:s.PropTypes.number,active:s.PropTypes.bool,last:s.PropTypes.bool,locale:s.PropTypes.object},e.exports=l},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("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 a(){}var i=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}}(),s=function(e,t,n){for(var r=!0;r;){var o=e,a=t,i=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,a);if(void 0!==s){if("value"in s)return s.value;var l=s.get;if(void 0===l)return;return l.call(i)}var u=Object.getPrototypeOf(o);if(null===u)return;e=u,t=a,n=i,r=!0,s=u=void 0}},l=n(1),u=n(326),c=n(325),p=n(100),f=n(101),d=function(e){function t(e){var n=this;r(this,t),s(Object.getPrototypeOf(t.prototype),"constructor",this).call(this,e);var o=e.onChange!==a,i="current"in e;i&&!o&&console.warn("Warning: You provided a `current` prop to a Pagination component without an `onChange` handler. This will render a read-only component.");var l=e.defaultCurrent;"current"in e&&(l=e.current);var u=e.defaultPageSize;"pageSize"in e&&(u=e.pageSize),this.state={current:l,_current:l,pageSize:u},["render","_handleChange","_handleKeyUp","_handleKeyDown","_changePageSize","_isValid","_prev","_next","_hasPrev","_hasNext","_jumpPrev","_jumpNext"].forEach(function(e){return n[e]=n[e].bind(n)})}return o(t,e),i(t,[{key:"componentWillReceiveProps",value:function(e){if("current"in e&&this.setState({current:e.current,_current:e.current}),"pageSize"in e){var t={},n=this.state.current,r=this._calcPage(e.pageSize);n=n>r?r:n,"current"in e||(t.current=n,t._current=n),t.pageSize=e.pageSize,this.setState(t)}}},{key:"_calcPage",value:function(e){var t=e;return"undefined"==typeof t&&(t=this.state.pageSize),Math.floor((this.props.total-1)/t)+1}},{key:"_isValid",value:function(e){return"number"==typeof e&&e>=1&&e!==this.state.current}},{key:"_handleKeyDown",value:function(e){e.keyCode!==p.ARROW_UP&&e.keyCode!==p.ARROW_DOWN||e.preventDefault()}},{key:"_handleKeyUp",value:function(e){var t=e.target.value,n=void 0;n=""===t?t:isNaN(Number(t))?this.state._current:Number(t),this.setState({_current:n}),e.keyCode===p.ENTER?this._handleChange(n):e.keyCode===p.ARROW_UP?this._handleChange(n-1):e.keyCode===p.ARROW_DOWN&&this._handleChange(n+1)}},{key:"_changePageSize",value:function(e){var t=this.state.current,n=this._calcPage(e);t=t>n?n:t,"number"==typeof e&&("pageSize"in this.props||this.setState({pageSize:e}),"current"in this.props||this.setState({current:t,_current:t})),this.props.onShowSizeChange(t,e)}},{key:"_handleChange",value:function(e){var t=e;return this._isValid(t)?(t>this._calcPage()&&(t=this._calcPage()),"current"in this.props||this.setState({current:t,_current:t}),this.props.onChange(t),t):this.state.current}},{key:"_prev", value:function(){this._hasPrev()&&this._handleChange(this.state.current-1)}},{key:"_next",value:function(){this._hasNext()&&this._handleChange(this.state.current+1)}},{key:"_jumpPrev",value:function(){this._handleChange(Math.max(1,this.state.current-5))}},{key:"_jumpNext",value:function(){this._handleChange(Math.min(this._calcPage(),this.state.current+5))}},{key:"_hasPrev",value:function(){return this.state.current>1}},{key:"_hasNext",value:function(){return this.state.current<this._calcPage()}},{key:"render",value:function(){var e=this.props,t=e.locale,n=e.prefixCls,r=this._calcPage(),o=[],a=null,i=null,s=null,p=null;if(e.simple)return l.createElement("ul",{className:n+" "+n+"-simple "+e.className},l.createElement("li",{title:t.prev_page,onClick:this._prev,className:(this._hasPrev()?"":n+"-disabled ")+(n+"-prev")},l.createElement("a",null)),l.createElement("div",{title:this.state.current+"/"+r,className:n+"-simple-pager"},l.createElement("input",{type:"text",value:this.state._current,onKeyDown:this._handleKeyDown,onKeyUp:this._handleKeyUp,onChange:this._handleKeyUp}),l.createElement("span",{className:n+"-slash"},"\uff0f"),r),l.createElement("li",{title:t.next_page,onClick:this._next,className:(this._hasNext()?"":n+"-disabled ")+(n+"-next")},l.createElement("a",null)));if(9>=r)for(var f=1;r>=f;f++){var d=this.state.current===f;o.push(l.createElement(u,{locale:t,rootPrefixCls:n,onClick:this._handleChange.bind(this,f),key:f,page:f,active:d}))}else{a=l.createElement("li",{title:t.prev_5,key:"prev",onClick:this._jumpPrev,className:n+"-jump-prev"},l.createElement("a",null)),i=l.createElement("li",{title:t.next_5,key:"next",onClick:this._jumpNext,className:n+"-jump-next"},l.createElement("a",null)),p=l.createElement(u,{locale:e.locale,last:!0,rootPrefixCls:n,onClick:this._handleChange.bind(this,r),key:r,page:r,active:!1}),s=l.createElement(u,{locale:e.locale,rootPrefixCls:n,onClick:this._handleChange.bind(this,1),key:1,page:1,active:!1});var h=this.state.current,y=Math.max(1,h-2),v=Math.min(h+2,r);2>=h-1&&(v=5),2>=r-h&&(y=r-4);for(var f=y;v>=f;f++){var d=h===f;o.push(l.createElement(u,{locale:e.locale,rootPrefixCls:n,onClick:this._handleChange.bind(this,f),key:f,page:f,active:d}))}h-1>=4&&o.unshift(a),r-h>=4&&o.push(i),1!==y&&o.unshift(s),v!==r&&o.push(p)}var m=null;return e.showTotal&&(m=l.createElement("span",{className:n+"-total-text"},e.showTotal(e.total))),l.createElement("ul",{className:n+" "+e.className,unselectable:"unselectable"},m,l.createElement("li",{title:t.prev_page,onClick:this._prev,className:(this._hasPrev()?"":n+"-disabled ")+(n+"-prev")},l.createElement("a",null)),o,l.createElement("li",{title:t.next_page,onClick:this._next,className:(this._hasNext()?"":n+"-disabled ")+(n+"-next")},l.createElement("a",null)),l.createElement(c,{locale:e.locale,rootPrefixCls:n,selectComponentClass:e.selectComponentClass,selectPrefixCls:e.selectPrefixCls,changeSize:this.props.showSizeChanger?this._changePageSize.bind(this):null,current:this.state.current,pageSize:this.state.pageSize,pageSizeOptions:this.props.pageSizeOptions,quickGo:this.props.showQuickJumper?this._handleChange.bind(this):null}))}}]),t}(l.Component);d.propTypes={current:l.PropTypes.number,defaultCurrent:l.PropTypes.number,total:l.PropTypes.number,pageSize:l.PropTypes.number,defaultPageSize:l.PropTypes.number,onChange:l.PropTypes.func,showSizeChanger:l.PropTypes.bool,onShowSizeChange:l.PropTypes.func,selectComponentClass:l.PropTypes.func,showQuickJumper:l.PropTypes.bool,pageSizeOptions:l.PropTypes.arrayOf(l.PropTypes.string),showTotal:l.PropTypes.func,locale:l.PropTypes.object},d.defaultProps={defaultCurrent:1,total:0,defaultPageSize:10,onChange:a,className:"",selectPrefixCls:"rc-select",prefixCls:"rc-pagination",selectComponentClass:null,showQuickJumper:!1,showSizeChanger:!1,onShowSizeChange:a,locale:f},e.exports=d},function(e,t,n){"use strict";e.exports=n(327)},function(e,t,n){"use strict";var r=n(11),o=n(1),a={strokeWidth:1,strokeColor:"#3FC7FA",trailWidth:1,trailColor:"#D9D9D9"},i=o.createClass({displayName:"Line",render:function(){var e=r({},this.props),t={strokeDasharray:"100px, 100px",strokeDashoffset:100-e.percent+"px",transition:"stroke-dashoffset 0.6s ease 0s, stroke 0.6s linear"};["strokeWidth","strokeColor","trailWidth","trailColor"].forEach(function(t){return"trailWidth"===t&&!e.trailWidth&&e.strokeWidth?void(e.trailWidth=e.strokeWidth):"strokeWidth"===t&&e.strokeWidth&&(!parseFloat(e.strokeWidth)||parseFloat(e.strokeWidth)>100||parseFloat(e.strokeWidth)<0)?void(e[t]=a[t]):void(e[t]||(e[t]=a[t]))});var n=e.strokeWidth,i=n/2,s=100-n/2,l="M "+i+","+i+" L "+s+","+i,u="0 0 100 "+n;return o.createElement("svg",{className:"rc-progress-line",viewBox:u,preserveAspectRatio:"none"},o.createElement("path",{className:"rc-progress-line-trail",d:l,strokeLinecap:"round",stroke:e.trailColor,strokeWidth:e.trailWidth,fillOpacity:"0"}),o.createElement("path",{className:"rc-progress-line-path",d:l,strokeLinecap:"round",stroke:e.strokeColor,strokeWidth:e.strokeWidth,fillOpacity:"0",style:t}))}}),s=o.createClass({displayName:"Circle",render:function(){var e=r({},this.props),t=e.strokeWidth,n=50-t/2,i="M 50,50 m 0,-"+n+"\n a "+n+","+n+" 0 1 1 0,"+2*n+"\n a "+n+","+n+" 0 1 1 0,-"+2*n,s=2*Math.PI*n,l={strokeDasharray:s+"px "+s+"px",strokeDashoffset:(100-e.percent)/100*s+"px",transition:"stroke-dashoffset 0.6s ease 0s, stroke 0.6s ease"};return["strokeWidth","strokeColor","trailWidth","trailColor"].forEach(function(t){return"trailWidth"===t&&!e.trailWidth&&e.strokeWidth?void(e.trailWidth=e.strokeWidth):void(e[t]||(e[t]=a[t]))}),o.createElement("svg",{className:"rc-progress-circle",viewBox:"0 0 100 100"},o.createElement("path",{className:"rc-progress-circle-trail",d:i,stroke:e.trailColor,strokeWidth:e.trailWidth,fillOpacity:"0"}),o.createElement("path",{className:"rc-progress-circle-path",d:i,strokeLinecap:"round",stroke:e.strokeColor,strokeWidth:e.strokeWidth,fillOpacity:"0",style:l}))}});e.exports={Line:i,Circle:s}},function(e,t,n){"use strict";e.exports=n(329)},function(e,t,n){(function(r){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function a(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)}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=function(e,t,n){for(var r=!0;r;){var o=e,a=t,i=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,a);if(void 0!==s){if("value"in s)return s.value;var l=s.get;if(void 0===l)return;return l.call(i)}var u=Object.getPrototypeOf(o);if(null===u)return;e=u,t=a,n=i,r=!0,s=u=void 0}},u=n(1),c=o(u),p=n(4),f=n(334),d=n(332),h=o(d),y={easeInElastic:function(e,t,n){var r=e,o=t>=1?t:1,a=(n||1)/(1>t?t:1),i=a/Math.PI*2*(Math.asin(1/o)||0);return-(o*Math.pow(2,10*(r-=1))*Math.sin((r-i)*a))},easeOutElastic:function(e,t,n){var r=t>=1?t:1,o=(n||1)/(1>t?t:1),a=o/Math.PI*2*(Math.asin(1/r)||0);return r*Math.pow(2,-10*e)*Math.sin((e-a)*o)+1},easeInOutElastic:function(e,t,n){var r=e,o=t>=1?t:1,a=(n||1)/(1>t?t:1),i=a/Math.PI*2*(Math.asin(1/o)||0);return r*=2,1>r?-.5*(o*Math.pow(2,10*(r-=1))*Math.sin((r-i)*a)):o*Math.pow(2,-10*(r-=1))*Math.sin((r-i)*a)*.5+1},easeInBounce:function(e){var t=e,n=1-t;return 1/2.75>n?1-7.5625*t*t:2/2.75>t?1-(7.5625*(t-=1.5/2.75)*t+.75):2.5/2.75>t?1-(7.5625*(t-=2.25/2.75)*t+.9375):1-(7.5625*(t-=2.625/2.75)*t+.984375)},easeOutBounce:function(e){var t=e;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},easeInOutBounce:function(e){var t=e,n=.5>t;return t=n?1-2*t:2*t-1,t=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,n?.5*(1-t):.5*t+.5}},v=void 0;"undefined"!=typeof document&&"undefined"!=typeof window?(v=n(417),Object.keys(y).forEach(function(e){v.Easings&&(v.Easings[e]=y[e])})):v=function(){var e=arguments[arguments.length-1];r(function(){e()})};var m={easeInBack:[.6,-.28,.735,.045],easeOutBack:[.175,.885,.32,1.275],easeInOutBack:[.68,-.55,.265,1.55]},g="ant-queue-anim-placeholder-",b=function(e){function t(){var e=this;a(this,t),l(Object.getPrototypeOf(t.prototype),"constructor",this).apply(this,arguments),this.keysToEnter=[],this.keysToLeave=[],this.keysAnimating=[],this.placeholderTimeoutIds={};var n=(0,f.toArrayChildren)((0,f.getChildrenFromProps)(this.props));n.forEach(function(t){t&&t.key&&e.keysToEnter.push(t.key)}),this.originalChildren=(0,f.toArrayChildren)((0,f.getChildrenFromProps)(this.props)),this.state={children:n,childrenShow:{}},["performEnter","performLeave","enterBegin","leaveComplete"].forEach(function(t){return e[t]=e[t].bind(e)})}return i(t,e),s(t,[{key:"componentDidMount",value:function(){this.componentDidUpdate()}},{key:"componentWillReceiveProps",value:function(e){var t=this,n=(0,f.toArrayChildren)(e.children),r=this.originalChildren,o=(0,f.mergeChildren)(r,n);this.keysToEnter=[],this.keysToLeave=[],this.keysAnimating=[],this.setState({children:o}),n.forEach(function(e){if(e){var n=e.key,o=(0,f.findChildInChildrenByKey)(r,n);!o&&n&&t.keysToEnter.push(n)}}),r.forEach(function(e){if(e){var r=e.key,o=(0,f.findChildInChildrenByKey)(n,r);!o&&r&&t.keysToLeave.push(r)}})}},{key:"componentDidUpdate",value:function(){this.originalChildren=(0,f.toArrayChildren)((0,f.getChildrenFromProps)(this.props));var e=Array.prototype.slice.call(this.keysToEnter),t=Array.prototype.slice.call(this.keysToLeave);0===this.keysAnimating.length&&(this.keysAnimating=e.concat(t)),e.forEach(this.performEnter),t.forEach(this.performLeave)}},{key:"componentWillUnmount",value:function(){var e=this;this.originalChildren&&this.originalChildren.length>0&&(this.originalChildren.forEach(function(t){e.refs[t.key]&&v((0,p.findDOMNode)(e.refs[t.key]),"stop")}),Object.keys(this.placeholderTimeoutIds).forEach(function(t){clearTimeout(e.placeholderTimeoutIds[t])}))}},{key:"getVelocityConfig",value:function(e){for(var t=arguments.length,n=Array(t>1?t-1:0),r=1;t>r;r++)n[r-1]=arguments[r];return this.props.animConfig?f.transformArguments.apply(void 0,[this.props.animConfig].concat(n))[e]:h["default"][f.transformArguments.apply(void 0,[this.props.type].concat(n))[e]]}},{key:"getVelocityEnterConfig",value:function(){for(var e=arguments.length,t=Array(e),n=0;e>n;n++)t[n]=arguments[n];return this.getVelocityConfig.apply(this,[0].concat(t))}},{key:"getVelocityLeaveConfig",value:function(){for(var e=arguments.length,t=Array(e),n=0;e>n;n++)t[n]=arguments[n];var r=this.getVelocityConfig.apply(this,[1].concat(t)),o={};return Object.keys(r).forEach(function(e){Array.isArray(r[e])?o[e]=Array.prototype.slice.call(r[e]).reverse():o[e]=r[e]}),o}},{key:"getVelocityEasing",value:function(){for(var e=arguments.length,t=Array(e),n=0;e>n;n++)t[n]=arguments[n];return f.transformArguments.apply(void 0,[this.props.ease].concat(t)).map(function(e){return"string"==typeof e?m[e]||e:void 0})}},{key:"performEnter",value:function(e,t){var n=(0,f.transformArguments)(this.props.interval,e,t)[0],r=(0,f.transformArguments)(this.props.delay,e,t)[0];this.placeholderTimeoutIds[e]=setTimeout(this.performEnterBegin.bind(this,e,t),n*t+r),this.keysToEnter.indexOf(e)>=0&&this.keysToEnter.splice(this.keysToEnter.indexOf(e),1)}},{key:"performEnterBegin",value:function(e,t){var n=this.state.childrenShow;n[e]=!0,this.setState({childrenShow:n},this.realPerformEnter.bind(this,e,t))}},{key:"realPerformEnter",value:function(e,t){var n=(0,p.findDOMNode)(this.refs[e]);if(n){var r=(0,f.transformArguments)(this.props.duration,e,t)[0];n.style.visibility="hidden",v(n,"stop"),v(n,this.getVelocityEnterConfig(e,t),{duration:r,easing:this.getVelocityEasing(e,t)[0],visibility:"visible",begin:this.enterBegin.bind(this,e),complete:this.enterComplete.bind(this,e)})}}},{key:"performLeave",value:function(e,t){clearTimeout(this.placeholderTimeoutIds[e]),delete this.placeholderTimeoutIds[e];var n=(0,p.findDOMNode)(this.refs[e]);if(n){var r=(0,f.transformArguments)(this.props.interval,e,t)[1],o=(0,f.transformArguments)(this.props.delay,e,t)[1],a=(0,f.transformArguments)(this.props.duration,e,t)[1],i=this.props.leaveReverse?this.keysToLeave.length-t-1:t;v(n,"stop"),v(n,this.getVelocityLeaveConfig(e,t),{delay:r*i+o,duration:a,easing:this.getVelocityEasing(e,t)[1],begin:this.leaveBegin.bind(this),complete:this.leaveComplete.bind(this,e)})}}},{key:"enterBegin",value:function(e,t){var n=this;t.forEach(function(e){var t=n.props.animatingClassName;e.className=e.className.replace(t[1],""),-1===e.className.indexOf(t[0])&&(e.className+=" "+t[0])})}},{key:"enterComplete",value:function(e,t){var n=this;this.keysAnimating.indexOf(e)>=0&&this.keysAnimating.splice(this.keysAnimating.indexOf(e),1),t.forEach(function(e){e.className=e.className.replace(n.props.animatingClassName[0],"").trim()})}},{key:"leaveBegin",value:function(e){var t=this;e.forEach(function(e){var n=t.props.animatingClassName;e.className=e.className.replace(n[0],""),-1===e.className.indexOf(n[1])&&(e.className+=" "+n[1])})}},{key:"leaveComplete",value:function(e,t){var n=this;if(!(this.keysAnimating.indexOf(e)<0)){this.keysAnimating.splice(this.keysAnimating.indexOf(e),1);var r=this.state.childrenShow;r[e]=!1,this.keysToLeave.indexOf(e)>=0&&this.keysToLeave.splice(this.keysToLeave.indexOf(e),1);var o=this.keysToLeave.some(function(e){return r[e]});if(!o){var a=(0,f.toArrayChildren)((0,f.getChildrenFromProps)(this.props));this.setState({children:a,childrenShow:r})}t.forEach(function(e){e.className=e.className.replace(n.props.animatingClassName[1],"").trim()})}}},{key:"render",value:function(){var e=this,t=(0,f.toArrayChildren)(this.state.children).map(function(t){return t&&t.key?e.state.childrenShow[t.key]?(0,u.cloneElement)(t,{ref:t.key,key:t.key}):(0,u.createElement)("div",{ref:g+t.key,key:g+t.key}):t});return(0,u.createElement)(this.props.component,this.props,t)}}]),t}(c["default"].Component),P=c["default"].PropTypes.oneOfType([c["default"].PropTypes.number,c["default"].PropTypes.array]),O=c["default"].PropTypes.oneOfType([c["default"].PropTypes.string,c["default"].PropTypes.array]),C=c["default"].PropTypes.oneOfType([c["default"].PropTypes.object,c["default"].PropTypes.array]),T=c["default"].PropTypes.oneOfType([c["default"].PropTypes.func,c["default"].PropTypes.string]),w=c["default"].PropTypes.oneOfType([c["default"].PropTypes.func,O]),x=c["default"].PropTypes.oneOfType([c["default"].PropTypes.func,C]),E=c["default"].PropTypes.oneOfType([c["default"].PropTypes.func,P]);b.propTypes={component:T,interval:P,duration:E,delay:E,type:w,animConfig:x,ease:w,leaveReverse:c["default"].PropTypes.bool,animatingClassName:c["default"].PropTypes.array},b.defaultProps={component:"div",interval:100,duration:500,delay:0,type:"right",animConfig:null,ease:"easeOutQuart",leaveReverse:!1,animatingClassName:["queue-anim-entering","queue-anim-leaving"]},t["default"]=b,e.exports=t["default"]}).call(t,n(43).setImmediate)},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t["default"]={left:{opacity:[1,0],translateX:[0,-30]},top:{opacity:[1,0],translateY:[0,-30]},right:{opacity:[1,0],translateX:[0,30]},bottom:{opacity:[1,0],translateY:[0,30]},alpha:{opacity:[1,0]},scale:{opacity:[1,0],scale:[1,0]},scaleBig:{opacity:[1,0],scale:[1,2]},scaleX:{opacity:[1,0],scaleX:[1,0]},scaleY:{opacity:[1,0],scaleY:[1,0]}},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(331),a=r(o);t["default"]=a["default"],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 c["default"].Children.forEach(e,function(e){t.push(e)}),t}function a(e,t){var n=null;return e&&e.forEach(function(e){!n&&e&&e.key===t&&(n=e)}),n}function i(e,t){var n=[],r={},o=[];return e.forEach(function(e){e&&(a(t,e.key)?o.length&&(r[e.key]=o,o=[]):e.key&&o.push(e))}),t.forEach(function(e){e&&(r.hasOwnProperty(e.key)&&(n=n.concat(r[e.key])),n.push(e))}),o.forEach(function(t){var r=e.indexOf(t);r>=0&&n.splice(r,0,t)}),n}function s(e,t,n){var r=void 0;return r="function"==typeof e?e({key:t,index:n}):e,Array.isArray(r)&&2===r.length?r:[r,r]}function l(e){return e&&e.children}Object.defineProperty(t,"__esModule",{value:!0}),t.toArrayChildren=o,t.findChildInChildrenByKey=a,t.mergeChildren=i,t.transformArguments=s,t.getChildrenFromProps=l;var u=n(1),c=r(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),a=n(95),i=o.createClass({displayName:"Radio",getDefaultProps:function(){return{prefixCls:"rc-radio",type:"radio"}},render:function(){return o.createElement(a,r({},this.props,{ref:"checkbox"}))}});e.exports=i},function(e,t,n){"use strict";e.exports=n(335)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){}Object.defineProperty(t,"__esModule",{value:!0});var a=n(4),i=r(a),s=n(1),l=r(s),u=n(340),c=n(338),p=r(c),f=l["default"].createClass({displayName:"Rate",propTypes:{disabled:s.PropTypes.bool,value:s.PropTypes.number,defaultValue:s.PropTypes.number,count:s.PropTypes.number,allowHalf:s.PropTypes.bool,style:s.PropTypes.object,prefixCls:s.PropTypes.string,onChange:s.PropTypes.func},getDefaultProps:function(){return{defaultValue:0,count:5,allowHalf:!1,style:{},prefixCls:"rc-rate",onChange:o}},getInitialState:function(){var e=this.props.value;return void 0===e&&(e=this.props.defaultValue),{value:e}},componentWillReceiveProps:function(e){if("value"in e){var t=e.value;void 0===t&&(t=e.defaultValue),this.setState({value:t})}},onHover:function(e,t){var n=this.getStarValue(t,e.pageX);this.setState({hoverValue:n})},onMouseLeave:function(){this.setState({hoverValue:void 0})},onClick:function(e,t){var n=this.getStarValue(t,e.pageX);"value"in this.props||this.setState({value:n}),this.onMouseLeave(),this.props.onChange(n)},getStarDOM:function(e){return i["default"].findDOMNode(this.refs["star_"+e])},getStarValue:function(e,t){var n=e+1;if(this.props.allowHalf){var r=(0,u.getOffsetLeft)(this.getStarDOM(0)),o=(0,u.getOffsetLeft)(this.getStarDOM(1))-r;o/2>t-r-o*e&&(n-=.5)}return n},render:function(){for(var e=this.props,t=e.count,n=e.allowHalf,r=e.style,o=e.prefixCls,a=e.disabled,i=this.state,s=i.value,u=i.hoverValue,c=[],f=a?o+"-disabled":"",d=0;t>d;d++)c.push(l["default"].createElement(p["default"],{ref:"star_"+d,index:d,disabled:a,prefixCls:o+"-star",allowHalf:n,value:void 0===u?s:u,onClick:this.onClick,onHover:this.onHover,key:d}));return l["default"].createElement("ul",{className:o+" "+f,style:r,onMouseLeave:a?null:this.onMouseLeave},c)}});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=n(1),a=r(o),i=a["default"].createClass({displayName:"Star",propTypes:{value:o.PropTypes.number,index:o.PropTypes.number,prefixCls:o.PropTypes.string,allowHalf:o.PropTypes.bool,disabled:o.PropTypes.bool,onHover:o.PropTypes.func,onClick:o.PropTypes.func},onHover:function(e){this.props.onHover(e,this.props.index)},onClick:function(e){this.props.onClick(e,this.props.index)},getClassName:function(){var e=this.props,t=e.index,n=e.value,r=e.prefixCls,o=e.allowHalf,a=t+1;return o&&n+.5===a?r+" "+r+"-half "+r+"-active":n>=a?r+" "+r+"-full":r+" "+r+"-zero"},render:function(){var e=this.onHover,t=this.onClick,n=this.props,r=n.disabled,o=n.prefixCls;return a["default"].createElement("li",{className:this.getClassName(),onClick:r?null:t,onMouseMove:r?null:e},a["default"].createElement("div",{className:o+"-content"}))}});t["default"]=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});var o=n(337),a=r(o);t["default"]=a["default"],e.exports=t["default"]},function(e,t){"use strict";function n(e,t){var n=t?e.pageYOffset:e.pageXOffset,r=t?"scrollTop":"scrollLeft";if("number"!=typeof n){var o=e.document;n=o.documentElement[r],"number"!=typeof n&&(n=o.body[r])}return n}function r(e){var t=void 0,n=void 0,r=void 0,o=e.ownerDocument,a=o.body,i=o&&o.documentElement;return t=e.getBoundingClientRect(),n=t.left,r=t.top,n-=i.clientLeft||a.clientLeft||0,r-=i.clientTop||a.clientTop||0,{left:n,top:r}}function o(e){var t=r(e),o=e.ownerDocument,a=o.defaultView||o.parentWindow;return t.left+=n(a),t.left}Object.defineProperty(t,"__esModule",{value:!0}),t.getOffsetLeft=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="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},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},i=n(1),s=r(i),l=n(4),u=n(42),c=n(21),p=r(c),f=n(37),d=r(f),h=s["default"].createClass({displayName:"DropdownMenu",propTypes:{defaultActiveFirstOption:i.PropTypes.bool,value:i.PropTypes.any,dropdownMenuStyle:i.PropTypes.object,multiple:i.PropTypes.bool,onPopupFocus:i.PropTypes.func,onMenuDeSelect:i.PropTypes.func,onMenuSelect:i.PropTypes.func,prefixCls:i.PropTypes.string,menuItems:i.PropTypes.any,inputValue:i.PropTypes.string,visible:i.PropTypes.bool},componentWillMount:function(){this.lastInputValue=this.props.inputValue},componentDidMount:function(){this.scrollActiveItemToView(),this.lastVisible=this.props.visible},shouldComponentUpdate:function(e){return e.visible||(this.lastVisible=!1),e.visible},componentDidUpdate:function(e){var t=this.props;!e.visible&&t.visible&&this.scrollActiveItemToView(),this.lastVisible=t.visible,this.lastInputValue=t.inputValue},scrollActiveItemToView:function(){var e=(0,l.findDOMNode)(this.firstActiveItem);e&&(0,d["default"])(e,(0,l.findDOMNode)(this.refs.menu),{onlyScrollIfNeeded:!0})},renderMenu:function(){var e=this,t=this.props,n=t.menuItems,r=t.defaultActiveFirstOption,l=t.value,f=t.prefixCls,d=t.multiple,h=t.onMenuSelect,y=t.inputValue;if(n&&n.length){var v=function(){var o={};d?(o.onDeselect=t.onMenuDeselect,o.onSelect=h):o.onClick=h;var v=(0,u.getSelectKeys)(n,l),m={},g=n;return v.length&&!function(){t.visible&&!e.lastVisible&&(m.activeKey=v[0]);var r=!1,o=function(t){return r||-1===v.indexOf(t.key)?t:(r=!0,(0,i.cloneElement)(t,{ref:function(t){e.firstActiveItem=t}}))};g=n.map(function(e){if(e.type===c.ItemGroup){var t=e.props.children.map(o);return(0,i.cloneElement)(e,{},t)}return o(e)})}(),y!==e.lastInputValue&&(m.activeKey=""),{v:s["default"].createElement(p["default"],a({ref:"menu",style:e.props.dropdownMenuStyle,defaultActiveFirst:r},m,{multiple:d,focusable:!1},o,{selectedKeys:v,prefixCls:f+"-menu"}),g)}}();if("object"===("undefined"==typeof v?"undefined":o(v)))return v.v}return null},render:function(){return s["default"].createElement("div",{style:{overflow:"auto"},onFocus:this.props.onPopupFocus,onMouseDown:u.preventDefaultEvent},this.renderMenu())}});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=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),i=r(a),s=n(42),l=n(21),u=n(346),c=r(u),p=n(41),f=r(p),d=n(102),h=r(d);t["default"]={filterOption:function y(e,t){if(!e)return!0;var y=this.props.filterOption;return y?t.props.disabled?!1:y.call(this,e,t):!0},renderFilterOptions:function(e){return this.renderFilterOptionsFromChildren(this.props.children,!0,e)},renderFilterOptionsFromChildren:function(e,t,n){var r=this,a=[],u=this.props,p=void 0===n?this.state.inputValue:n,d=[],y=u.tags;if(i["default"].Children.forEach(e,function(e){if(e.type!==f["default"]){(0,c["default"])(e.type===h["default"],"the children of `Select` should be `Select.Option` or `Select.OptGroup`, "+("instead of `"+(e.type.name||e.type.displayName||e.type)+"`."));var t=(0,s.getValuePropValue)(e);r.filterOption(p,e)&&a.push(i["default"].createElement(l.Item,o({style:s.UNSELECTABLE_STYLE,attribute:s.UNSELECTABLE_ATTRIBUTE,value:t,key:t},e.props))),y&&!e.props.disabled&&d.push(t)}else{var n=r.renderFilterOptionsFromChildren(e.props.children,!1);if(n.length){var u=e.props.label,v=e.key;v||"string"!=typeof u?!u&&v&&(u=v):v=u,a.push(i["default"].createElement(l.ItemGroup,{key:v,title:u},n))}}}),y){var v=this.state.value||[];if(v=v.filter(function(e){return-1===d.indexOf(e.key)&&(!p||String(e.key).indexOf(String(p))>-1)}),a=a.concat(v.map(function(e){var t=e.key;return i["default"].createElement(l.Item,{style:s.UNSELECTABLE_STYLE,attribute:s.UNSELECTABLE_ATTRIBUTE,value:t,key:t},t)})),p){var m=a.every(function(e){return(0,s.getValuePropValue)(e)!==p});m&&a.unshift(i["default"].createElement(l.Item,{style:s.UNSELECTABLE_STYLE,attribute:s.UNSELECTABLE_ATTRIBUTE,value:p,key:p},p))}}return!a.length&&t&&u.notFoundContent&&(a=[i["default"].createElement(l.Item,{style:s.UNSELECTABLE_STYLE,attribute:s.UNSELECTABLE_ATTRIBUTE,disabled:!0,value:"NOT_FOUND",key:"NOT_FOUND"},u.notFoundContent)]),a}},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 a(){}function i(e,t){return String((0,C.getPropValue)(t,this.props.optionFilterProp)).indexOf(e)>-1}function s(e,t){this[e]=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=n(1),c=r(u),p=n(4),f=r(p),d=n(6),h=n(2),y=r(h),v=n(41),m=r(v),g=n(9),b=r(g),P=n(73),O=r(P),C=n(42),T=n(344),w=r(T),x=n(342),E=r(x),S=c["default"].createClass({displayName:"Select",propTypes:{defaultActiveFirstOption:u.PropTypes.bool,multiple:u.PropTypes.bool,filterOption:u.PropTypes.any,showSearch:u.PropTypes.bool,disabled:u.PropTypes.bool,allowClear:u.PropTypes.bool,showArrow:u.PropTypes.bool,tags:u.PropTypes.bool,prefixCls:u.PropTypes.string,className:u.PropTypes.string,transitionName:u.PropTypes.string,optionLabelProp:u.PropTypes.string,optionFilterProp:u.PropTypes.string,animation:u.PropTypes.string,choiceTransitionName:u.PropTypes.string,onChange:u.PropTypes.func,onBlur:u.PropTypes.func,onSelect:u.PropTypes.func,onSearch:u.PropTypes.func,placeholder:u.PropTypes.any,onDeselect:u.PropTypes.func,labelInValue:u.PropTypes.bool,value:u.PropTypes.any,defaultValue:u.PropTypes.any,dropdownStyle:u.PropTypes.object,maxTagTextLength:u.PropTypes.number},mixins:[E["default"]],getDefaultProps:function(){return{prefixCls:"rc-select",filterOption:i,defaultOpen:!1,labelInValue:!1,defaultActiveFirstOption:!0,showSearch:!0,allowClear:!1,placeholder:"",defaultValue:[],onChange:a,onBlur:a,onSelect:a,onSearch:a,onDeselect:a,showArrow:!0,dropdownMatchSelectWidth:!0,dropdownStyle:{},dropdownMenuStyle:{},optionFilterProp:"value",optionLabelProp:"value",notFoundContent:"Not Found"}},getInitialState:function(){var e=this.props,t=[];t="value"in e?(0,C.toArray)(e.value):(0,C.toArray)(e.defaultValue),t=this.addLabelToValue(e,t);var n="";e.combobox&&(n=t.length?String(t[0].key):""),this.saveInputRef=s.bind(this,"inputInstance"),this.saveInputMirrorRef=s.bind(this,"inputMirrorInstance");var r=e.open;return void 0===r&&(r=e.defaultOpen),{value:t,inputValue:n,open:r}},componentWillReceiveProps:function(e){if("value"in e){var t=(0,C.toArray)(e.value);t=this.addLabelToValue(e,t),this.setState({value:t}),e.combobox&&this.setState({inputValue:t.length?String(t[0].key):""})}},componentDidUpdate:function(){var e=this.state,t=this.props;if(e.open&&(0,C.isMultipleOrTags)(t)){var n=this.getInputDOMNode(),r=this.getInputMirrorDOMNode();n.value?(n.style.width="",n.style.width=r.clientWidth+"px"):n.style.width=""}},componentWillUnmount:function(){this.clearBlurTime(),this.dropdownContainer&&(f["default"].unmountComponentAtNode(this.dropdownContainer),document.body.removeChild(this.dropdownContainer),this.dropdownContainer=null)},onInputChange:function(e){var t=e.target.value,n=this.props;this.setState({inputValue:t,open:!0}),(0,C.isCombobox)(n)&&this.fireChange([{key:t}]),n.onSearch(t)},onDropdownVisibleChange:function(e){this.setOpenState(e)},onKeyDown:function(e){var t=this.props;if(!t.disabled){var n=e.keyCode;this.state.open&&!this.getInputDOMNode()?this.onInputKeyDown(e):n!==d.KeyCode.ENTER&&n!==d.KeyCode.DOWN||(this.setOpenState(!0),e.preventDefault())}},onInputKeyDown:function(e){var t=this.props;if(!t.disabled){var n=this.state,r=e.keyCode;if(!(0,C.isMultipleOrTags)(t)||e.target.value||r!==d.KeyCode.BACKSPACE){if(r===d.KeyCode.DOWN){if(!n.open)return this.openIfHasChildren(),e.preventDefault(),void e.stopPropagation()}else if(r===d.KeyCode.ESC)return void(n.open&&(this.setOpenState(!1),e.preventDefault(),e.stopPropagation()));if(n.open){var o=this.refs.trigger.getInnerMenu();o&&o.onKeyDown(e)&&(e.preventDefault(),e.stopPropagation())}}else{var a=n.value.concat();if(a.length){var i=a.pop();t.onDeselect(t.labelInValue?i:i.key),this.fireChange(a)}}}},onMenuSelect:function(e){var t=e.item,n=this.state.value,r=this.props,o=(0,C.getValuePropValue)(t),a=this.getLabelFromOption(t),i=o;if(r.labelInValue&&(i={key:i,label:a}),r.onSelect(i,t),(0,C.isMultipleOrTags)(r)){if(-1!==(0,C.findIndexInValueByKey)(n,o))return;n=n.concat([{key:o,label:a}])}else{if(n.length&&n[0].key===o)return void this.setOpenState(!1,!0);n=[{key:o,label:a}],this.setOpenState(!1,!0)}this.fireChange(n),this.setState({inputValue:""}),(0,C.isCombobox)(r)&&this.setState({inputValue:(0,C.getPropValue)(t,r.optionLabelProp)})},onMenuDeselect:function(e){var t=e.item,n=e.domEvent;"click"===n.type&&this.removeSelected((0,C.getValuePropValue)(t)),this.setState({inputValue:""})},onArrowClick:function(e){e.stopPropagation(),this.props.disabled||this.setOpenState(!this.state.open,!0)},onPlaceholderClick:function(){this.getInputDOMNode()&&this.getInputDOMNode().focus()},onOuterFocus:function(){this.clearBlurTime(),this._focused=!0,this.updateFocusClassName()},onPopupFocus:function(){this.maybeFocus(!0,!0)},onOuterBlur:function(){var e=this;this.blurTimer=setTimeout(function(){e._focused=!1,e.updateFocusClassName();var t=e.props,n=e.state.value;if((0,C.isSingleMode)(t)&&t.showSearch&&e.state.inputValue&&t.defaultActiveFirstOption){var r=e._options||[];if(r.length){var o=(0,C.findFirstMenuItem)(r);o&&(n=[{key:o.key,label:e.getLabelFromOption(o)}],e.fireChange(n))}}t.onBlur(e.getVLForOnChange(n))},10)},onClearSelection:function(e){var t=this.props,n=this.state;t.disabled||(e.stopPropagation(),(n.inputValue||n.value.length)&&(this.state.value.length&&this.fireChange([]),this.setOpenState(!1,!0),this.state.inputValue&&this.setState({inputValue:""})))},onChoiceAnimationLeave:function(){this.refs.trigger.refs.trigger.forcePopupAlign()},getLabelBySingleValue:function(e,t){var n=this;if(void 0===t)return null;var r=null;return c["default"].Children.forEach(e,function(e){if(e.type===m["default"]){var o=n.getLabelBySingleValue(e.props.children,t);null!==o&&(r=o)}else(0,C.getValuePropValue)(e)===t&&(r=n.getLabelFromOption(e)); }),r},getLabelFromOption:function(e){return(0,C.getPropValue)(e,this.props.optionLabelProp)},getLabelFromProps:function(e,t){return this.getLabelByValue(e.children,t)},getVLForOnChange:function(e){var t=e;return void 0!==t?(this.props.labelInValue||(t=t.map(function(e){return e.key})),(0,C.isMultipleOrTags)(this.props)?t:t[0]):t},getLabelByValue:function(e,t){var n=this.getLabelBySingleValue(e,t);return null===n?t:n},getDropdownContainer:function(){return this.dropdownContainer||(this.dropdownContainer=document.createElement("div"),document.body.appendChild(this.dropdownContainer)),this.dropdownContainer},getPlaceholderElement:function(){var e=this.props,t=this.state,n=!1;t.inputValue&&(n=!0),t.value.length&&(n=!0),(0,C.isCombobox)(e)&&1===t.value.length&&!t.value[0].key&&(n=!1);var r=e.placeholder;return r?c["default"].createElement("div",l({onMouseDown:C.preventDefaultEvent,style:l({display:n?"none":"block"},C.UNSELECTABLE_STYLE)},C.UNSELECTABLE_ATTRIBUTE,{onClick:this.onPlaceholderClick,className:e.prefixCls+"-selection__placeholder"}),r):null},getInputElement:function(){var e=this.props;return c["default"].createElement("div",{className:e.prefixCls+"-search__field__wrap"},c["default"].createElement("input",{ref:this.saveInputRef,onChange:this.onInputChange,onKeyDown:this.onInputKeyDown,value:this.state.inputValue,disabled:e.disabled,className:e.prefixCls+"-search__field"}),c["default"].createElement("span",{ref:this.saveInputMirrorRef,className:e.prefixCls+"-search__field__mirror"},this.state.inputValue))},getInputDOMNode:function(){return this.inputInstance},getInputMirrorDOMNode:function(){return this.inputMirrorInstance},getPopupDOMNode:function(){return this.refs.trigger.getPopupDOMNode()},getPopupMenuComponent:function(){return this.refs.trigger.getInnerMenu()},setOpenState:function(e,t){var n=this,r=this.props,o=this.state;if(o.open===e)return void this.maybeFocus(e,t);var a={open:e};!e&&(0,C.isSingleMode)(r)&&r.showSearch&&(a.inputValue=""),e||this.maybeFocus(e,t),this.setState(a,function(){e&&n.maybeFocus(e,t)})},clearBlurTime:function(){this.blurTimer&&(clearTimeout(this.blurTimer),this.blurTimer=null)},updateFocusClassName:function(){var e=this.refs,t=this.props;this._focused?(0,O["default"])(e.root).add(t.prefixCls+"-focused"):(0,O["default"])(e.root).remove(t.prefixCls+"-focused")},maybeFocus:function(e,t){if(t||e){var n=this.getInputDOMNode(),r=document,o=r.activeElement;if(n&&(e||(0,C.isMultipleOrTagsOrCombobox)(this.props)))o!==n&&n.focus();else{var a=this.refs.selection;o!==a&&a.focus()}}},addLabelToValue:function(e,t){var n=this,r=t;return e.labelInValue?r.forEach(function(t){t.label=t.label||n.getLabelFromProps(e,t.key)}):r=r.map(function(t){return{key:t,label:n.getLabelFromProps(e,t)}}),r},removeSelected:function(e){var t=this.props;if(!t.disabled){var n=void 0,r=this.state.value.filter(function(t){return t.key===e&&(n=t.label),t.key!==e}),o=(0,C.isMultipleOrTags)(t);if(o){var a=e;t.labelInValue&&(a={key:e,label:n}),t.onDeselect(a)}this.fireChange(r)}},openIfHasChildren:function(){var e=this.props;(c["default"].Children.count(e.children)||(0,C.isSingleMode)(e))&&this.setOpenState(!0)},fireChange:function(e){var t=this.props;"value"in t||this.setState({value:e}),t.onChange(this.getVLForOnChange(e))},renderTopControlNode:function(){var e=this,t=this.state,n=t.value,r=t.open,o=t.inputValue,a=this.props,i=a.choiceTransitionName,s=a.prefixCls,u=a.maxTagTextLength,p=a.showSearch,f=s+"-selection__rendered",d=null;if((0,C.isSingleMode)(a)){var h=null;if(n.length){var y=!1,v=1;p&&r?(y=!o,y&&(v=.4)):y=!0,h=c["default"].createElement("div",{key:"value",className:s+"-selection-selected-value",style:{display:y?"block":"none",opacity:v}},n[0].label)}d=p?[h,c["default"].createElement("div",{className:s+"-search "+s+"-search--inline",key:"input",style:{display:r?"block":"none"}},this.getInputElement())]:[h]}else{var m=[];(0,C.isMultipleOrTags)(a)&&(m=n.map(function(t){var n=t.label,r=n;return u&&"string"==typeof n&&n.length>u&&(n=n.slice(0,u)+"..."),c["default"].createElement("li",l({style:C.UNSELECTABLE_STYLE},C.UNSELECTABLE_ATTRIBUTE,{onMouseDown:C.preventDefaultEvent,className:s+"-selection__choice",key:t.key,title:r}),c["default"].createElement("div",{className:s+"-selection__choice__content"},n),c["default"].createElement("span",{className:s+"-selection__choice__remove",onClick:e.removeSelected.bind(e,t.key)}))})),m.push(c["default"].createElement("li",{className:s+"-search "+s+"-search--inline",key:"__input"},this.getInputElement())),d=(0,C.isMultipleOrTags)(a)&&i?c["default"].createElement(b["default"],{onLeave:this.onChoiceAnimationLeave,component:"ul",transitionName:i},m):c["default"].createElement("ul",null,m)}return c["default"].createElement("div",{className:f},this.getPlaceholderElement(),d)},render:function(){var e,t=this.props,n=(0,C.isMultipleOrTags)(t),r=this.state,a=t.className,i=t.disabled,s=t.allowClear,u=t.prefixCls,p=this.renderTopControlNode(),f={},d=this.state.open,h=[];d&&(h=this.renderFilterOptions()),this._options=h,!d||!(0,C.isMultipleOrTagsOrCombobox)(t)&&t.showSearch||h.length||(d=!1),(0,C.isMultipleOrTagsOrCombobox)(t)||(f={onKeyDown:this.onKeyDown,tabIndex:0});var v=(e={},o(e,a,!!a),o(e,u,1),o(e,u+"-open",d),o(e,u+"-focused",d||!!this._focused),o(e,u+"-combobox",(0,C.isCombobox)(t)),o(e,u+"-disabled",i),o(e,u+"-enabled",!i),o(e,u+"-allow-clear",!!t.allowClear),e),m=l({},C.UNSELECTABLE_STYLE,{display:"none"});(this.state.inputValue||this.state.value.length)&&(m.display="block");var g=c["default"].createElement("span",l({key:"clear",onMouseDown:C.preventDefaultEvent,style:m},C.UNSELECTABLE_ATTRIBUTE,{className:u+"-selection__clear",onClick:this.onClearSelection}));return c["default"].createElement(w["default"],{onPopupFocus:this.onPopupFocus,dropdownAlign:t.dropdownAlign,dropdownClassName:t.dropdownClassName,dropdownMatchSelectWidth:t.dropdownMatchSelectWidth,defaultActiveFirstOption:t.defaultActiveFirstOption,dropdownMenuStyle:t.dropdownMenuStyle,transitionName:t.transitionName,animation:t.animation,prefixCls:t.prefixCls,dropdownStyle:t.dropdownStyle,combobox:t.combobox,showSearch:t.showSearch,options:h,multiple:n,disabled:i,visible:d,inputValue:r.inputValue,value:r.value,onDropdownVisibleChange:this.onDropdownVisibleChange,getPopupContainer:t.getPopupContainer,onMenuSelect:this.onMenuSelect,onMenuDeselect:this.onMenuDeselect,ref:"trigger"},c["default"].createElement("div",{style:t.style,ref:"root",onBlur:this.onOuterBlur,onFocus:this.onOuterFocus,className:(0,y["default"])(v)},c["default"].createElement("div",l({ref:"selection",key:"selection",className:u+"-selection\n "+u+"-selection--"+(n?"multiple":"single"),role:"combobox","aria-autocomplete":"list","aria-haspopup":"true","aria-expanded":d},f),p,s&&!n?g:null,n||!t.showArrow?null:c["default"].createElement("span",l({key:"arrow",className:u+"-arrow",style:C.UNSELECTABLE_STYLE},C.UNSELECTABLE_ATTRIBUTE,{onMouseDown:C.preventDefaultEvent,onClick:this.onArrowClick}),c["default"].createElement("b",null)))))}});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 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}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},s=n(14),l=r(s),u=n(1),c=r(u),p=n(2),f=r(p),d=n(341),h=r(d),y=n(4),v=r(y),m={bottomLeft:{points:["tl","bl"],offset:[0,4],overflow:{adjustX:0,adjustY:1}},topLeft:{points:["bl","tl"],offset:[0,-4],overflow:{adjustX:0,adjustY:1}}},g=c["default"].createClass({displayName:"SelectTrigger",propTypes:{onPopupFocus:u.PropTypes.func,dropdownMatchSelectWidth:u.PropTypes.bool,dropdownAlign:u.PropTypes.object,visible:u.PropTypes.bool,multiple:u.PropTypes.bool,inputValue:u.PropTypes.string,filterOption:u.PropTypes.any,options:u.PropTypes.any,prefixCls:u.PropTypes.string,popupClassName:u.PropTypes.string,children:u.PropTypes.any},componentDidUpdate:function(){var e=this.props,t=e.visible,n=e.dropdownMatchSelectWidth;if(t){var r=this.getPopupDOMNode();if(r){var o=n?"width":"minWidth";r.style[o]=v["default"].findDOMNode(this).offsetWidth+"px"}}},getInnerMenu:function(){return this.popupMenu&&this.popupMenu.refs.menu},getPopupDOMNode:function(){return this.refs.trigger.getPopupDomNode()},getDropdownElement:function(e){var t=this.props;return c["default"].createElement(h["default"],i({ref:this.saveMenu},e,{prefixCls:this.getDropdownPrefixCls(),onMenuSelect:t.onMenuSelect,onMenuDeselect:t.onMenuDeselect,value:t.value,defaultActiveFirstOption:t.defaultActiveFirstOption,dropdownMenuStyle:t.dropdownMenuStyle}))},getDropdownTransitionName:function(){var e=this.props,t=e.transitionName;return!t&&e.animation&&(t=this.getDropdownPrefixCls()+"-"+e.animation),t},getDropdownPrefixCls:function(){return this.props.prefixCls+"-dropdown"},saveMenu:function(e){this.popupMenu=e},render:function(){var e,t=this.props,n=t.onPopupFocus,r=a(t,["onPopupFocus"]),s=r.multiple,u=r.visible,p=r.inputValue,d=r.dropdownAlign,h=this.getDropdownPrefixCls(),y=(e={},o(e,r.dropdownClassName,!!r.dropdownClassName),o(e,h+"--"+(s?"multiple":"single"),1),e),v=this.getDropdownElement({menuItems:r.options,onPopupFocus:n,multiple:s,inputValue:p,visible:u});return c["default"].createElement(l["default"],i({},r,{showAction:r.disabled?[]:["click"],hideAction:r.disabled?[]:["blur"],ref:"trigger",popupPlacement:"bottomLeft",builtinPlacements:m,prefixCls:h,popupTransitionName:this.getDropdownTransitionName(),onPopupVisibleChange:r.onDropdownVisibleChange,popup:v,popupAlign:d,popupVisible:u,getPopupContainer:r.getPopupContainer,popupClassName:(0,f["default"])(y),popupStyle:r.dropdownStyle}),r.children)}});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}),t.OptGroup=t.Option=void 0;var o=n(343),a=r(o),i=n(102),s=r(i),l=n(41),u=r(l);a["default"].Option=s["default"],a["default"].OptGroup=u["default"],t.Option=s["default"],t.OptGroup=u["default"],t["default"]=a["default"]},17,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 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 i=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}}(),s=function(e,t,n){for(var r=!0;r;){var o=e,a=t,i=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,a);if(void 0!==s){if("value"in s)return s.value;var l=s.get;if(void 0===l)return;return l.call(i)}var u=Object.getPrototypeOf(o);if(null===u)return;e=u,t=a,n=i,r=!0,s=u=void 0}},l=n(1),u=r(l),c=n(107),p=r(c),f=function(e){function t(e){o(this,t),s(Object.getPrototypeOf(t.prototype),"constructor",this).call(this,e),this.state={isTooltipVisible:!1}}return a(t,e),i(t,[{key:"showTooltip",value:function(){this.setState({isTooltipVisible:!0})}},{key:"hideTooltip",value:function(){this.setState({isTooltipVisible:!1})}},{key:"render",value:function(){var e=this.props,t=e.className,n=e.tipTransitionName,r=e.tipFormatter,o=e.vertical,a=e.offset,i=e.value,s=e.dragging,l=e.noTip,c=o?{bottom:a+"%"}:{left:a+"%"},f=u["default"].createElement("div",{className:t,style:c,onMouseUp:this.showTooltip.bind(this),onMouseEnter:this.showTooltip.bind(this),onMouseLeave:this.hideTooltip.bind(this)});if(l)return f;var d=s||this.state.isTooltipVisible;return u["default"].createElement(p["default"],{prefixCls:t.replace("slider-handle","tooltip"),placement:"top",visible:d,overlay:u["default"].createElement("span",null,r(i)),delay:0,transitionName:n},f)}}]),t}(u["default"].Component);t["default"]=f,f.propTypes={className:u["default"].PropTypes.string,vertical:u["default"].PropTypes.bool,offset:u["default"].PropTypes.number,tipTransitionName:u["default"].PropTypes.string,tipFormatter:u["default"].PropTypes.func,value:u["default"].PropTypes.number,dragging:u["default"].PropTypes.bool,noTip:u["default"].PropTypes.bool},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 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},i=n(1),s=r(i),l=n(2),u=r(l),c=function(e){var t=e.className,n=e.vertical,r=e.marks,i=e.included,l=e.upperBound,c=e.lowerBound,p=e.max,f=e.min,d=Object.keys(r),h=d.length,y=100/(h-1),v=.9*y,m=p-f,g=d.map(parseFloat).sort(function(e,t){return e-t}).map(function(e){var p,d=!i&&e===l||i&&l>=e&&e>=c,h=(0,u["default"])((p={},o(p,t+"-text",!0),o(p,t+"-text-active",d),p)),y={marginBottom:"-200%",bottom:(e-f)/m*100+"%"},g={width:v+"%",marginLeft:-v/2+"%",left:(e-f)/m*100+"%"},b=n?y:g,P=r[e],O="object"==typeof P&&!s["default"].isValidElement(P),C=O?P.label:P,T=O?a({},b,P.style):b;return s["default"].createElement("span",{className:h,style:T,key:e},C)});return s["default"].createElement("div",{className:t},g)};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,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 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 s(){}function l(e){return e.touches.length>1||"touchend"===e.type.toLowerCase()&&e.touches.length>0}function u(e,t){return e?t.touches[0].clientY:t.touches[0].pageX}function c(e,t){return e?t.clientY:t.pageX}function p(e){e.stopPropagation(),e.preventDefault()}Object.defineProperty(t,"__esModule",{value:!0});var f=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=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}}(),h=function(e,t,n){for(var r=!0;r;){var o=e,a=t,i=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,a);if(void 0!==s){if("value"in s)return s.value;var l=s.get;if(void 0===l)return;return l.call(i)}var u=Object.getPrototypeOf(o);if(null===u)return;e=u,t=a,n=i,r=!0,s=u=void 0}},y=n(1),v=r(y),m=n(6),g=n(2),b=r(g),P=n(351),O=r(P),C=n(347),T=r(C),w=n(350),x=r(w),E=n(348),S=r(E),k=function(e){function t(e){a(this,t),h(Object.getPrototypeOf(t.prototype),"constructor",this).call(this,e);var n=e.range,r=e.min,o=e.max,i=n?[r,r]:r,s="defaultValue"in e?e.defaultValue:i,l=void 0!==e.value?e.value:s,u=void 0,c=void 0;e.range?(c=this.trimAlignValue(l[0]),u=this.trimAlignValue(l[1])):u=this.trimAlignValue(l);var p=void 0;p=e.range&&u===c&&c===o?"lowerBound":"upperBound",this.state={handle:null,recent:p,upperBound:u,lowerBound:c||r}}return i(t,e),d(t,[{key:"componentWillReceiveProps",value:function(e){if("value"in e||"min"in e||"max"in e){var t=this.state,n=t.lowerBound,r=t.upperBound;if(e.range){var o=e.value||[n,r],a=this.trimAlignValue(o[1],e),i=this.trimAlignValue(o[0],e);if(i===n&&a===r)return;this.setState({upperBound:a,lowerBound:i}),(this.isValueOutOfBounds(r,e)||this.isValueOutOfBounds(n,e))&&this.props.onChange([i,a])}else{var o=void 0!==e.value?e.value:r,s=this.trimAlignValue(o,e);if(s===r&&n===e.min)return;this.setState({upperBound:s,lowerBound:e.min}),this.isValueOutOfBounds(r,e)&&this.props.onChange(s)}}}},{key:"onChange",value:function(e){var t=this.props,n=!("value"in t);n?this.setState(e):e.handle&&this.setState({handle:e.handle});var r=f({},this.state,e),o=t.range?[r.lowerBound,r.upperBound]:r.upperBound;t.onChange(o)}},{key:"onMouseMove",value:function(e){var t=c(this.props.vertical,e);this.onMove(e,t)}},{key:"onTouchMove",value:function(e){if(l(e))return void this.end("touch");var t=u(this.props.vertical,e);this.onMove(e,t)}},{key:"onMove",value:function(e,t){p(e);var n=this.props,r=this.state,a=t-this.startPosition;a=this.props.vertical?-a:a;var i=a/this.getSliderLength()*(n.max-n.min),s=this.trimAlignValue(this.startValue+i),l=r[r.handle];return s!==l?n.allowCross&&s<r.lowerBound&&"upperBound"===r.handle?void this.onChange({handle:"lowerBound",lowerBound:s,upperBound:this.state.lowerBound}):n.allowCross&&s>r.upperBound&&"lowerBound"===r.handle?void this.onChange({handle:"upperBound",upperBound:s,lowerBound:this.state.upperBound}):void this.onChange(o({},r.handle,s)):void 0}},{key:"onTouchStart",value:function(e){if(!l(e)){var t=u(this.props.vertical,e);this.onStart(t),this.addDocumentEvents("touch"),p(e)}}},{key:"onMouseDown",value:function(e){if(0===e.button){var t=c(this.props.vertical,e);this.onStart(t),this.addDocumentEvents("mouse"),p(e)}}},{key:"onStart",value: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,a=r.upperBound,i=r.lowerBound,s="upperBound";if(this.props.range){var l=Math.abs(a-n)>Math.abs(i-n);l&&(s="lowerBound");var u=a===i;u&&(s=r.recent),u&&n!==a&&(s=a>n?"lowerBound":"upperBound")}this.setState({handle:s,recent:s});var c=r[s];n!==c&&this.onChange(o({},s,n))}},{key:"getValue",value:function(){var e=this.state,t=e.lowerBound,n=e.upperBound;return this.props.range?[t,n]:n}},{key:"getSliderLength",value:function(){var e=this.refs.slider;return e?this.props.vertical?e.clientHeight:e.clientWidth:0}},{key:"getSliderStart",value:function(){var e=this.refs.slider,t=e.getBoundingClientRect();return this.props.vertical?t.top:t.left}},{key:"getPrecision",value:function(e){var t=e.toString(),n=0;return t.indexOf(".")>=0&&(n=t.length-t.indexOf(".")-1),n}},{key:"isValueOutOfBounds",value:function(e,t){return e<t.min||e>t.max}},{key:"trimAlignValue",value:function(e,t){var n=this.state||{},r=n.handle,o=n.lowerBound,a=n.upperBound,i=f({},this.props,t||{}),s=i.marks,l=i.step,u=i.min,c=i.max,p=i.allowCross,d=e;u>=d&&(d=u),d>=c&&(d=c),!p&&"upperBound"===r&&o>=d&&(d=o),!p&&"lowerBound"===r&&d>=a&&(d=a);var h=Object.keys(s).map(parseFloat);if(null!==l){var y=Math.round(d/l)*l;h.push(y)}var v=h.map(function(e){return Math.abs(d-e)}),m=h[v.indexOf(Math.min.apply(Math,v))];return null!==l?parseFloat(m.toFixed(this.getPrecision(l))):m}},{key:"calcOffset",value:function(e){var t=this.props,n=t.min,r=t.max,o=(e-n)/(r-n);return 100*o}},{key:"calcValue",value:function(e){var t=this.props,n=t.vertical,r=t.min,o=t.max,a=Math.abs(e/this.getSliderLength()),i=n?(1-a)*(o-r)+r:a*(o-r)+r;return i}},{key:"calcValueByPos",value:function(e){var t=e-this.getSliderStart(),n=this.trimAlignValue(this.calcValue(t));return n}},{key:"addDocumentEvents",value:function(e){"touch"===e?(this.onTouchMoveListener=m.Dom.addEventListener(document,"touchmove",this.onTouchMove.bind(this)),this.onTouchUpListener=m.Dom.addEventListener(document,"touchend",this.end.bind(this,"touch"))):"mouse"===e&&(this.onMouseMoveListener=m.Dom.addEventListener(document,"mousemove",this.onMouseMove.bind(this)),this.onMouseUpListener=m.Dom.addEventListener(document,"mouseup",this.end.bind(this,"mouse")))}},{key:"removeEvents",value:function(e){"touch"===e?(this.onTouchMoveListener.remove(),this.onTouchUpListener.remove()):"mouse"===e&&(this.onMouseMoveListener.remove(),this.onMouseUpListener.remove())}},{key:"end",value:function(e){this.removeEvents(e),this.props.onAfterChange(this.getValue()),this.setState({handle:null})}},{key:"render",value:function(){var e,t=this.state,n=t.handle,r=t.upperBound,a=t.lowerBound,i=this.props,l=i.className,u=i.prefixCls,c=i.disabled,p=i.vertical,f=i.dots,d=i.included,h=i.range,m=i.step,g=i.marks,P=i.max,C=i.min,T=i.tipTransitionName,w=i.tipFormatter,E=i.children,k=this.props.handle,j=this.calcOffset(r),_=this.calcOffset(a),N=u+"-handle",M=null===m||null===w,D=(0,y.cloneElement)(k,{className:N,noTip:M,tipTransitionName:T,tipFormatter:w,vertical:p,offset:j,value:r,dragging:"upperBound"===n}),A=null;h&&(A=(0,y.cloneElement)(k,{className:N,noTip:M,tipTransitionName:T,tipFormatter:w,vertical:p,offset:_,value:a,dragging:"lowerBound"===n}));var L=(0,b["default"])((e={},o(e,u,!0),o(e,u+"-disabled",c),o(e,l,!!l),o(e,u+"-vertical",this.props.vertical),e)),V=d||h;return v["default"].createElement("div",{ref:"slider",className:L,onTouchStart:c?s:this.onTouchStart.bind(this),onMouseDown:c?s:this.onMouseDown.bind(this)},D,A,v["default"].createElement(O["default"],{className:u+"-track",vertical:p,included:V,offset:_,length:j-_}),v["default"].createElement(x["default"],{prefixCls:u,vertical:p,marks:g,dots:f,step:m,included:V,lowerBound:a,upperBound:r,max:P,min:C}),v["default"].createElement(S["default"],{className:u+"-mark",vertical:p,marks:g,included:V,lowerBound:a,upperBound:r,max:P,min:C}),E)}}]),t}(v["default"].Component);k.propTypes={min:v["default"].PropTypes.number,max:v["default"].PropTypes.number,step:v["default"].PropTypes.number,defaultValue:v["default"].PropTypes.oneOfType([v["default"].PropTypes.number,v["default"].PropTypes.arrayOf(v["default"].PropTypes.number)]),value:v["default"].PropTypes.oneOfType([v["default"].PropTypes.number,v["default"].PropTypes.arrayOf(v["default"].PropTypes.number)]),marks:v["default"].PropTypes.object,included:v["default"].PropTypes.bool,className:v["default"].PropTypes.string,prefixCls:v["default"].PropTypes.string,disabled:v["default"].PropTypes.bool,children:v["default"].PropTypes.any,onBeforeChange:v["default"].PropTypes.func,onChange:v["default"].PropTypes.func,onAfterChange:v["default"].PropTypes.func,handle:v["default"].PropTypes.element,tipTransitionName:v["default"].PropTypes.string,tipFormatter:v["default"].PropTypes.func,dots:v["default"].PropTypes.bool,range:v["default"].PropTypes.bool,vertical:v["default"].PropTypes.bool,allowCross:v["default"].PropTypes.bool},k.defaultProps={prefixCls:"rc-slider",className:"",tipTransitionName:"",min:0,max:100,step:1,marks:{},handle:v["default"].createElement(T["default"],null),onBeforeChange:s,onChange:s,onAfterChange:s,tipFormatter:function(e){return e},included:!0,disabled:!1,dots:!1,range:!1,vertical:!1,allowCross:!0},t["default"]=k,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 a(e,t,n,r,o,a){(0,p["default"])(n?r>0:!0,"`Slider[step]` should be a positive number in order to make Slider[dots] work.");var i=Object.keys(t).map(parseFloat);if(n)for(var s=o;a>=s;s+=r)i.indexOf(s)>=0||i.push(s);return i}Object.defineProperty(t,"__esModule",{value:!0});var i=n(1),s=r(i),l=n(2),u=r(l),c=n(353),p=r(c),f=function(e){var t=e.prefixCls,n=e.vertical,r=e.marks,i=e.dots,l=e.step,c=e.included,p=e.lowerBound,f=e.upperBound,d=e.max,h=e.min,y=d-h,v=a(n,r,i,l,h,d).map(function(e){var r,a=Math.abs(e-h)/y*100+"%",i=n?{bottom:a}:{left:a},l=!c&&e===f||c&&f>=e&&e>=p,d=(0,u["default"])((r={},o(r,t+"-dot",!0),o(r,t+"-dot-active",l),r));return s["default"].createElement("span",{className:d,style:i,key:e})});return s["default"].createElement("div",{className:t+"-step"},v)};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=n(1),a=r(o),i=function(e){var t=e.className,n=e.included,r=e.vertical,o=e.offset,i=e.length,s={visibility:n?"visible":"hidden"};return r?(s.bottom=o+"%",s.height=i+"%"):(s.left=o+"%",s.width=i+"%"),a["default"].createElement("div",{className:t,style:s})};t["default"]=i,e.exports=t["default"]},function(e,t,n){"use strict";e.exports=n(349)},17,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 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 i(e){var t,n,r=e.className,i=e.prefixCls,l=e.style,c=e.tailWidth,f=e.status,d=void 0===f?"wait":f,h=e.iconPrefix,y=e.icon,v=e.wrapperStyle,m=e.adjustMarginRight,g=e.stepLast,b=e.stepNumber,P=e.description,O=e.title,C=a(e,["className","prefixCls","style","tailWidth","status","iconPrefix","icon","wrapperStyle","adjustMarginRight","stepLast","stepNumber","description","title"]),T=(0,p["default"])((t={},o(t,i+"-icon",!0),o(t,h+"icon",!0),o(t,h+"icon-"+y,y),o(t,h+"icon-check",!y&&"finish"===d),o(t,h+"icon-cross",!y&&"error"===d),t)),w=y||"finish"===d||"error"===d?u["default"].createElement("span",{className:T}):u["default"].createElement("span",{className:i+"-icon"},b),x=(0,p["default"])((n={},o(n,i+"-item",!0),o(n,i+"-item-last",g),o(n,i+"-status-"+d,!0),o(n,i+"-custom",y),o(n,r,!!r),n));return u["default"].createElement("div",s({},C,{className:x,style:s({width:c,marginRight:m},l)}),g?"":u["default"].createElement("div",{className:i+"-tail"},u["default"].createElement("i",null)),u["default"].createElement("div",{className:i+"-step"},u["default"].createElement("div",{className:i+"-head",style:{background:v.background||v.backgroundColor}},u["default"].createElement("div",{className:i+"-head-inner"},w)),u["default"].createElement("div",{className:i+"-main"},u["default"].createElement("div",{className:i+"-title",style:{background:v.background||v.backgroundColor}},O),P?u["default"].createElement("div",{className:i+"-description"},P):"")))}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(2),p=r(c);i.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=i},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],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(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 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},p=n(1),f=r(p),d=n(4),h=r(d),y=n(2),v=r(y),m=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.getBoundingClientRect().width;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,p=n.direction,d=n.labelPlacement,h=n.iconPrefix,y=n.status,m=n.size,g=i(n,["prefixCls","style","className","children","direction","labelPlacement","iconPrefix","status","size"]),b=u.length-1,P=this.state.lastStepOffsetWidth>0,O=(0,v["default"])((e={},a(e,r,!0),a(e,r+"-"+m,m),a(e,r+"-"+p,!0),a(e,r+"-label-"+d,"horizontal"===p),a(e,r+"-hidden",!P),a(e,l,l),e));return f["default"].createElement("div",c({className:O,style:s},g),f["default"].Children.map(u,function(e,o){var a="vertical"!==p&&o!==b&&P?100/b+"%":null,i="vertical"===p||o===b?null:-(t.state.lastStepOffsetWidth/b+1),l={stepNumber:(o+1).toString(),stepLast:o===b,tailWidth:a,adjustMarginRight:i,prefixCls:r,iconPrefix:h,wrapperStyle:s};return"error"===n.status&&o===n.current-1&&(l.className=n.prefixCls+"-next-error"),e.props.status||(o===n.current?l.status=y:o<n.current?l.status="finish":l.status="wait"),f["default"].cloneElement(e,l)},this))},t}(f["default"].Component);t["default"]=m,m.propTypes={prefixCls:p.PropTypes.string,iconPrefix:p.PropTypes.string,direction:p.PropTypes.string,labelPlacement:p.PropTypes.string,children:p.PropTypes.any,status:p.PropTypes.string,size:p.PropTypes.string},m.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(355);r.Step=n(354),e.exports=r},function(e,t,n){"use strict";function r(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 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 a(){}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},s=n(1),l=n(2),u=s.createClass({displayName:"Switch",propTypes:{className:s.PropTypes.string,prefixCls:s.PropTypes.string,disabled:s.PropTypes.bool,checkedChildren:s.PropTypes.any,unCheckedChildren:s.PropTypes.any,onChange:s.PropTypes.func,onMouseUp:s.PropTypes.func},getDefaultProps:function(){return{prefixCls:"rc-switch",checkedChildren:null,unCheckedChildren:null,className:"",defaultChecked:!1,onChange:a}},getInitialState:function(){var e=this.props,t=!1;return t="checked"in e?!!e.checked:!!e.defaultChecked,{checked:t}},componentWillReceiveProps:function(e){"checked"in e&&this.setState({checked:!!e.checked})},setChecked:function(e){ "checked"in this.props||this.setState({checked:e}),this.props.onChange(e)},toggle:function(){var e=!this.state.checked;this.setChecked(e)},handleKeyDown:function(e){37===e.keyCode&&this.setChecked(!1),39===e.keyCode&&this.setChecked(!0)},handleMouseUp:function(e){this.refs.node&&this.refs.node.blur(),this.props.onMouseUp&&this.props.onMouseUp(e)},render:function(){var e,t=this.props,n=t.className,u=t.prefixCls,c=t.disabled,p=t.checkedChildren,f=t.unCheckedChildren,d=r(t,["className","prefixCls","disabled","checkedChildren","unCheckedChildren"]),h=this.state.checked,y=l((e={},o(e,n,!!n),o(e,u,!0),o(e,u+"-checked",h),o(e,u+"-disabled",c),e));return s.createElement("span",i({},d,{className:y,tabIndex:"0",ref:"node",onKeyDown:this.handleKeyDown,onClick:c?a:this.toggle,onMouseUp:this.handleMouseUp}),s.createElement("span",{className:u+"-inner"},h?p:f))}});e.exports=u},function(e,t,n){"use strict";e.exports=n(357)},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 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},i=n(1),s=r(i),l=n(360),u=r(l),c=s["default"].createClass({displayName:"Table",propTypes:{data:s["default"].PropTypes.array,expandIconAsCell:s["default"].PropTypes.bool,defaultExpandAllRows:s["default"].PropTypes.bool,expandedRowKeys:s["default"].PropTypes.array,defaultExpandedRowKeys:s["default"].PropTypes.array,useFixedHeader:s["default"].PropTypes.bool,columns:s["default"].PropTypes.array,prefixCls:s["default"].PropTypes.string,bodyStyle:s["default"].PropTypes.object,style:s["default"].PropTypes.object,rowKey:s["default"].PropTypes.func,rowClassName:s["default"].PropTypes.func,expandedRowClassName:s["default"].PropTypes.func,childrenColumnName:s["default"].PropTypes.string,onExpand:s["default"].PropTypes.func,onExpandedRowsChange:s["default"].PropTypes.func,indentSize:s["default"].PropTypes.number,onRowClick:s["default"].PropTypes.func,columnsPageRange:s["default"].PropTypes.array,columnsPageSize:s["default"].PropTypes.number,expandIconColumnIndex:s["default"].PropTypes.number,showHeader:s["default"].PropTypes.bool,footer:s["default"].PropTypes.func,scroll:s["default"].PropTypes.object,rowRef:s["default"].PropTypes.func},getDefaultProps:function(){return{data:[],useFixedHeader:!1,expandIconAsCell:!1,columns:[],defaultExpandAllRows:!1,defaultExpandedRowKeys:[],rowKey:function(e){return e.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}}},getInitialState:function(){var e=this.props,t=[],n=[].concat(o(e.data));if(e.defaultExpandAllRows)for(var r=0;r<n.length;r++){var a=n[r];a[e.childrenColumnName]&&a[e.childrenColumnName].length>0&&(t.push(e.rowKey(a)),n=n.concat(a[e.childrenColumnName]))}else t=e.expandedRowKeys||e.defaultExpandedRowKeys;return{expandedRowKeys:t,data:e.data,currentColumnsPage:0,currentHoverIndex:null,scrollPosition:"left"}},componentDidMount:function(){this.refs.headTable&&(this.refs.headTable.scrollLeft=0),this.refs.bodyTable&&(this.refs.bodyTable.scrollLeft=0)},componentWillReceiveProps:function(e){"data"in e&&this.setState({data:e.data}),"expandedRowKeys"in e&&this.setState({expandedRowKeys:e.expandedRowKeys})},onExpandedRowsChange:function(e){this.props.expandedRowKeys||this.setState({expandedRowKeys:e}),this.props.onExpandedRowsChange(e)},onExpanded:function(e,t){var n=this.findExpandedRow(t);if("undefined"==typeof n||e){if(!n&&e){var r=this.getExpandedRows().concat();r.push(this.props.rowKey(t)),this.onExpandedRowsChange(r)}}else this.onRowDestroy(t);this.props.onExpand(e,t)},onRowDestroy:function(e){var t=this.getExpandedRows().concat(),n=this.props.rowKey(e),r=-1;t.forEach(function(e,t){e===n&&(r=t)}),-1!==r&&t.splice(r,1),this.onExpandedRowsChange(t)},getExpandedRows:function(){return this.props.expandedRowKeys||this.state.expandedRowKeys},getHeader:function(e,t){var n=this.props,r=n.showHeader,o=n.expandIconAsCell,a=n.prefixCls,i=[];return o&&"right"!==t&&i.push({key:"rc-table-expandIconAsCell",className:a+"-expand-icon-th",title:""}),i=i.concat(e||this.getCurrentColumns()).map(function(e){return 0!==e.colSpan?s["default"].createElement("th",{key:e.key,colSpan:e.colSpan,className:e.className||""},e.title):void 0}),r?s["default"].createElement("thead",{className:a+"-thead"},s["default"].createElement("tr",null,i)):null},getExpandedRow:function(e,t,n,r,o){var a=this.props.prefixCls;return s["default"].createElement("tr",{key:e+"-extra-row",style:{display:n?"":"none"},className:a+"-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:"&nbsp;"))},getRowsByData:function(e,t,n,r,o){for(var i=this.props,l=i.childrenColumnName,c=i.expandedRowRender,p=[],f=i.rowKey,d=i.rowClassName,h=i.rowRef,y=i.expandedRowClassName,v=i.data.some(function(e){return e[l]}),m=i.onRowClick,g=this.isAnyColumnsFixed(),b="right"!==o?i.expandIconAsCell:!1,P="right"!==o?i.expandIconColumnIndex:-1,O=0;O<e.length;O++){var C=e[O],T=f?f(C,O):void 0,w=C[l],x=this.isRowExpanded(C),E=void 0;c&&x&&(E=c(C,O));var S=d(C,O);this.state.currentHoverIndex===O&&(S+=" "+i.prefixCls+"-row-hover");var k={};g&&(k.onHover=this.handleRowHover),p.push(s["default"].createElement(u["default"],a({indent:n,indentSize:i.indentSize,needIndentSpaced:v,className:S,record:C,expandIconAsCell:b,onDestroy:this.onRowDestroy,index:O,visible:t,onExpand:this.onExpanded,expandable:w||c,expanded:x,prefixCls:i.prefixCls+"-row",childrenColumnName:l,columns:r||this.getCurrentColumns(),expandIconColumnIndex:P,onRowClick:m},k,{key:T,ref:h(C,O)})));var j=t&&x;E&&x&&p.push(this.getExpandedRow(T,E,j,y(C,O),o)),w&&(p=p.concat(this.getRowsByData(w,j,n+1)))}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,i=t.prefixCls,s=this.state.currentColumnsPage;return!r||r[0]>r[1]?n:n.map(function(t,n){var l=a({},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]),(u>n||n>c)&&(l.className=l.className||"",l.className+=" "+i+"-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,i=o.prefixCls,l=o.scroll,u=void 0===l?{}:l,c=this.props.useFixedHeader,p=a({},this.props.bodyStyle),f="";(u.x||n)&&(f=i+"-fixed",p.overflowX=p.overflowX||"auto"),u.y&&(p.height=p.height||u.y,p.overflowY=p.overflowY||"auto",c=!0);var d=function(){var t=arguments.length<=0||void 0===arguments[0]?!0:arguments[0],o=arguments.length<=1||void 0===arguments[1]?!0:arguments[1],a={};return!n&&u.x&&(u.x===!0?a.tableLayout="fixed":a.width=u.x),s["default"].createElement("table",{className:f,style:a},e.getColGroup(n,r),t?e.getHeader(n,r):null,o?s["default"].createElement("tbody",{className:i+"-tbody"},e.getRows(n,r)):null)},h=void 0;c&&(h=s["default"].createElement("div",{className:i+"-header",ref:n?null:"headTable"},d(!0,!1)));var y=s["default"].createElement("div",{className:i+"-body",style:p,ref:"bodyTable",onMouseEnter:this.detectScrollTarget,onScroll:this.handleBodyScroll},d(!c));if(n&&n.length){var v=void 0;"left"===n[0].fixed||n[0].fixed===!0?v="fixedColumnsBodyLeft":"right"===n[0].fixed&&(v="fixedColumnsBodyRight"),delete p.overflowX,delete p.overflowY,y=s["default"].createElement("div",{className:i+"-body-outer",style:a({},p)},s["default"].createElement("div",{className:i+"-body-inner",ref:v,onMouseEnter:this.detectScrollTarget,onScroll:this.handleBodyScroll},d(!c)))}return s["default"].createElement("span",null,h,y)},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},getMaxColumnsPage:function(){var e=this.props,t=e.columnsPageRange,n=e.columnsPageSize;return Math.floor((t[1]-t[0]-1)/n)},goToColumnsPage:function(e){var t=this.getMaxColumnsPage(),n=e;0>n&&(n=0),n>t&&(n=t),this.setState({currentColumnsPage:n})},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,a=this.getMaxColumnsPage(),i=r+"-prev-columns-page";0===o&&(i+=" "+r+"-prev-columns-page-disabled");var l=s["default"].createElement("span",{className:i,onClick:this.prevColumnsPage}),u=r+"-next-columns-page";o===a&&(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.props.rowKey(e)});return n[0]},isRowExpanded:function(e){return"undefined"!=typeof this.findExpandedRow(e)},detectScrollTarget:function(e){this.scrollTarget=e.currentTarget},isAnyColumnsFixed:function(){return this.getCurrentColumns().some(function(e){return!!e.fixed})},isAnyColumnsLeftFixed:function(){return this.getCurrentColumns().some(function(e){return"left"===e.fixed||e.fixed===!0})},isAnyColumnsRightFixed:function(){return this.getCurrentColumns().some(function(e){return"right"===e.fixed})},handleBodyScroll:function(e){if(e.target===this.scrollTarget){var t=this.props.scroll||{};t.x&&e.target===this.refs.bodyTable&&(this.refs.headTable&&(this.refs.headTable.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"})),t.y&&(this.refs.fixedColumnsBodyLeft&&(this.refs.fixedColumnsBodyLeft.scrollTop=e.target.scrollTop),this.refs.fixedColumnsBodyRight&&(this.refs.fixedColumnsBodyRight.scrollTop=e.target.scrollTop),this.refs.bodyTable&&(this.refs.bodyTable.scrollTop=e.target.scrollTop))}},handleRowHover:function(e,t){e?this.setState({currentHoverIndex:t}):this.setState({currentHoverIndex: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.isAnyColumnsLeftFixed()&&s["default"].createElement("div",{className:t+"-fixed-left"},this.getLeftFixedTable()),s["default"].createElement("div",{className:r?t+"-scroll":""},this.getTable(),this.getFooter()),this.isAnyColumnsRightFixed()&&s["default"].createElement("div",{className:t+"-fixed-right"},this.getRightFixedTable()))}});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});var o=n(1),a=r(o),i=n(276),s=r(i),l=a["default"].createClass({displayName:"TableRow",propTypes:{onDestroy:a["default"].PropTypes.func,onRowClick:a["default"].PropTypes.func,record:a["default"].PropTypes.object,prefixCls:a["default"].PropTypes.string,expandIconColumnIndex:a["default"].PropTypes.number,onHover:a["default"].PropTypes.func},getDefaultProps:function(){return{onRowClick:function(){},onDestroy:function(){},expandIconColumnIndex:0,onHover:function(){}}},componentWillUnmount:function(){this.props.onDestroy(this.props.record)},isInvalidRenderCellText:function(e){return e&&!a["default"].isValidElement(e)&&"[object Object]"===Object.prototype.toString.call(e)},render:function u(){for(var e=this.props,t=e.prefixCls,n=e.columns,r=e.record,o=e.index,i=[],l=e.expanded,c=e.expandable,p=e.expandIconAsCell,f=e.indent,d=e.indentSize,h=e.needIndentSpaced,y=e.onRowClick,v=e.expandIconColumnIndex,m=0;m<n.length;m++){var g=n[m],b=g.className||"",u=g.render,P=s["default"].get(r,g.dataIndex),O=void 0,C=void 0,T=void 0,w=void 0,x=!1;c?O=a["default"].createElement("span",{className:t+"-expand-icon "+t+"-"+(l?"expanded":"collapsed"),onClick:e.onExpand.bind(null,!l,r)}):h&&(O=a["default"].createElement("span",{className:t+"-expand-icon "+t+"-spaced"}));var E=p?!1:m===v;p&&0===m&&i.push(a["default"].createElement("td",{className:t+"-expand-icon-cell",key:"rc-table-expand-icon-cell"},O)),u&&(P=u(P,r,o),this.isInvalidRenderCellText(P)&&(C=P.props||{},w=C.rowSpan,T=C.colSpan,P=P.children)),this.isInvalidRenderCellText(P)&&(P=null),0!==w&&0!==T||(x=!0);var S=a["default"].createElement("span",{style:{paddingLeft:d*f+"px"},className:t+"-indent indent-level-"+f});x||i.push(a["default"].createElement("td",{key:g.key,colSpan:T,rowSpan:w,className:b},E?S:null,E?O:null,P))}return a["default"].createElement("tr",{onClick:y.bind(null,r,o),onMouseEnter:e.onHover.bind(null,!0,o),onMouseLeave:e.onHover.bind(null,!1,o),className:t+" "+e.className+" "+t+"-level-"+f,style:e.visible?null:{display:"none"}},i)}});t["default"]=l,e.exports=t["default"]},function(e,t,n){"use strict";e.exports=n(359)},function(e,t,n){"use strict";function r(e){var t=e.refs,n=t.nav,r=(0,o.offset)(n),a=t.inkBar,i=t.activeTab,s=e.props.tabPosition;if(i){var l=i,u=(0,o.offset)(l),c=(0,o.getTransformPropertyName)();if("top"===s||"bottom"===s){var p=u.left-r.left;c?(a.style[c]="translate3d("+p+"px,0,0)",a.style.width=l.offsetWidth+"px",a.style.height=""):(a.style.left=p+"px",a.style.top="",a.style.bottom="",a.style.right=n.offsetWidth-p-l.offsetWidth+"px")}else{var f=u.top-r.top;c?(a.style[c]="translate3d(0,"+f+"px,0)",a.style.height=l.offsetHeight+"px",a.style.width=""):(a.style.left="",a.style.right="",a.style.top=f+"px",a.style.bottom=n.offsetHeight-f-l.offsetHeight+"px")}}a.style.display=i?"block":"none"}Object.defineProperty(t,"__esModule",{value:!0});var o=n(104);t["default"]={componentDidUpdate:function(){r(this)},componentDidMount:function(){r(this)}},e.exports=t["default"]},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,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(){}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},s=n(1),l=r(s),u=n(2),c=r(u),p=n(362),f=r(p),d=n(104),h={"float":"right"},y=l["default"].createClass({displayName:"Nav",propTypes:{tabPosition:s.PropTypes.string,tabBarExtraContent:s.PropTypes.any,onTabClick:s.PropTypes.func,onKeyDown:s.PropTypes.func},mixins:[f["default"]],getInitialState:function(){return{next:!1,offset:0,prev:!1}},componentDidMount:function(){this.componentDidUpdate()},componentDidUpdate:function(e){var t=this.props;if(e&&e.tabPosition!==t.tabPosition)return void this.setOffset(0);var n=this.refs.nav,r=this.getOffsetWH(n),o=this.refs.navWrap,a=this.getOffsetWH(o),i=this.state,s=i.offset,l=a-r,u=this.state,c=u.next,p=u.prev;l>=0?(c=!1,this.setOffset(0),s=0):s>l?c=!0:(c=!1,this.setOffset(l),s=l),p=0>s,this.setNext(c),this.setPrev(p);var f={next:c,prev:p};this.isNextPrevShown(i)!==this.isNextPrevShown(f)?this.setNextPrev({},this.scrollToActiveTab):e&&t.activeKey===e.activeKey||this.scrollToActiveTab()},onTabClick:function(e){this.props.onTabClick(e)},setNextPrev:function(e,t){this.setState(e,t)},getTabs:function(){var e=this,t=this.props,n=t.panels,r=t.activeKey,o=[],a=t.prefixCls;return l["default"].Children.forEach(n,function(t){var n=t.key,s=r===n?a+"-tab-active":"";s+=" "+a+"-tab";var u={};t.props.disabled?s+=" "+a+"-tab-disabled":u={onClick:e.onTabClick.bind(e,n)};var c={};r===n&&(c.ref="activeTab"),o.push(l["default"].createElement("div",i({role:"tab","aria-disabled":t.props.disabled?"true":"false","aria-selected":r===n?"true":"false"},u,{className:s,key:n},c),l["default"].createElement("div",{className:a+"-tab-inner"},t.props.tab)))}),o},getOffsetWH:function(e){var t=this.props.tabPosition,n="offsetWidth";return"left"!==t&&"right"!==t||(n="offsetHeight"),e[n]},getOffsetLT:function(e){var t=this.props.tabPosition,n="left";return"left"!==t&&"right"!==t||(n="top"),e.getBoundingClientRect()[n]},setOffset:function(e){var t=Math.min(0,e);if(this.state.offset!==t){this.setState({offset:t});var n={},r=this.props.tabPosition,o=(0,d.getTransformPropertyName)();n="left"===r||"right"===r?o?{name:o,value:"translate3d(0,"+t+"px,0)"}:{name:"top",value:t+"px"}:o?{name:o,value:"translate3d("+t+"px,0,0)"}:{name:"left",value:t+"px"},this.refs.nav.style[n.name]=n.value}},setPrev:function(e){this.state.prev!==e&&this.setState({prev:e})},setNext:function(e){this.state.next!==e&&this.setState({next:e})},isNextPrevShown:function(e){return e.next||e.prev},scrollToActiveTab:function(){var e=this.refs,t=e.activeTab,n=e.navWrap;if(t){var r=this.getOffsetWH(t),o=this.getOffsetWH(n),a=this.state.offset,i=this.getOffsetLT(n),s=this.getOffsetLT(t);i>s?(a+=i-s,this.setState({offset:a})):s+r>i+o&&(a-=s+r-(i+o),this.setState({offset:a}))}},prev:function(){var e=this.refs.navWrap,t=this.getOffsetWH(e),n=this.state,r=n.offset;this.setOffset(r+t)},next:function(){var e=this.refs.navWrap,t=this.getOffsetWH(e),n=this.state,r=n.offset;this.setOffset(r-t)},render:function(){var e=this.props,t=this.state,n=e.prefixCls,r=this.getTabs(),i=e.tabMovingDirection,s=n+"-ink-bar";i&&(s+=" "+n+"-ink-bar-transition-"+i);var u=void 0,p=void 0,f=t.prev||t.next;if(f){var d,y;p=l["default"].createElement("span",{onClick:t.prev?this.prev:a,unselectable:"unselectable",className:(0,c["default"])((d={},o(d,n+"-tab-prev",1),o(d,n+"-tab-btn-disabled",!t.prev),d))},l["default"].createElement("span",{className:n+"-tab-prev-icon"})),u=l["default"].createElement("span",{onClick:t.next?this.next:a,unselectable:"unselectable",className:(0,c["default"])((y={},o(y,n+"-tab-next",1),o(y,n+"-tab-btn-disabled",!t.next),y))},l["default"].createElement("span",{className:n+"-tab-next-icon"}))}var v=this.props.tabBarExtraContent;return l["default"].createElement("div",{role:"tablist",className:n+"-bar",tabIndex:"0",onKeyDown:this.props.onKeyDown},v?l["default"].createElement("div",{style:h},v):null,l["default"].createElement("div",{className:n+"-nav-container "+(f?n+"-nav-container-scrolling":""),style:e.style,ref:"container"},p,u,l["default"].createElement("div",{className:n+"-nav-wrap",ref:"navWrap"},l["default"].createElement("div",{className:n+"-nav-scroll"},l["default"].createElement("div",{className:n+"-nav",ref:"nav"},l["default"].createElement("div",{className:s,ref:"inkBar"}),r)))))}});t["default"]=y,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 a(){}function i(e){var t=void 0;return l["default"].Children.forEach(e.children,function(e){t||e.props.disabled||(t=e.key)}),t}Object.defineProperty(t,"__esModule",{value:!0});var s=n(1),l=r(s),u=n(363),c=r(u),p=n(103),f=r(p),d=n(364),h=r(d),y=n(9),v=r(y),m=n(2),g=r(m),b=l["default"].createClass({displayName:"Tabs",propTypes:{destroyInactiveTabPane:s.PropTypes.bool,onTabClick:s.PropTypes.func,onChange:s.PropTypes.func,children:s.PropTypes.any,tabBarExtraContent:s.PropTypes.any,animation:s.PropTypes.string,prefixCls:s.PropTypes.string,className:s.PropTypes.string,tabPosition:s.PropTypes.string},getDefaultProps:function(){return{prefixCls:"rc-tabs",destroyInactiveTabPane:!1,tabBarExtraContent:null,onChange:a,tabPosition:"top",style:{},contentStyle:{},navStyle:{},onTabClick:a}},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){var t=this.state.activeKey;if("activeKey"in e&&(t=e.activeKey,!t))return void this.setState({activeKey:t});var n=void 0;l["default"].Children.forEach(e.children,function(e){e.key===t&&(n=!0)}),n?this.setActiveKey(t,e):this.setActiveKey(i(e),e)},onTabClick:function(e){this.setActiveKey(e),this.props.onTabClick(e),this.state.activeKey!==e&&this.props.onChange(e)},onNavKeyDown:function(e){var t=e.keyCode;if(t===c["default"].RIGHT||t===c["default"].DOWN){e.preventDefault();var n=this.getNextActiveKey(!0);this.onTabClick(n)}else if(t===c["default"].LEFT||t===c["default"].UP){e.preventDefault();var r=this.getNextActiveKey(!1);this.onTabClick(r)}},getNextActiveKey:function(e){var t=this.state.activeKey,n=[];l["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,a){e.key===t&&(o=a===r-1?n[0].key:n[a+1].key)}),o},getTabPanes:function(){var e=this.state,t=this.props,n=e.activeKey,r=t.children,o=[];return l["default"].Children.forEach(r,function(e){var r=e.key,a=n===r;o.push(l["default"].cloneElement(e,{active:a,rootPrefixCls:t.prefixCls}))}),o},getIndexPair:function(e,t,n){var r=[];l["default"].Children.forEach(e.children,function(e){r.push(e.key)});var o=r.indexOf(t),a=r.indexOf(n);return{currentIndex:o,nextIndex:a}},setActiveKey:function(e,t){var n=t||this.props,r=this.state.activeKey;if(!(r===e||"activeKey"in n&&n===this.props))if(r){var o=this.getIndexPair(n,r,e),a=o.currentIndex,i=o.nextIndex;if(-1===a){var s=this.getIndexPair(this.props,r,e);a=s.currentIndex,i=s.nextIndex}var l=a>i?"backward":"forward";this.setState({activeKey:e,tabMovingDirection:l})}else this.setState({activeKey:e})},render:function(){var e,t=this.props,n=t.destroyInactiveTabPane,r=t.prefixCls,a=t.tabPosition,i=t.className,s=t.animation,u=(0,g["default"])((e={},o(e,r,1),o(e,r+"-"+a,1),o(e,i,!!i),e)),c=this.state.tabMovingDirection,p=this.getTabPanes(),f=void 0;f=t.transitionName&&t.transitionName[c||"backward"],!f&&s&&(f=r+"-"+s+"-"+(c||"backward")),n&&(p=p.filter(function(e){return e.props.active})),f&&(p=n?l["default"].createElement(v["default"],{exclusive:!0,component:"div",transitionName:f},p):l["default"].createElement(v["default"],{showProp:"active",exclusive:!0,component:"div",transitionName:f},p));var d=[l["default"].createElement(h["default"],{prefixCls:r,key:"nav",onKeyDown:this.onNavKeyDown,tabBarExtraContent:this.props.tabBarExtraContent,tabPosition:a,style:t.navStyle,onTabClick:this.onTabClick,tabMovingDirection:c,panels:this.props.children,activeKey:this.state.activeKey}),l["default"].createElement("div",{className:r+"-content",style:t.contentStyle,key:"content"},p)];return"bottom"===a&&d.reverse(),l["default"].createElement("div",{className:u,style:t.style},d)}});b.TabPane=f["default"],t["default"]=b,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(365),a=r(o),i=n(103),s=r(i);t["default"]=a["default"],t.TabPane=s["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(105),a=r(o);t["default"]=a["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(38),a=r(o),i=n(79),s=r(i);t["default"]={clear:"Clear",format:a["default"],calendar:s["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(77),a=r(o),i=n(80),s=r(i);t["default"]={clear:"\u6e05\u9664",format:a["default"],calendar:s["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(1),a=r(o),i=n(373),s=r(i),l=n(10),u=r(l),c=function(e,t){var n=""+e;10>e&&(n="0"+e);var r=!1;return t&&t.indexOf(e)>=0&&(r=!0),{value:n,disabled:r}},p=a["default"].createClass({displayName:"Combobox",propTypes:{formatter:o.PropTypes.object,prefixCls:o.PropTypes.string,value:o.PropTypes.object,onChange:o.PropTypes.func,showHour:o.PropTypes.bool,gregorianCalendarLocale:o.PropTypes.object,showSecond:o.PropTypes.bool,hourOptions:o.PropTypes.array,minuteOptions:o.PropTypes.array,secondOptions:o.PropTypes.array,disabledHours:o.PropTypes.func,disabledMinutes:o.PropTypes.func,disabledSeconds:o.PropTypes.func,onCurrentSelectPanelChange:o.PropTypes.func},onItemChange:function(e,t){var n=this.props.onChange,r=this.props.value;r=r?r.clone():this.getNow().clone(),"hour"===e?r.setHourOfDay(t):"minute"===e?r.setMinutes(t):r.setSeconds(t),n(r)},onEnterSelectPanel:function(e){this.props.onCurrentSelectPanelChange(e)},getHourSelect:function(e){var t=this.props,n=t.prefixCls,r=t.hourOptions,o=t.disabledHours,i=t.showHour;if(!i)return null;var l=o();return a["default"].createElement(s["default"],{prefixCls:n,options:r.map(function(e){return c(e,l)}),selectedIndex:r.indexOf(e),type:"hour",onSelect:this.onItemChange,onMouseEnter:this.onEnterSelectPanel.bind(this,"hour")})},getMinuteSelect:function(e){var t=this.props,n=t.prefixCls,r=t.minuteOptions,o=t.disabledMinutes,i=this.props.value||this.getNow(),l=o(i.getHourOfDay());return a["default"].createElement(s["default"],{prefixCls:n,options:r.map(function(e){return c(e,l)}),selectedIndex:r.indexOf(e),type:"minute",onSelect:this.onItemChange,onMouseEnter:this.onEnterSelectPanel.bind(this,"minute")})},getSecondSelect:function(e){var t=this.props,n=t.prefixCls,r=t.secondOptions,o=t.disabledSeconds,i=t.showSecond;if(!i)return null;var l=this.props.value||this.getNow(),u=o(l.getHourOfDay(),l.getMinutes());return a["default"].createElement(s["default"],{prefixCls:n,options:r.map(function(e){return c(e,u)}),selectedIndex:r.indexOf(e),type:"second",onSelect:this.onItemChange,onMouseEnter:this.onEnterSelectPanel.bind(this,"second")})},getNow:function(){if(this.showNow)return this.showNow;var e=new u["default"](this.props.gregorianCalendarLocale);return e.setTime(Date.now()),this.showNow=e,e},render:function(){var e=this.props.prefixCls,t=this.props.value||this.getNow();return a["default"].createElement("div",{className:e+"-combobox"},this.getHourSelect(t.getHourOfDay()),this.getMinuteSelect(t.getMinutes()),this.getSecondSelect(t.getSeconds()))}});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),a=r(o),i=n(376),s=r(i),l=a["default"].createClass({displayName:"Header",propTypes:{formatter:o.PropTypes.object,prefixCls:o.PropTypes.string,gregorianCalendarLocale:o.PropTypes.object,locale:o.PropTypes.object,disabledDate:o.PropTypes.func,placeholder:o.PropTypes.string,value:o.PropTypes.object,hourOptions:o.PropTypes.array,minuteOptions:o.PropTypes.array,secondOptions:o.PropTypes.array,disabledHours:o.PropTypes.func,disabledMinutes:o.PropTypes.func,disabledSeconds:o.PropTypes.func,onChange:o.PropTypes.func,onClear:o.PropTypes.func,onEsc:o.PropTypes.func,allowEmpty:o.PropTypes.bool,currentSelectPanel:o.PropTypes.string},getInitialState:function(){var e=this.props.value;return{str:e&&this.props.formatter.format(e)||"",invalid:!1}},componentDidMount:function(){this.timer=setTimeout(this.selectRange,0)},componentWillReceiveProps:function(e){var t=e.value;this.setState({str:t&&e.formatter.format(t)||"",invalid:!1})},componentDidUpdate:function(){this.timer=setTimeout(this.selectRange,0)},componentWillUnmount:function(){clearTimeout(this.timer)},onInputChange:function(e){var t=e.target.value;this.setState({str:t});var n=null,r=this.props,o=r.formatter,a=r.gregorianCalendarLocale,i=r.hourOptions,s=r.minuteOptions,l=r.secondOptions,u=r.disabledHours,c=r.disabledMinutes,p=r.disabledSeconds,f=r.onChange,d=r.allowEmpty;if(t){var h=this.props.value;try{n=o.parse(t,{locale:a,obeyCount:!0})}catch(y){return void this.setState({invalid:!0})}if(!n)return void this.setState({invalid:!0});if(i.indexOf(n.getHourOfDay())<0||s.indexOf(n.getMinutes())<0||l.indexOf(n.getSeconds())<0)return void this.setState({invalid:!0});var v=u(),m=c(n.getHourOfDay()),g=p(n.getHourOfDay(),n.getMinutes());if(v&&v.indexOf(n.getHourOfDay())>=0||m&&m.indexOf(n.getMinutes())>=0||g&&g.indexOf(n.getSeconds())>=0)return void this.setState({invalid:!0});if(h&&n){if(h.getHourOfDay()!==n.getHourOfDay()||h.getMinutes()!==n.getMinutes()||h.getSeconds()!==n.getSeconds()){var b=h.clone();b.setHourOfDay(n.getHourOfDay()),b.setMinutes(n.getMinutes()),b.setSeconds(n.getSeconds()),f(b)}}else h!==n&&f(n)}else{if(!d)return void this.setState({invalid:!0});f(null)}this.setState({invalid:!1})},onKeyDown:function(e){27===e.keyCode&&this.props.onEsc()},onClear:function(){this.setState({str:""}),this.props.onClear()},getClearButton:function(){var e=this.props,t=e.locale,n=e.prefixCls,r=e.allowEmpty;return r?a["default"].createElement("a",{className:n+"-clear-btn",role:"button",title:t.clear,onMouseDown:this.onClear}):null},getInput:function(){var e=this.props,t=e.prefixCls,n=e.placeholder,r=this.state,o=r.invalid,i=r.str,s=o?t+"-input-invalid":"";return a["default"].createElement("input",{className:t+"-input "+s,ref:"input",onKeyDown:this.onKeyDown,value:i,placeholder:n,onChange:this.onInputChange})},selectRange:function(){if(this.refs.input.focus(),this.props.currentSelectPanel&&this.refs.input.value){var e=0,t=0;"hour"===this.props.currentSelectPanel?(e=0,t=this.refs.input.value.indexOf(":")):"minute"===this.props.currentSelectPanel?(e=this.refs.input.value.indexOf(":")+1,t=this.refs.input.value.lastIndexOf(":")):"second"===this.props.currentSelectPanel&&(e=this.refs.input.value.lastIndexOf(":")+1,t=this.refs.input.value.length),t-e===2&&(0,s["default"])(this.refs.input,e,t)}},render:function(){var e=this.props.prefixCls;return a["default"].createElement("div",{className:e+"-input-wrap"},this.getInput(),this.getClearButton())}});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 a(e,t,n){for(var r=[],o=0;e>o;o++)(!t||t.indexOf(o)<0||!n)&&r.push(o);return r}Object.defineProperty(t,"__esModule",{value:!0});var i=n(1),s=r(i),l=n(106),u=r(l),c=n(371),p=r(c),f=n(370),d=r(f),h=s["default"].createClass({ displayName:"Panel",propTypes:{prefixCls:i.PropTypes.string,value:i.PropTypes.object,locale:i.PropTypes.object,placeholder:i.PropTypes.string,gregorianCalendarLocale:i.PropTypes.object,formatter:i.PropTypes.object,disabledHours:i.PropTypes.func,disabledMinutes:i.PropTypes.func,disabledSeconds:i.PropTypes.func,hideDisabledOptions:i.PropTypes.bool,onChange:i.PropTypes.func,onEsc:i.PropTypes.func,allowEmpty:i.PropTypes.bool,showHour:i.PropTypes.bool,showSecond:i.PropTypes.bool,onClear:i.PropTypes.func},mixins:[u["default"]],getDefaultProps:function(){return{onChange:o,onClear:o}},getInitialState:function(){return{value:this.props.value,selectionRange:[]}},componentWillReceiveProps:function(e){var t=e.value;t&&this.setState({value:t})},onChange:function(e){this.setState({value:e}),this.props.onChange(e)},onClear:function(){this.props.onClear()},onCurrentSelectPanelChange:function(e){this.setState({currentSelectPanel:e})},render:function(){var e=this.props,t=e.locale,n=e.prefixCls,r=e.placeholder,o=e.disabledHours,i=e.disabledMinutes,l=e.disabledSeconds,u=e.hideDisabledOptions,c=e.allowEmpty,f=e.showHour,h=e.showSecond,y=e.formatter,v=e.gregorianCalendarLocale,m=this.state.value,g=o(),b=i(m?m.getHourOfDay():null),P=l(m?m.getHourOfDay():null,m?m.getMinutes():null),O=a(24,g,u),C=a(60,b,u),T=a(60,P,u);return s["default"].createElement("div",{className:n+"-inner"},s["default"].createElement(p["default"],{prefixCls:n,gregorianCalendarLocale:v,locale:t,value:m,currentSelectPanel:this.state.currentSelectPanel,onEsc:this.props.onEsc,formatter:y,placeholder:r,hourOptions:O,minuteOptions:C,secondOptions:T,disabledHours:o,disabledMinutes:i,disabledSeconds:l,onChange:this.onChange,onClear:this.onClear,allowEmpty:c}),s["default"].createElement(d["default"],{prefixCls:n,value:m,gregorianCalendarLocale:v,formatter:y,onChange:this.onChange,showHour:f,showSecond:h,hourOptions:O,minuteOptions:C,secondOptions:T,disabledHours:o,disabledMinutes:i,disabledSeconds:l,onCurrentSelectPanelChange:this.onCurrentSelectPanelChange}))}});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,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 a=n(1),i=r(a),s=n(4),l=r(s),u=n(2),c=r(u),p=function d(e,t,n){var r=window.requestAnimationFrame||function(){return setTimeout(arguments[0],10)};if(0>=n)return void(e.scrollTop=t);var o=t-e.scrollTop,a=o/n*10;r(function(){e.scrollTop=e.scrollTop+a,e.scrollTop!==t&&d(e,t,n-10)})},f=i["default"].createClass({displayName:"Select",propTypes:{prefixCls:a.PropTypes.string,options:a.PropTypes.array,gregorianCalendarLocale:a.PropTypes.object,selectedIndex:a.PropTypes.number,type:a.PropTypes.string,onSelect:a.PropTypes.func,onMouseEnter:a.PropTypes.func},componentDidMount:function(){this.scrollToSelected(0)},componentDidUpdate:function(e){e.selectedIndex!==this.props.selectedIndex&&this.scrollToSelected(120)},onSelect:function h(e){var t=this.props,h=t.onSelect,n=t.type;h(n,e)},getOptions:function(){var e=this,t=this.props,n=t.options,r=t.selectedIndex,a=t.prefixCls;return n.map(function(t,n){var s,l=(0,c["default"])((s={},o(s,a+"-select-option-selected",r===n),o(s,a+"-select-option-disabled",t.disabled),s)),u=null;return t.disabled||(u=e.onSelect.bind(e,+t.value)),i["default"].createElement("li",{className:l,key:n,onClick:u,disabled:t.disabled},t.value)})},scrollToSelected:function(e){var t=l["default"].findDOMNode(this),n=l["default"].findDOMNode(this.refs.list),r=this.props.selectedIndex;0>r&&(r=0);var o=n.children[r],a=o.offsetTop;p(t,a,e)},render:function(){if(0===this.props.options.length)return null;var e=this.props.prefixCls;return i["default"].createElement("div",{className:e+"-select",onMouseEnter:this.props.onMouseEnter},i["default"].createElement("ul",{ref:"list"},this.getOptions()))}});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){return"string"==typeof e?new i["default"](e,t.format):e}Object.defineProperty(t,"__esModule",{value:!0}),t.getFormatter=o;var a=n(27),i=r(a)},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n={adjustX:1,adjustY:1},r=[0,0],o={bottomLeft:{points:["tl","tl"],overflow:n,offset:[0,-3],targetOffset:r},bottomRight:{points:["tr","tr"],overflow:n,offset:[0,-3],targetOffset:r},topRight:{points:["br","br"],overflow:n,offset:[0,3],targetOffset:r},topLeft:{points:["bl","bl"],overflow:n,offset:[0,3],targetOffset:r}};t["default"]=o,e.exports=t["default"]},function(e,t){"use strict";function n(e,t,n){if(e.createTextRange){var r=e.createTextRange();r.collapse(!0),r.moveStart("character",t),r.moveEnd("character",n),r.select(),e.focus()}else e.setSelectionRange?(e.focus(),e.setSelectionRange(t,n)):"undefined"!=typeof e.selectionStart&&(e.selectionStart=t,e.selectionEnd=n,e.focus())}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){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 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},i=n(1),s=r(i),l=n(378),u=n(14),c=r(u),p=s["default"].createClass({displayName:"Tooltip",propTypes:{trigger:i.PropTypes.any,children:i.PropTypes.any,defaultVisible:i.PropTypes.bool,visible:i.PropTypes.bool,placement:i.PropTypes.string,transitionName:i.PropTypes.string,animation:i.PropTypes.any,onVisibleChange:i.PropTypes.func,afterVisibleChange:i.PropTypes.func,overlay:i.PropTypes.node.isRequired,overlayStyle:i.PropTypes.object,overlayClassName:i.PropTypes.string,prefixCls:i.PropTypes.string,mouseEnterDelay:i.PropTypes.number,mouseLeaveDelay:i.PropTypes.number,getTooltipContainer:i.PropTypes.func,destroyTooltipOnHide:i.PropTypes.bool,align:i.PropTypes.shape({offset:i.PropTypes.array,targetOffset:i.PropTypes.array}),arrowContent:i.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"},n)]},getPopupDomNode:function(){return this.refs.trigger.popupDomNode},render:function(){var e=this.props,t=e.overlayClassName,n=e.trigger,r=e.mouseEnterDelay,i=e.mouseLeaveDelay,u=e.overlayStyle,p=e.prefixCls,f=e.children,d=e.onVisibleChange,h=e.transitionName,y=e.animation,v=e.placement,m=e.align,g=e.destroyTooltipOnHide,b=e.defaultVisible,P=e.getTooltipContainer,O=o(e,["overlayClassName","trigger","mouseEnterDelay","mouseLeaveDelay","overlayStyle","prefixCls","children","onVisibleChange","transitionName","animation","placement","align","destroyTooltipOnHide","defaultVisible","getTooltipContainer"]),C=a({},O);return"visible"in this.props&&(C.popupVisible=this.props.visible),s["default"].createElement(c["default"],a({popupClassName:t,ref:"trigger",prefixCls:p,popup:this.getPopupElement(),action:n,builtinPlacements:l.placements,popupPlacement:v,popupAlign:m,getPopupContainer:P,onPopupVisibleChange:d,popupTransitionName:h,popupAnimation:y,defaultPopupVisible:b,destroyPopupOnHide:g,mouseLeaveDelay:i,popupStyle:u,mouseEnterDelay:r},C),f)}});t["default"]=p,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={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:[-3,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.placements=o,t["default"]=o},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 a(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(){}function s(e,t){return String((0,C.getPropValue)(t,(0,C.labelCompatible)(this.props.treeNodeFilterProp))).indexOf(e)>-1}function l(e,t){this[e]=t}function u(e){var t=arguments.length<=1||void 0===arguments[1]?0:arguments[1];return e.map(function(e,n){var r=t+"-"+n,o={title:e.label,value:e.value||String(e.key||e.label),key:e.key||e.value||r,disabled:e.disabled||!1},a=void 0;return a=e.children&&e.children.length?f["default"].createElement(E["default"],o,u(e.children,r)):f["default"].createElement(E["default"],c({},o,{isLeaf:e.isLeaf}))})}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},p=n(1),f=r(p),d=n(4),h=r(d),y=n(6),v=n(2),m=r(v),g=n(11),b=r(g),P=n(9),O=r(P),C=n(109),T=n(380),w=r(T),x=n(108),E=r(x),S="SHOW_ALL",k="SHOW_PARENT",j="SHOW_CHILD",_=f["default"].createClass({displayName:"Select",propTypes:{children:p.PropTypes.any,multiple:p.PropTypes.bool,filterTreeNode:p.PropTypes.any,showSearch:p.PropTypes.bool,disabled:p.PropTypes.bool,showArrow:p.PropTypes.bool,tags:p.PropTypes.bool,transitionName:p.PropTypes.string,animation:p.PropTypes.string,choiceTransitionName:p.PropTypes.string,onClick:p.PropTypes.func,onChange:p.PropTypes.func,onSelect:p.PropTypes.func,onDeselect:p.PropTypes.func,onSearch:p.PropTypes.func,searchPlaceholder:p.PropTypes.string,placeholder:p.PropTypes.any,inputValue:p.PropTypes.any,value:p.PropTypes.oneOfType([p.PropTypes.array,p.PropTypes.string,p.PropTypes.object]),defaultValue:p.PropTypes.oneOfType([p.PropTypes.array,p.PropTypes.string,p.PropTypes.object]),label:p.PropTypes.any,defaultLabel:p.PropTypes.any,labelInValue:p.PropTypes.bool,dropdownStyle:p.PropTypes.object,drodownPopupAlign:p.PropTypes.object,maxTagTextLength:p.PropTypes.number,showCheckedStrategy:p.PropTypes.oneOf([S,k,j]),treeCheckStrictly:p.PropTypes.bool,treeIcon:p.PropTypes.bool,treeLine:p.PropTypes.bool,treeDefaultExpandAll:p.PropTypes.bool,treeCheckable:p.PropTypes.oneOfType([p.PropTypes.bool,p.PropTypes.node]),treeNodeLabelProp:p.PropTypes.string,treeNodeFilterProp:p.PropTypes.string,treeData:p.PropTypes.array,treeDataSimpleMode:p.PropTypes.oneOfType([p.PropTypes.bool,p.PropTypes.object]),loadData:p.PropTypes.func},getDefaultProps:function(){return{prefixCls:"rc-tree-select",filterTreeNode:s,showSearch:!0,allowClear:!1,placeholder:"",searchPlaceholder:"",labelInValue:!1,defaultValue:[],inputValue:"",onClick:i,onChange:i,onSelect:i,onDeselect:i,onSearch:i,showArrow:!0,dropdownMatchSelectWidth:!0,dropdownStyle:{},notFoundContent:"Not Found",showCheckedStrategy:j,treeCheckStrictly:!1,treeIcon:!1,treeLine:!1,treeDataSimpleMode:!1,treeDefaultExpandAll:!1,treeCheckable:!1,treeNodeFilterProp:"value",treeNodeLabelProp:"title"}},getInitialState:function(){var e=this.props,t=[];t="value"in e?(0,C.toArray)(e.value):(0,C.toArray)(e.defaultValue),this.renderedTreeData=this.renderTreeData(),t=this.addLabelToValue(e,t),t=this.getValue(e,t);var n=e.inputValue||"";this.saveInputRef=l.bind(this,"inputInstance");var r=e.open;return void 0===r&&(r=e.defaultOpen),{value:t,inputValue:n,open:r,focused:!1}},componentDidMount:function(){if(this.state.inputValue){var e=this.getInputDOMNode();e&&e.value&&(e.style.width="",e.style.width=e.scrollWidth+"px")}},componentWillReceiveProps:function(e){if("value"in e){"no"!==this._cacheTreeNodesStates&&this._savedValue&&e.value===this._savedValue?this._cacheTreeNodesStates=!0:this._cacheTreeNodesStates=!1;var t=(0,C.toArray)(e.value);this.renderedTreeData=this.renderTreeData(e),t=this.addLabelToValue(e,t),t=this.getValue(e,t),this.setState({value:t})}},componentDidUpdate:function(){var e=this.state,t=this.props;if(e.open&&(0,C.isMultipleOrTags)(t)){var n=this.getInputDOMNode();n.value?(n.style.width="",n.style.width=n.scrollWidth+"px"):n.style.width=""}},componentWillUnmount:function(){this.clearDelayTimer(),this.dropdownContainer&&(h["default"].unmountComponentAtNode(this.dropdownContainer),document.body.removeChild(this.dropdownContainer),this.dropdownContainer=null)},onInputChange:function(e){var t=e.target.value,n=this.props;this.setState({inputValue:t,open:!0}),n.onSearch(t)},onDropdownVisibleChange:function(e){var t=this;!e&&document.activeElement===this.getInputDOMNode(),setTimeout(function(){t.setOpenState(e)},10)},onKeyDown:function(e){var t=this.props;if(!t.disabled){var n=e.keyCode;this.state.open&&!this.getInputDOMNode()?this.onInputKeyDown(e):n!==y.KeyCode.ENTER&&n!==y.KeyCode.DOWN||(this.setOpenState(!0),e.preventDefault())}},onInputBlur:function(){},onInputKeyDown:function(e){var t=this.props;if(!t.disabled){var n=this.state,r=e.keyCode;if(!(0,C.isMultipleOrTags)(t)||e.target.value||r!==y.KeyCode.BACKSPACE){if(r===y.KeyCode.DOWN){if(!n.open)return this.openIfHasChildren(),e.preventDefault(),void e.stopPropagation()}else if(r===y.KeyCode.ESC)return void(n.open&&(this.setOpenState(!1),e.preventDefault(),e.stopPropagation()));n.open}else{var o=n.value.concat();if(o.length){var a=o.pop();t.onDeselect(this.isLabelInValue()?a:a.key),this.fireChange(o)}}}},onSelect:function(e,t){var n=this;if(t.selected===!1)return void this.onDeselect(t);var r=t.node,o=this.state.value,a=this.props,i=(0,C.getValuePropValue)(r),s=this.getLabelFromNode(r),l=i;this.isLabelInValue()&&(l={value:l,label:s}),a.onSelect(l,r,t);var u="check"===t.event;if((0,C.isMultipleOrTags)(a))if(u)o=this.getCheckedNodes(t,a).map(function(e){return{value:(0,C.getValuePropValue)(e),label:n.getLabelFromNode(e)}});else{if(o.some(function(e){return e.value===i}))return;o=o.concat([{value:i,label:s}])}else{if(o.length&&o[0].value===i)return void this.setOpenState(!1);o=[{value:i,label:s}],this.setOpenState(!1)}var c={triggerValue:i,triggerNode:r};if(u){c.checked=t.checked,c.allCheckedNodes=a.treeCheckStrictly?t.checkedNodes:(0,C.flatToHierarchy)(t.checkedNodesPositions),this._checkedNodes=t.checkedNodesPositions;var p=this.refs.trigger.popupEle;this._treeNodesStates=p.checkKeys}else c.selected=t.selected;this.fireChange(o,c),null===a.inputValue&&this.setState({inputValue:""})},onDeselect:function(e){this.removeSelected((0,C.getValuePropValue)(e.node)),(0,C.isMultipleOrTags)(this.props)||this.setOpenState(!1),null===this.props.inputValue&&this.setState({inputValue:""})},onPlaceholderClick:function(){this.getInputDOMNode().focus()},onOuterFocus:function(){},onOuterBlur:function(){},onClearSelection:function(e){var t=this.props,n=this.state;t.disabled||(e.stopPropagation(),(n.inputValue||n.value.length)&&(this.fireChange([]),this.setOpenState(!1),null===t.inputValue&&this.setState({inputValue:""})))},getLabelFromNode:function(e){return(0,C.getPropValue)(e,this.props.treeNodeLabelProp)},getLabelFromProps:function(e,t){var n=this;if(void 0===t)return null;var r=null;return(0,C.loopAllChildren)(this.renderedTreeData||e.children,function(e){(0,C.getValuePropValue)(e)===t&&(r=n.getLabelFromNode(e))}),null===r?t:r},getDropdownContainer:function(){return this.dropdownContainer||(this.dropdownContainer=document.createElement("div"),document.body.appendChild(this.dropdownContainer)),this.dropdownContainer},getSearchPlaceholderElement:function(e){var t=this.props,n=void 0;return n=(0,C.isMultipleOrTagsOrCombobox)(t)?t.placeholder||t.searchPlaceholder:t.searchPlaceholder,n?f["default"].createElement("span",{style:{display:e?"none":"block"},onClick:this.onPlaceholderClick,className:t.prefixCls+"-search__field__placeholder"},n):null},getInputElement:function(){var e=this.props;return f["default"].createElement("span",{className:e.prefixCls+"-search__field__wrap"},f["default"].createElement("input",{ref:this.saveInputRef,onBlur:this.onInputBlur,onChange:this.onInputChange,onKeyDown:this.onInputKeyDown,value:this.state.inputValue,disabled:e.disabled,className:e.prefixCls+"-search__field",role:"textbox"}),(0,C.isMultipleOrTags)(e)?null:this.getSearchPlaceholderElement(!!this.state.inputValue))},getInputDOMNode:function(){return this.inputInstance},getPopupDOMNode:function(){return this.refs.trigger.getPopupDOMNode()},getPopupComponentRefs:function(){return this.refs.trigger.getPopupEleRefs()},getValue:function(e,t){var n=this,r=t;if(e.treeCheckable&&e.treeCheckStrictly&&(this.halfCheckedValues=[],r=[],t.forEach(function(e){e.halfChecked?n.halfCheckedValues.push(e):r.push(e)})),!e.treeCheckable||e.treeCheckStrictly)return r;var o=void 0;this._cachetreeData&&this._cacheTreeNodesStates&&this._checkedNodes?this.checkedTreeNodes=o=this._checkedNodes:(this._treeNodesStates=(0,C.getTreeNodesStates)(this.renderedTreeData||e.children,r.map(function(e){return e.value})),this.checkedTreeNodes=o=this._treeNodesStates.checkedNodes);var a=function(t){return t.map(function(t){return{value:(0,C.getValuePropValue)(t.node),label:(0,C.getPropValue)(t.node,e.treeNodeLabelProp)}})},i=this.props,s=[];return i.showCheckedStrategy===S?s=a(o):i.showCheckedStrategy===k?!function(){var e=(0,C.filterParentPosition)(o.map(function(e){return e.pos}));s=a(o.filter(function(t){return-1!==e.indexOf(t.pos)}))}():s=a(o.filter(function(e){return!e.node.props.children})),s},getCheckedNodes:function(e,t){var n=e.checkedNodes;if(t.treeCheckStrictly)return n;var r=e.checkedNodesPositions;return t.showCheckedStrategy===S?n=n:t.showCheckedStrategy===k?!function(){var e=(0,C.filterParentPosition)(r.map(function(e){return e.pos}));n=r.filter(function(t){return-1!==e.indexOf(t.pos)}).map(function(e){return e.node})}():n=n.filter(function(e){return!e.props.children}),n},getDeselectedValue:function(e){var t=this.checkedTreeNodes,n=void 0;t.forEach(function(t){t.node.props.value===e&&(n=t.pos)});var r=n.split("-"),o=[],a=[];t.forEach(function(e){var t=e.pos.split("-");e.pos===n||r.length>t.length&&(0,C.isInclude)(t,r)||r.length<t.length&&(0,C.isInclude)(r,t)||(a.push(e),o.push(e.node.props.value))}),this.checkedTreeNodes=this._checkedNodes=a;var i=this.state.value.filter(function(e){return-1!==o.indexOf(e.value)});this.fireChange(i,{triggerValue:e,clear:!0})},setOpenState:function(e,t){var n=this;this.clearDelayTimer();var r=this.props,o=this.refs;this.setState({open:e},function(){if(t||e)if(e||(0,C.isMultipleOrTagsOrCombobox)(r)){var a=n.getInputDOMNode();a&&document.activeElement!==a&&a.focus()}else o.selection&&o.selection.focus()})},addLabelToValue:function(e,t){var n=this,r=t;return this.isLabelInValue()?r.forEach(function(t,o){return"[object Object]"!==Object.prototype.toString.call(r[o])?void(r[o]={value:"",label:""}):void(t.label=t.label||n.getLabelFromProps(e,t.value))}):r=r.map(function(t){return{value:t,label:n.getLabelFromProps(e,t)}}),r},clearDelayTimer:function(){this.delayTimer&&(clearTimeout(this.delayTimer),this.delayTimer=null)},removeSelected:function(e){var t=this.props;if(!t.disabled){if(this._cacheTreeNodesStates="no",t.treeCheckable&&(t.showCheckedStrategy===S||t.showCheckedStrategy===k)&&!t.treeCheckStrictly)return void this.getDeselectedValue(e);var n=void 0,r=this.state.value.filter(function(t){return t.value===e&&(n=t.label),t.value!==e}),o=(0,C.isMultipleOrTags)(t);if(o){var a=e;this.isLabelInValue()&&(a={value:e,label:n}),t.onDeselect(a)}t.treeCheckable&&this.checkedTreeNodes&&this.checkedTreeNodes.length&&(this.checkedTreeNodes=this._checkedNodes=this.checkedTreeNodes.filter(function(e){return r.some(function(t){return t.value===e.node.props.value})})),this.fireChange(r,{triggerValue:e,clear:!0})}},openIfHasChildren:function(){var e=this.props;(f["default"].Children.count(e.children)||(0,C.isSingleMode)(e))&&this.setOpenState(!0)},fireChange:function(e,t){var n=this,r=this.props;"value"in r||this.setState({value:e});var a=e.map(function(e){return e.value}),i=this.state.value.map(function(e){return e.value});a.length===i.length&&a.every(function(e,t){return i[t]===e})||!function(){var i={preValue:[].concat(o(n.state.value))};t&&(0,b["default"])(i,t);var s=null,l=e;if(n.isLabelInValue()?n.halfCheckedValues.length&&n.halfCheckedValues.forEach(function(e){l.some(function(t){return t.value===e.value})||l.push(e)}):(s=e.map(function(e){return e.label}),l=l.map(function(e){return e.value})),i.clear&&r.treeCheckable){var u=n.renderedTreeData||r.children;i.allCheckedNodes=(0,C.flatToHierarchy)((0,C.filterAllCheckedData)(a,u))}n._savedValue=(0,C.isMultipleOrTags)(r)?l:l[0],r.onChange(n._savedValue,s,i)}()},isLabelInValue:function(){var e=this.props,t=e.treeCheckable,n=e.treeCheckStrictly,r=e.labelInValue;return t&&n?!0:r||!1},renderTopControlNode:function(){var e=this,t=this.state.value,n=this.props,r=n.choiceTransitionName,o=n.prefixCls,a=n.maxTagTextLength;if((0,C.isSingleMode)(n)){var i=f["default"].createElement("span",{key:"placeholder",className:o+"-selection__placeholder"},n.placeholder);return t.length&&(i=f["default"].createElement("span",{key:"value"},t[0].label)),f["default"].createElement("span",{className:o+"-selection__rendered"},i)}var s=[];(0,C.isMultipleOrTags)(n)&&(s=t.map(function(t){var n=t.label,r=n;return a&&"string"==typeof n&&n.length>a&&(n=n.slice(0,a)+"..."),f["default"].createElement("li",c({style:C.UNSELECTABLE_STYLE},C.UNSELECTABLE_ATTRIBUTE,{onMouseDown:C.preventDefaultEvent,className:o+"-selection__choice",key:t.value,title:r}),f["default"].createElement("span",{className:o+"-selection__choice__remove",onClick:e.removeSelected.bind(e,t.value)}),f["default"].createElement("span",{className:o+"-selection__choice__content"},n))})),s.push(f["default"].createElement("li",{className:o+"-search "+o+"-search--inline",key:"__input"},this.getInputElement()));var l=o+"-selection__rendered";return(0,C.isMultipleOrTags)(n)&&r?f["default"].createElement(O["default"],{className:l,component:"ul",transitionName:r},s):f["default"].createElement("ul",{className:l},s)},renderTreeData:function(e){var t=e||this.props;if(t.treeData){if(e&&e.treeData===this.props.treeData&&this.renderedTreeData)return this._cachetreeData=!0,this.renderedTreeData;this._cachetreeData=!1;var n=t.treeData;if(t.treeDataSimpleMode){var r={id:"id",pId:"pId",rootPId:null};"[object Object]"===Object.prototype.toString.call(t.treeDataSimpleMode)&&(0,b["default"])(r,t.treeDataSimpleMode),n=(0,C.processSimpleTreeData)(t.treeData,r)}return u(n)}},render:function(){var e,t=this.props,n=(0,C.isMultipleOrTags)(t),r=this.state,o=t.className,i=t.disabled,s=t.allowClear,l=t.prefixCls,u=this.renderTopControlNode(),p={};(0,C.isMultipleOrTagsOrCombobox)(t)||(p={onKeyDown:this.onKeyDown,tabIndex:0});var d=(e={},a(e,o,!!o),a(e,l,1),a(e,l+"-open",r.open),a(e,l+"-focused",r.open||r.focused),a(e,l+"-disabled",i),a(e,l+"-enabled",!i),e),h=f["default"].createElement("span",{key:"clear",className:l+"-selection__clear",onClick:this.onClearSelection});return f["default"].createElement(w["default"],c({},t,{treeNodes:t.children,treeData:this.renderedTreeData,_cachetreeData:this._cachetreeData,_treeNodesStates:this._treeNodesStates,halfCheckedValues:this.halfCheckedValues,multiple:n,disabled:i,visible:r.open,inputValue:r.inputValue,_inputValue:null===t.inputValue,inputElement:this.getInputElement(),value:r.value,onDropdownVisibleChange:this.onDropdownVisibleChange,onSelect:this.onSelect,ref:"trigger"}),f["default"].createElement("span",{style:t.style,onClick:t.onClick,onBlur:this.onOuterBlur,onFocus:this.onOuterFocus,className:(0,m["default"])(d)},f["default"].createElement("span",c({ref:"selection",key:"selection",className:l+"-selection\n "+l+"-selection--"+(n?"multiple":"single"),role:"combobox","aria-autocomplete":"list","aria-haspopup":"true","aria-expanded":r.open},p),u,s&&!n?h:null,n||!t.showArrow?null:f["default"].createElement("span",{key:"arrow",className:l+"-arrow",style:{outline:"none"}},f["default"].createElement("b",null)),n?this.getSearchPlaceholderElement(!!this.state.inputValue||this.state.value.length):null)))}});_.SHOW_ALL=S,_.SHOW_PARENT=k,_.SHOW_CHILD=j,t["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){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 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},i=n(1),s=r(i),l=n(4),u=r(l),c=n(2),p=r(c),f=n(14),d=r(f),h=n(110),y=r(h),v=n(109),m=n(6),g=r(m),b={bottomLeft:{points:["tl","bl"],offset:[0,4],overflow:{adjustX:0,adjustY:1}},topLeft:{points:["bl","tl"],offset:[0,-4],overflow:{adjustX:0,adjustY:1}}},P=s["default"].createClass({displayName:"SelectTrigger",propTypes:{dropdownMatchSelectWidth:i.PropTypes.bool,dropdownPopupAlign:i.PropTypes.object,visible:i.PropTypes.bool,filterTreeNode:i.PropTypes.any,treeNodes:i.PropTypes.any,inputValue:i.PropTypes.string,_inputValue:i.PropTypes.bool,prefixCls:i.PropTypes.string,popupClassName:i.PropTypes.string,children:i.PropTypes.any},getInitialState:function(){return{_expandedKeys:[],fireOnExpand:!1}},componentWillReceiveProps:function(e){e.inputValue&&e.inputValue!==this.props.inputValue&&this.setState({_expandedKeys:[],fireOnExpand:!1})},componentDidUpdate:function(){if(this.props.dropdownMatchSelectWidth&&this.props.visible){var e=this.getPopupDOMNode();e&&(e.style.width=u["default"].findDOMNode(this).offsetWidth+"px")}},onExpand:function(e){this.setState({_expandedKeys:e,fireOnExpand:!0})},getPopupEleRefs:function(){return this.popupEle&&this.popupEle.refs},getPopupDOMNode:function(){return this.refs.trigger.getPopupDomNode()},getDropdownTransitionName:function(){var e=this.props,t=e.transitionName;return!t&&e.animation&&(t=this.getDropdownPrefixCls()+"-"+e.animation),t},getDropdownPrefixCls:function(){return this.props.prefixCls+"-dropdown"},highlightTreeNode:function(e){var t=this.props,n=e.props[(0,v.labelCompatible)(t.treeNodeFilterProp)];return"string"==typeof n?t.inputValue&&n.indexOf(t.inputValue)>-1:!1},filterTreeNode:function O(e,t){if(!e)return!0;var O=this.props.filterTreeNode;return O?t.props.disabled?!1:O.call(this,e,t):!0},savePopupElement:function(e){this.popupEle=e},processTreeNode:function(e){var t=this,n=[];this._expandedKeys=[],(0,v.loopAllChildren)(e,function(e,r,o){t.filterTreeNode(t.props.inputValue,e)&&(n.push(o),t._expandedKeys.push(e.key))});var r=[];n.forEach(function(e){var t=e.split("-");t.reduce(function(e,t){var n=e+"-"+t;return r.indexOf(n)<0&&r.push(n),n})});var o=[];(0,v.loopAllChildren)(e,function(e,t,n){r.indexOf(n)>-1&&o.push({node:e,pos:n})});var a=(0,v.flatToHierarchy)(o),i=function l(e){return e.map(function(e){return e.children?s["default"].cloneElement(e.node,{},l(e.children)):e.node})};return i(a)},renderTree:function(e,t,n,r){var o=this.props,i={multiple:r,prefixCls:o.prefixCls+"-tree",showIcon:o.treeIcon,showLine:o.treeLine,defaultExpandAll:o.treeDefaultExpandAll,filterTreeNode:this.highlightTreeNode};return o.treeCheckable?(o.inputValue&&!o._inputValue||(i._treeNodesStates=o._treeNodesStates),i.selectable=!1,i.checkable=o.treeCheckable,i.checkStrictly=o.treeCheckStrictly,i.onCheck=o.onSelect,o.treeCheckStrictly&&t.length?i.checkedKeys={checked:e,halfChecked:t}:i.checkedKeys=e):(i.selectedKeys=e,i.onSelect=o.onSelect),i.defaultExpandAll||(i.expandedKeys=e),i.autoExpandParent=!0,i.onExpand=this.onExpand,this._expandedKeys&&this._expandedKeys.length&&(i.expandedKeys=this._expandedKeys),this.state.fireOnExpand&&(i.expandedKeys=this.state._expandedKeys,i.autoExpandParent=!1),o.loadData&&(i.loadData=o.loadData),s["default"].createElement(y["default"],a({ref:this.savePopupElement},i),n)},render:function(){var e,t=this.props,n=t.multiple,r=this.getDropdownPrefixCls(),i=(e={},o(e,t.dropdownClassName,!!t.dropdownClassName),o(e,r+"--"+(n?"multiple":"single"),1),e),l=t.visible,u=n||t.combobox||!t.showSearch?null:s["default"].createElement("span",{className:r+"-search"},t.inputElement),c=function C(e){return g["default"].Children.toArray(e).map(function(e){return e&&e.props.children?s["default"].createElement(h.TreeNode,a({},e.props,{key:e.key}),C(e.props.children)):s["default"].createElement(h.TreeNode,a({},e.props,{key:e.key}))})},f=void 0;t._cachetreeData&&this.treeNodes?f=this.treeNodes:(f=c(t.treeData||t.treeNodes),this.treeNodes=f),t.inputValue&&(f=this.processTreeNode(f));var y=[],m=[];(0,v.loopAllChildren)(f,function(e){t.value.some(function(t){return t.value===(0,v.getValuePropValue)(e)})&&y.push(e.key),t.halfCheckedValues&&t.halfCheckedValues.some(function(t){return t.value===(0,v.getValuePropValue)(e)})&&m.push(e.key)});var P=void 0;f.length||(t.notFoundContent&&(P=s["default"].createElement("span",null,t.notFoundContent)),u||(l=!1));var O=s["default"].createElement("div",null,u,P?P:this.renderTree(y,m,f,n));return s["default"].createElement(d["default"],{action:t.disabled?[]:["click"],ref:"trigger",popupPlacement:"bottomLeft",builtinPlacements:b,popupAlign:this.props.dropdownPopupAlign,prefixCls:r,popupTransitionName:this.getDropdownTransitionName(),onPopupVisibleChange:t.onDropdownVisibleChange,popup:O,popupVisible:l,popupClassName:(0,p["default"])(i),popupStyle:t.dropdownStyle},this.props.children)}});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(379),a=r(o),i=n(108),s=r(i);a["default"].TreeNode=s["default"],t["default"]=a["default"],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 a(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 s(){}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=function(e,t,n){for(var r=!0;r;){var o=e,a=t,i=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,a);if(void 0!==s){if("value"in s)return s.value;var l=s.get;if(void 0===l)return;return l.call(i)}var u=Object.getPrototypeOf(o);if(null===u)return;e=u,t=a,n=i,r=!0,s=u=void 0}},p=n(1),f=r(p),d=n(11),h=r(d),y=n(2),v=r(y),m=n(111),g=function(e){function t(e){var n=this;a(this,t),c(Object.getPrototypeOf(t.prototype),"constructor",this).call(this,e), ["onKeyDown","onCheck"].forEach(function(e){n[e]=n[e].bind(n)}),this.contextmenuKeys=[],this.checkedKeysChange=!0,this.state={expandedKeys:this.getDefaultExpandedKeys(e),checkedKeys:this.getDefaultCheckedKeys(e),selectedKeys:this.getDefaultSelectedKeys(e),dragNodesKeys:"",dragOverNodeKey:"",dropNodeKey:""}}return i(t,e),u(t,[{key:"componentWillReceiveProps",value:function(e){var t=this.getDefaultExpandedKeys(e,!0),n=this.getDefaultCheckedKeys(e,!0),r=this.getDefaultSelectedKeys(e,!0),o={};t&&(o.expandedKeys=t),n&&(e.checkedKeys===this.props.checkedKeys?this.checkedKeysChange=!1:this.checkedKeysChange=!0,o.checkedKeys=n),r&&(o.selectedKeys=r),this.setState(o)}},{key:"onDragStart",value:function(e,t){this.dragNode=t,this.dragNodesKeys=this.getDragNodes(t);var n={dragNodesKeys:this.dragNodesKeys},r=this.getExpandedKeys(t,!1);r&&(this.getRawExpandedKeys(),n.expandedKeys=r),this.setState(n),this.props.onDragStart({event:e,node:t})}},{key:"onDragEnterGap",value:function(e,t){var n=(0,m.getOffset)(t.refs.selectHandle).top,r=t.refs.selectHandle.offsetHeight,o=e.pageY,a=2;return o>n+r-a?(this.dropPosition=1,1):n+a>o?(this.dropPosition=-1,-1):(this.dropPosition=0,0)}},{key:"onDragEnter",value:function(e,t){var n=this.onDragEnterGap(e,t);if(this.dragNode.props.eventKey===t.props.eventKey&&0===n)return void this.setState({dragOverNodeKey:""});var r={dragOverNodeKey:t.props.eventKey},a=this.getExpandedKeys(t,!0);a&&(this.getRawExpandedKeys(),r.expandedKeys=a),this.setState(r),this.props.onDragEnter({event:e,node:t,expandedKeys:a&&[].concat(o(a))||[].concat(o(this.state.expandedKeys))})}},{key:"onDragOver",value:function(e,t){this.props.onDragOver({event:e,node:t})}},{key:"onDragLeave",value:function(e,t){this.props.onDragLeave({event:e,node:t})}},{key:"onDrop",value:function(e,t){var n=t.props.eventKey;if(this.setState({dragOverNodeKey:"",dropNodeKey:n}),this.dragNodesKeys.indexOf(n)>-1)return console.warn&&console.warn("can not drop to dragNode(include it's children node)"),!1;var r=t.props.pos.split("-"),a={event:e,node:t,dragNode:this.dragNode,dragNodesKeys:[].concat(o(this.dragNodesKeys)),dropPosition:this.dropPosition+Number(r[r.length-1])};0!==this.dropPosition&&(a.dropToGap=!0),"expandedKeys"in this.props&&(a.rawExpandedKeys=[].concat(o(this._rawExpandedKeys))||[].concat(o(this.state.expandedKeys))),this.props.onDrop(a)}},{key:"onExpand",value:function(e){var t=this,n=!e.props.expanded,r="expandedKeys"in this.props,a=[].concat(o(this.state.expandedKeys)),i=a.indexOf(e.props.eventKey);return n&&-1===i?a.push(e.props.eventKey):!n&&i>-1&&a.splice(i,1),r||this.setState({expandedKeys:a}),this.props.onExpand(a,{node:e,expanded:n}),n&&this.props.loadData?this.props.loadData(e).then(function(){r||t.setState({expandedKeys:a})}):void 0}},{key:"onCheck",value:function(e){var t=this,n=!e.props.checked;e.props.halfChecked&&(n=!0);var r=e.props.eventKey,a=[].concat(o(this.state.checkedKeys)),i=a.indexOf(r),s={event:"check",node:e,checked:n};if(this.props.checkStrictly&&"checkedKeys"in this.props)n&&-1===i&&a.push(r),!n&&i>-1&&a.splice(i,1),s.checkedNodes=[],(0,m.loopAllChildren)(this.props.children,function(e,t,n,r){-1!==a.indexOf(r)&&s.checkedNodes.push(e)}),this.props.onCheck((0,m.getStrictlyValue)(a,this.props.checkedKeys.halfChecked),s);else{n&&-1===i&&!function(){t.treeNodesStates[e.props.pos].checked=!0;var n=[];Object.keys(t.treeNodesStates).forEach(function(e){t.treeNodesStates[e].checked&&n.push(e)}),(0,m.handleCheckState)(t.treeNodesStates,(0,m.filterParentPosition)(n),!0)}(),n||(this.treeNodesStates[e.props.pos].checked=!1,this.treeNodesStates[e.props.pos].halfChecked=!1,(0,m.handleCheckState)(this.treeNodesStates,[e.props.pos],!1));var l=(0,m.getCheck)(this.treeNodesStates);s.checkedNodes=l.checkedNodes,s.checkedNodesPositions=l.checkedNodesPositions,this.checkKeys=l,this._checkedKeys=a=l.checkedKeys,"checkedKeys"in this.props||this.setState({checkedKeys:a}),this.props.onCheck(a,s)}}},{key:"onSelect",value:function(e){var t=this.props,n=[].concat(o(this.state.selectedKeys)),r=e.props.eventKey,a=n.indexOf(r),i=void 0;-1!==a?(i=!1,n.splice(a,1)):(i=!0,t.multiple||(n.length=0),n.push(r));var s=[];n.length&&(0,m.loopAllChildren)(this.props.children,function(e){-1!==n.indexOf(e.key)&&s.push(e)});var l={event:"select",node:e,selected:i,selectedNodes:s};"selectedKeys"in this.props||this.setState({selectedKeys:n}),t.onSelect(n,l)}},{key:"onMouseEnter",value:function(e,t){this.props.onMouseEnter({event:e,node:t})}},{key:"onMouseLeave",value:function(e,t){this.props.onMouseLeave({event:e,node:t})}},{key:"onContextMenu",value:function(e,t){var n=[].concat(o(this.state.selectedKeys)),r=t.props.eventKey;-1===this.contextmenuKeys.indexOf(r)&&this.contextmenuKeys.push(r),this.contextmenuKeys.forEach(function(e){var t=n.indexOf(e);-1!==t&&n.splice(t,1)}),-1===n.indexOf(r)&&n.push(r),this.setState({selectedKeys:n}),this.props.onRightClick({event:e,node:t})}},{key:"onKeyDown",value:function(e){e.preventDefault()}},{key:"getFilterExpandedKeys",value:function(e,t,n){var r=e[t],o=[];e.autoExpandParent&&(0,m.loopAllChildren)(e.children,function(e,t,n,a){r.indexOf(a)>-1&&o.push(n)});var a=[];return(0,m.loopAllChildren)(e.children,function(t,r,i,s){n?a.push(s):e.autoExpandParent&&o.forEach(function(e){(e.split("-").length>i.split("-").length&&(0,m.isInclude)(i.split("-"),e.split("-"))||i===e)&&-1===a.indexOf(s)&&a.push(s)})}),a.length?a:r}},{key:"getDefaultExpandedKeys",value:function(e,t){var n=t?void 0:this.getFilterExpandedKeys(e,"defaultExpandedKeys",e.defaultExpandAll);return"expandedKeys"in e&&(n=(e.autoExpandParent?this.getFilterExpandedKeys(e,"expandedKeys",!1):e.expandedKeys)||[]),n}},{key:"getDefaultCheckedKeys",value:function(e,t){var n=t?void 0:e.defaultCheckedKeys;return"checkedKeys"in e&&(n=e.checkedKeys||[],e.checkStrictly&&(e.checkedKeys.checked?n=e.checkedKeys.checked:Array.isArray(e.checkedKeys)||(n=[]))),n}},{key:"getDefaultSelectedKeys",value:function(e,t){var n=function(t){return e.multiple?[].concat(o(t)):t.length?[t[0]]:t},r=t?void 0:n(e.defaultSelectedKeys);return"selectedKeys"in e&&(r=n(e.selectedKeys)),r}},{key:"getRawExpandedKeys",value:function(){!this._rawExpandedKeys&&"expandedKeys"in this.props&&(this._rawExpandedKeys=[].concat(o(this.state.expandedKeys)))}},{key:"getOpenTransitionName",value:function(){var e=this.props,t=e.openTransitionName,n=e.openAnimation;return t||"string"!=typeof n||(t=e.prefixCls+"-open-"+n),t}},{key:"getDragNodes",value:function(e){var t=[],n=e.props.pos.split("-");return(0,m.loopAllChildren)(this.props.children,function(r,o,a,i){var s=a.split("-");(e.props.pos===a||n.length<s.length&&(0,m.isInclude)(n,s))&&t.push(i)}),t}},{key:"getExpandedKeys",value:function(e,t){var n=e.props.eventKey,r=this.state.expandedKeys,a=r.indexOf(n),i=void 0;return a>-1&&!t?(i=[].concat(o(r)),i.splice(a,1),i):t&&-1===r.indexOf(n)?r.concat([n]):void 0}},{key:"filterTreeNode",value:function n(e){var n=this.props.filterTreeNode;return"function"!=typeof n||e.props.disabled?!1:n.call(this,e)}},{key:"renderTreeNode",value:function(e,t){var n=arguments.length<=2||void 0===arguments[2]?0:arguments[2],r=n+"-"+t,o=e.key||r,a=this.state,i=this.props,s={ref:"treeNode-"+o,root:this,eventKey:o,pos:r,selectable:i.selectable,loadData:i.loadData,onMouseEnter:i.onMouseEnter,onMouseLeave:i.onMouseLeave,onRightClick:i.onRightClick,prefixCls:i.prefixCls,showLine:i.showLine,showIcon:i.showIcon,draggable:i.draggable,dragOver:a.dragOverNodeKey===o&&0===this.dropPosition,dragOverGapTop:a.dragOverNodeKey===o&&-1===this.dropPosition,dragOverGapBottom:a.dragOverNodeKey===o&&1===this.dropPosition,expanded:-1!==a.expandedKeys.indexOf(o),selected:-1!==a.selectedKeys.indexOf(o),openTransitionName:this.getOpenTransitionName(),openAnimation:i.openAnimation,filterTreeNode:this.filterTreeNode.bind(this)};return i.checkable&&(s.checkable=i.checkable,i.checkStrictly?(a.checkedKeys&&(s.checked=-1!==a.checkedKeys.indexOf(o)||!1),i.checkedKeys.halfChecked?s.halfChecked=-1!==i.checkedKeys.halfChecked.indexOf(o)||!1:s.halfChecked=!1):(this.checkedKeys&&(s.checked=-1!==this.checkedKeys.indexOf(o)||!1),s.halfChecked=-1!==this.halfCheckedKeys.indexOf(o)),this.treeNodesStates[r]&&(0,h["default"])(s,this.treeNodesStates[r].siblingPosition)),f["default"].cloneElement(e,s)}},{key:"render",value:function(){var e=this,t=this.props,n={className:(0,v["default"])(t.className,t.prefixCls),role:"tree-node"};return t.focusable&&(n.tabIndex="0",n.onKeyDown=this.onKeyDown),t.checkable&&(this.checkedKeysChange||t.loadData)&&(t.checkStrictly?(this.treeNodesStates={},(0,m.loopAllChildren)(t.children,function(t,n,r,o,a){e.treeNodesStates[r]={siblingPosition:a}})):t._treeNodesStates?(this.treeNodesStates=t._treeNodesStates.treeNodesStates,this.halfCheckedKeys=t._treeNodesStates.halfCheckedKeys,this.checkedKeys=t._treeNodesStates.checkedKeys):!function(){var n=e.state.checkedKeys,r=void 0;!t.loadData&&e.checkKeys&&e._checkedKeys&&e._checkedKeys.every(function(e,t){return n[t]===e})?r=e.checkKeys:!function(){var o=[];e.treeNodesStates={},(0,m.loopAllChildren)(t.children,function(t,r,a,i,s){e.treeNodesStates[a]={node:t,key:i,checked:!1,halfChecked:!1,siblingPosition:s},-1!==n.indexOf(i)&&(e.treeNodesStates[a].checked=!0,o.push(a))}),(0,m.handleCheckState)(e.treeNodesStates,(0,m.filterParentPosition)(o),!0),r=(0,m.getCheck)(e.treeNodesStates)}(),e.halfCheckedKeys=r.halfCheckedKeys,e.checkedKeys=r.checkedKeys}()),f["default"].createElement("ul",l({},n,{unselectable:!0,ref:"tree"}),f["default"].Children.map(t.children,this.renderTreeNode,this))}}]),t}(f["default"].Component);g.propTypes={prefixCls:p.PropTypes.string,children:p.PropTypes.any,showLine:p.PropTypes.bool,showIcon:p.PropTypes.bool,selectable:p.PropTypes.bool,multiple:p.PropTypes.bool,checkable:p.PropTypes.oneOfType([p.PropTypes.bool,p.PropTypes.node]),_treeNodesStates:p.PropTypes.object,checkStrictly:p.PropTypes.bool,draggable:p.PropTypes.bool,autoExpandParent:p.PropTypes.bool,defaultExpandAll:p.PropTypes.bool,defaultExpandedKeys:p.PropTypes.arrayOf(p.PropTypes.string),expandedKeys:p.PropTypes.arrayOf(p.PropTypes.string),defaultCheckedKeys:p.PropTypes.arrayOf(p.PropTypes.string),checkedKeys:p.PropTypes.oneOfType([p.PropTypes.arrayOf(p.PropTypes.string),p.PropTypes.object]),defaultSelectedKeys:p.PropTypes.arrayOf(p.PropTypes.string),selectedKeys:p.PropTypes.arrayOf(p.PropTypes.string),onExpand:p.PropTypes.func,onCheck:p.PropTypes.func,onSelect:p.PropTypes.func,loadData:p.PropTypes.func,onMouseEnter:p.PropTypes.func,onMouseLeave:p.PropTypes.func,onRightClick:p.PropTypes.func,onDragStart:p.PropTypes.func,onDragEnter:p.PropTypes.func,onDragOver:p.PropTypes.func,onDragLeave:p.PropTypes.func,onDrop:p.PropTypes.func,filterTreeNode:p.PropTypes.func,openTransitionName:p.PropTypes.string,openAnimation:p.PropTypes.oneOfType([p.PropTypes.string,p.PropTypes.object])},g.defaultProps={prefixCls:"rc-tree",showLine:!1,showIcon:!0,selectable:!0,multiple:!1,checkable:!1,checkStrictly:!1,draggable:!1,autoExpandParent:!0,defaultExpandAll:!1,defaultExpandedKeys:[],defaultCheckedKeys:[],defaultSelectedKeys:[],onExpand:s,onCheck:s,onSelect:s,onDragStart:s,onDragEnter:s,onDragOver:s,onDragLeave:s,onDrop:s},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,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 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)}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},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}}(),u=function(e,t,n){for(var r=!0;r;){var o=e,a=t,i=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,a);if(void 0!==s){if("value"in s)return s.value;var l=s.get;if(void 0===l)return;return l.call(i)}var u=Object.getPrototypeOf(o);if(null===u)return;e=u,t=a,n=i,r=!0,s=u=void 0}},c=n(1),p=r(c),f=n(11),d=r(f),h=n(2),y=r(h),v=n(9),m=r(v),g=n(111),b="undefined"!=typeof window?(0,g.browser)(window.navigator):"",P=/.*(IE|Edge).+/.test(b),O="---",C=function(e){function t(e){var n=this;a(this,t),u(Object.getPrototypeOf(t.prototype),"constructor",this).call(this,e),["onExpand","onCheck","onContextMenu","onMouseEnter","onMouseLeave","onDragStart","onDragEnter","onDragOver","onDragLeave","onDrop"].forEach(function(e){n[e]=n[e].bind(n)}),this.state={dataLoading:!1,dragNodeHighlight:!1}}return i(t,e),l(t,[{key:"componentDidMount",value:function(){this.props.root._treeNodeInstances||(this.props.root._treeNodeInstances=[]),this.props.root._treeNodeInstances.push(this)}},{key:"onCheck",value:function(){this.props.root.onCheck(this)}},{key:"onSelect",value:function(){this.props.root.onSelect(this)}},{key:"onMouseEnter",value:function(e){e.preventDefault(),this.props.root.onMouseEnter(e,this)}},{key:"onMouseLeave",value:function(e){e.preventDefault(),this.props.root.onMouseLeave(e,this)}},{key:"onContextMenu",value:function(e){e.preventDefault(),this.props.root.onContextMenu(e,this)}},{key:"onDragStart",value:function(e){e.stopPropagation(),this.setState({dragNodeHighlight:!0}),this.props.root.onDragStart(e,this);try{e.dataTransfer.setData("text/plain","firefox-need-it")}finally{}}},{key:"onDragEnter",value:function(e){e.preventDefault(),e.stopPropagation(),this.props.root.onDragEnter(e,this)}},{key:"onDragOver",value:function(e){return e.preventDefault(),e.stopPropagation(),this.props.root.onDragOver(e,this),!1}},{key:"onDragLeave",value:function(e){e.stopPropagation(),this.props.root.onDragLeave(e,this)}},{key:"onDrop",value:function(e){e.preventDefault(),e.stopPropagation(),this.setState({dragNodeHighlight:!1}),this.props.root.onDrop(e,this)}},{key:"onExpand",value:function(){var e=this,t=this.props.root.onExpand(this);t&&"object"==typeof t&&!function(){var n=function(t){e.setState({dataLoading:t})};n(!0),t.then(function(){n(!1)},function(){n(!1)})}()}},{key:"onKeyDown",value:function(e){e.preventDefault()}},{key:"renderSwitcher",value:function(e,t){var n=e.prefixCls,r=o({},n+"-switcher",!0);return e.showLine?"0-0"===e.pos?r[n+"-roots_"+t]=!0:(r[n+"-center_"+t]=!e.last,r[n+"-bottom_"+t]=e.last):r[n+"-noline_"+t]=!0,e.disabled?(r[n+"-switcher-disabled"]=!0,p["default"].createElement("span",{className:(0,y["default"])(r)})):p["default"].createElement("span",{className:(0,y["default"])(r),onClick:this.onExpand})}},{key:"renderCheckbox",value:function(e){var t=e.prefixCls,n=o({},t+"-checkbox",!0);e.checked?n[t+"-checkbox-checked"]=!0:e.halfChecked&&(n[t+"-checkbox-indeterminate"]=!0);var r=null;return"boolean"!=typeof e.checkable&&(r=e.checkable),e.disabled||e.disableCheckbox?(n[t+"-checkbox-disabled"]=!0,p["default"].createElement("span",{ref:"checkbox",className:(0,y["default"])(n)},r)):p["default"].createElement("span",{ref:"checkbox",className:(0,y["default"])(n),onClick:this.onCheck},r)}},{key:"renderChildren",value:function(e){var n=this.renderFirst;this.renderFirst=1;var r=!0;!n&&e.expanded&&(r=!1);var a=e.children,i=a,l=void 0;if(Array.isArray(a)&&(l=a.every(function(e){return e.type===t})),a&&(a.type===t||l)){var u,c=(u={},o(u,e.prefixCls+"-child-tree",!0),o(u,e.prefixCls+"-child-tree-open",e.expanded),u);e.showLine&&(c[e.prefixCls+"-line"]=!e.last);var f={};e.openTransitionName?f.transitionName=e.openTransitionName:"object"==typeof e.openAnimation&&(f.animation=(0,d["default"])({},e.openAnimation),r||delete f.animation.appear),i=p["default"].createElement(m["default"],s({},f,{showProp:"expanded",transitionAppear:r,component:""}),p["default"].createElement("ul",{className:(0,y["default"])(c),expanded:e.expanded},p["default"].Children.map(a,function(t,n){return e.root.renderTreeNode(t,n,e.pos)},e.root)))}return i}},{key:"render",value:function(){var e,t=this,n=this.props,r=n.prefixCls,a=n.expanded?"open":"close",i=(e={},o(e,r+"-iconEle",!0),o(e,r+"-icon_loading",this.state.dataLoading),o(e,r+"-icon__"+a,!0),e),l=!0,u=n.title,c=this.renderChildren(n);c&&c!==n.children||(c=null,n.loadData&&!n.isLeaf||(l=!1)),n.expanded||(c=null);var f=function(){var e=n.showIcon||n.loadData&&t.state.dataLoading?p["default"].createElement("span",{className:(0,y["default"])(i)}):null,o=p["default"].createElement("span",{className:r+"-title"},u),a={};return n.disabled||((n.selected||t.state.dragNodeHighlight)&&(a.className=r+"-node-selected"),a.onClick=function(e){e.preventDefault(),n.selectable&&t.onSelect()},n.onRightClick&&(a.onContextMenu=t.onContextMenu),n.onMouseEnter&&(a.onMouseEnter=t.onMouseEnter),n.onMouseLeave&&(a.onMouseLeave=t.onMouseLeave),n.draggable&&(P&&(a.href="#"),a.draggable=!0,a["aria-grabbed"]=!0,a.onDragStart=t.onDragStart)),p["default"].createElement("a",s({ref:"selectHandle",title:"string"==typeof u?u:""},a),e,o)},d={};n.draggable&&(d.onDragEnter=this.onDragEnter,d.onDragOver=this.onDragOver,d.onDragLeave=this.onDragLeave,d.onDrop=this.onDrop);var h="",v="";n.disabled?h=r+"-treenode-disabled":n.dragOver?v="drag-over":n.dragOverGapTop?v="drag-over-gap-top":n.dragOverGapBottom&&(v="drag-over-gap-bottom");var m=n.filterTreeNode(this)?"filter-node":"",g=function(){var e,t=(e={},o(e,r+"-switcher",!0),o(e,r+"-switcher-noop",!0),e);return n.showLine?(t[r+"-center_docu"]=!n.last,t[r+"-bottom_docu"]=n.last):t[r+"-noline_docu"]=!0,p["default"].createElement("span",{className:(0,y["default"])(t)})};return p["default"].createElement("li",s({},d,{ref:"li",className:(0,y["default"])(n.className,h,v,m)}),l?this.renderSwitcher(n,a):g(),n.checkable?this.renderCheckbox(n):null,f(),c)}}]),t}(p["default"].Component);C.isTreeNode=1,C.propTypes={prefixCls:c.PropTypes.string,disabled:c.PropTypes.bool,disableCheckbox:c.PropTypes.bool,expanded:c.PropTypes.bool,isLeaf:c.PropTypes.bool,root:c.PropTypes.object,onSelect:c.PropTypes.func},C.defaultProps={title:O},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});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},a=n(1),i=r(a),s=n(4),l=r(s),u=n(279),c=r(u),p=n(9),f=r(p),d=n(385),h=r(d),y=n(112),v=r(y),m=i["default"].createClass({displayName:"Popup",propTypes:{visible:a.PropTypes.bool,style:a.PropTypes.object,getClassNameFromAlign:a.PropTypes.func,onAlign:a.PropTypes.func,getRootDomNode:a.PropTypes.func,onMouseEnter:a.PropTypes.func,align:a.PropTypes.any,destroyPopupOnHide:a.PropTypes.bool,className:a.PropTypes.string,prefixCls:a.PropTypes.string,onMouseLeave:a.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,a=e.prefixCls,s=e.destroyPopupOnHide,l=this.getClassName(this.currentAlignClassName||e.getClassNameFromAlign(t)),u=a+"-hidden";r||(this.currentAlignClassName=null);var p=o({},n,this.getZIndexStyle()),d={className:l,prefixCls:a,ref:"popup",onMouseEnter:e.onMouseEnter,onMouseLeave:e.onMouseLeave,style:p};return s?i["default"].createElement(f["default"],{component:"",exclusive:!0,transitionAppear:!0,transitionName:this.getTransitionName()},r?i["default"].createElement(c["default"],{target:this.getTarget,key:"popup",ref:this.saveAlign,monitorWindowResize:!0,align:t,onAlign:this.onAlign},i["default"].createElement(h["default"],o({visible:!0},d),e.children)):null):i["default"].createElement(f["default"],{component:"",exclusive:!0,transitionAppear:!0,transitionName:this.getTransitionName(),showProp:"xVisible"},i["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},i["default"].createElement(h["default"],o({hiddenClassName:u},d),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=i["default"].createElement(v["default"],{style:this.getZIndexStyle(),key:"mask",className:e.prefixCls+"-mask",hiddenClassName:e.prefixCls+"-mask-hidden",visible:e.visible}),n&&(t=i["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 i["default"].createElement("div",null,this.getMaskElement(),this.getPopupElement())}});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),a=r(o),i=n(112),s=r(i),l=a["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),a["default"].createElement("div",{className:t,onMouseEnter:e.onMouseEnter,onMouseLeave:e.onMouseLeave,style:e.style},a["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 a(){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},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(1),u=r(l),c=n(4),p=r(c),f=n(6),d=n(384),h=r(d),y=n(387),v=["onClick","onMouseDown","onTouchStart","onMouseEnter","onMouseLeave","onFocus","onBlur"],m=u["default"].createClass({displayName:"Trigger",propTypes:{action:l.PropTypes.any,showAction:l.PropTypes.any,hideAction:l.PropTypes.any,getPopupClassNameFromAlign:l.PropTypes.any,onPopupVisibleChange:l.PropTypes.func,afterPopupVisibleChange:l.PropTypes.func,popup:l.PropTypes.node.isRequired,popupStyle:l.PropTypes.object,prefixCls:l.PropTypes.string,popupClassName:l.PropTypes.string,popupPlacement:l.PropTypes.string,builtinPlacements:l.PropTypes.object,popupTransitionName:l.PropTypes.string,popupAnimation:l.PropTypes.any,mouseEnterDelay:l.PropTypes.number,mouseLeaveDelay:l.PropTypes.number,zIndex:l.PropTypes.number,focusDelay:l.PropTypes.number,blurDelay:l.PropTypes.number,getPopupContainer:l.PropTypes.func,destroyPopupOnHide:l.PropTypes.bool,mask:l.PropTypes.bool,onPopupAlign:l.PropTypes.func,popupAlign:l.PropTypes.object,popupVisible:l.PropTypes.bool,maskTransitionName:l.PropTypes.string,maskAnimation:l.PropTypes.string},getDefaultProps:function(){return{prefixCls:"rc-trigger-popup",getPopupClassNameFromAlign:a,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}},componentDidMount:function(){this.componentDidUpdate({},{popupVisible:this.state.popupVisible})},componentWillReceiveProps:function(e){"popupVisible"in e&&this.setState({popupVisible:!!e.popupVisible})},componentDidUpdate:function(e,t){var n=this,r=this.props,o=this.state;if(this.popupRendered){var a=function(){var e=n;return e.popupInstance=p["default"].unstable_renderSubtreeIntoContainer(n,n.getPopupElement(),n.getPopupContainer(),function(){this.isMounted()?e.popupDomNode=this.getPopupDomNode():e.popupDomNode=null,t.popupVisible!==o.popupVisible&&r.afterPopupVisibleChange(o.popupVisible)}),n.isClickToHide()&&o.popupVisible?(n.clickOutsideHandler||(n.clickOutsideHandler=f.Dom.addEventListener(document,"mousedown",n.onDocumentClick),n.touchOutsideHandler=f.Dom.addEventListener(document,"touchstart",n.onDocumentClick)),{v:void 0}):void(n.clickOutsideHandler&&(n.clickOutsideHandler.remove(),n.touchOutsideHandler.remove(),n.clickOutsideHandler=null,n.touchOutsideHandler=null))}();if("object"===("undefined"==typeof a?"undefined":s(a)))return a.v}},componentWillUnmount:function(){var e=this.popupContainer;e&&(p["default"].unmountComponentAtNode(e),e.parentNode.removeChild(e),this.popupContainer=null),this.clearDelayTimer(),this.clickOutsideHandler&&(this.clickOutsideHandler.remove(),this.touchOutsideHandler.remove(),this.clickOutsideHandler=null,this.touchOutsideHandler=null)},onMouseEnter:function(){this.delaySetPopupVisible(!0,this.props.mouseEnterDelay)},onMouseLeave:function(e){e.relatedTarget&&!e.relatedTarget.setTimeout&&f.Dom.contains(this.popupContainer,e.relatedTarget)||this.delaySetPopupVisible(!1,this.props.mouseLeaveDelay)},onFocus:function(){this.clearDelayTimer(),this.isFocusToShow()&&(this.focusTime=Date.now(),this.delaySetPopupVisible(!0,this.props.focusDelay))},onMouseDown:function(){this.preClickTime=Date.now()},onTouchStart:function(){this.preTouchTime=Date.now()},onBlur:function(){this.clearDelayTimer(),this.isBlurToHide()&&this.delaySetPopupVisible(!1,this.props.blurDelay)},onClick:function(e){if(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,c.findDOMNode)(this),r=this.getPopupDomNode();f.Dom.contains(n,t)||f.Dom.contains(r,t)||this.setPopupVisible(!1)},getPopupDomNode:function(){return this.popupDomNode},getRootDomNode:function(){return p["default"].findDOMNode(this)},getPopupContainer:function(){if(!this.popupContainer){this.popupContainer=document.createElement("div");var e=this.props.getPopupContainer?this.props.getPopupContainer((0,c.findDOMNode)(this)):document.body;e.appendChild(this.popupContainer)}return this.popupContainer},getPopupClassNameFromAlign:function(e){var t=[],n=this.props,r=n.popupPlacement,o=n.builtinPlacements,a=n.prefixCls;return r&&o&&t.push((0,y.getPopupClassNameFromAlign)(o,a,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},getPopupElement:function(){var e=this.props,t=this.state,n={};return this.isMouseEnterToShow()&&(n.onMouseEnter=this.onMouseEnter),this.isMouseLeaveToHide()&&(n.onMouseLeave=this.onMouseLeave),u["default"].createElement(h["default"],i({prefixCls:e.prefixCls,destroyPopupOnHide:e.destroyPopupOnHide,visible:t.popupVisible,className:e.popupClassName,action:e.action,align:this.getPopupAlign(),onAlign:e.onPopupAlign,animation:e.popupAnimation,getClassNameFromAlign:this.getPopupClassNameFromAlign},n,{getRootDomNode:this.getRootDomNode,style:e.popupStyle,mask:e.mask,zIndex:e.zIndex,transitionName:e.popupTransitionName,maskAnimation:e.maskAnimation,maskTransitionName:e.maskTransitionName}),e.popup)},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)},isClickToShow:function(){var e=this.props,t=e.action,n=e.showAction;return-1!==t.indexOf("click")||-1!==n.indexOf("click")},isClickToHide:function(){var e=this.props,t=e.action,n=e.hideAction;return-1!==t.indexOf("click")||-1!==n.indexOf("click")},isMouseEnterToShow:function(){var e=this.props,t=e.action,n=e.showAction;return-1!==t.indexOf("hover")||-1!==n.indexOf("mouseEnter")},isMouseLeaveToHide:function(){var e=this.props,t=e.action,n=e.hideAction;return-1!==t.indexOf("hover")||-1!==n.indexOf("mouseLeave")},isFocusToShow:function(){var e=this.props,t=e.action,n=e.showAction;return-1!==t.indexOf("focus")||-1!==n.indexOf("focus")},isBlurToHide:function(){var e=this.props,t=e.action,n=e.hideAction;return-1!==t.indexOf("focus")||-1!==n.indexOf("blur")},forcePopupAlign:function(){this.state.popupVisible&&this.popupInstance&&this.popupInstance.alignInstance&&this.popupInstance.alignInstance.forceAlign()},render:function(){this.popupRendered=this.popupRendered||this.state.popupVisible;var e=this.props,t=e.children,n=u["default"].Children.only(t),r=n.props||{},o={};return(this.isClickToHide()||this.isClickToShow())&&(o.onClick=(0,f.createChainedFunction)(this.onClick,r.onClick),o.onMouseDown=(0,f.createChainedFunction)(this.onMouseDown,r.onMouseDown),o.onTouchStart=(0,f.createChainedFunction)(this.onTouchStart,r.onTouchStart)),this.isMouseEnterToShow()&&(o.onMouseEnter=(0,f.createChainedFunction)(this.onMouseEnter,r.onMouseEnter)),this.isMouseLeaveToHide()&&(o.onMouseLeave=(0,f.createChainedFunction)(this.onMouseLeave,r.onMouseLeave)),(this.isFocusToShow()||this.isBlurToHide())&&(o.onFocus=(0,f.createChainedFunction)(this.onFocus,r.onFocus),o.onBlur=(0,f.createChainedFunction)(this.onBlur,r.onBlur)),v.forEach(function(t){var n=void 0;n=e[t]&&o[t]?(0,f.createChainedFunction)(e[t],o[t]):e[t]||o[t],n&&(o[t]=n)}),u["default"].cloneElement(n,o)}});t["default"]=m,e.exports=t["default"]},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 a({},r,n)}function o(e,t,r){var o=r.points;for(var a in e)if(e.hasOwnProperty(a)&&n(e[a].points,o))return t+"-placement-"+a;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};t.getAlignFromPlacement=r,t.getPopupClassNameFromAlign=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(392),a=r(o),i=n(1),s=r(i),l=n(113),u=r(l),c=s["default"].createClass({ displayName:"AjaxUploader",propTypes:{prefixCls:i.PropTypes.string,multiple:i.PropTypes.bool,onStart:i.PropTypes.func,data:i.PropTypes.oneOfType([i.PropTypes.object,i.PropTypes.func]),headers:i.PropTypes.object,beforeUpload:i.PropTypes.func,withCredentials:i.PropTypes.bool},getInitialState:function(){return{disabled:!1,uid:(0,u["default"])()}},onChange:function(e){if(!this.state.disabled){this.setState({disabled:!0});var t=e.target.files;this.uploadFiles(t)}},onClick:function(){var e=this.refs.file;e&&e.click()},onKeyDown:function(e){"Enter"===e.key&&this.onClick()},onFileDrop:function(e){if("dragover"===e.type)return void e.preventDefault();if(!this.state.disabled){var t=e.dataTransfer.files;this.uploadFiles(t),e.preventDefault()}},uploadFiles:function(e){var t=e.length;if(t>0){for(var n=0;t>n;n++){var r=e.item(n);r.uid=(0,u["default"])(),this.upload(r)}this.props.multiple?this.props.onStart(Array.prototype.slice.call(e)):this.props.onStart(Array.prototype.slice.call(e)[0])}},upload:function(e){var t=this,n=this.props;if(!n.beforeUpload)return this.post(e);var r=n.beforeUpload(e);r&&r.then?r.then(function(){t.post(e)},function(){t._reset()}):r!==!1?this.post(e):this._reset()},post:function(e){var t=this,n=this.props,r=n.data;"function"==typeof r&&(r=r(e)),(0,a["default"])({action:n.action,filename:n.name,file:e,data:r,headers:n.headers,withCredentials:n.withCredentials,onProgress:function(t){n.onProgress(t,e)},onSuccess:function(r){n.onSuccess(r,e),t._reset()},onError:function(r,o){n.onError(r,o,e),t._reset()}})},_reset:function(){this.setState({disabled:!1,uid:(0,u["default"])()})},render:function(){var e=this.props;return s["default"].createElement("span",{onClick:this.onClick,onKeyDown:this.onKeyDown,onDrop:this.onFileDrop,onDragOver:this.onFileDrop,role:"button",tabIndex:"0",className:this.state.disabled?this.props.prefixCls+" "+e.prefixCls+"-disabled":""+this.props.prefixCls},s["default"].createElement("input",{type:"file",ref:"file",key:this.state.uid,disabled:this.state.disabled,style:{display:"none"},accept:e.accept,multiple:this.props.multiple,onChange:this.onChange}),e.children)}});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});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},a=n(1),i=r(a),s=n(4),l=r(s),u=n(113),c=r(u),p=n(393),f=r(p),d={position:"absolute",top:0,opacity:0,filter:"alpha(opacity=0)",left:0,zIndex:9999},h=i["default"].createClass({displayName:"IframeUploader",propTypes:{prefixCls:a.PropTypes.string,onStart:a.PropTypes.func,multiple:a.PropTypes.bool,children:a.PropTypes.any,data:a.PropTypes.oneOfType([a.PropTypes.object,a.PropTypes.func]),action:a.PropTypes.string,name:a.PropTypes.string},getInitialState:function(){return{disabled:!1}},componentDidMount:function(){this.updateIframeWH(),this.initIframe()},componentDidUpdate:function(){this.updateIframeWH()},onLoad:function(){if(!this.state.disabled){var e=this.props,t=void 0,n=this.file;try{var r=this.getIframeDocument(),o=r.getElementsByTagName("script")[0];o&&o.parentNode===r.body&&r.body.removeChild(o),t=r.body.innerHTML,e.onSuccess(t,n)}catch(a){(0,f["default"])(!1,"cross domain error for Upload. Maybe server should return document.domain script. see Note from https://github.com/react-component/upload"),t="cross-domain",e.onError(a,null,n)}this.enableIframe(),this.initIframe()}},onChange:function(){var e=this.getFormInputNode(),t=this.file={uid:(0,c["default"])(),name:e.value};this.props.onStart(this.getFileForMultiple(t));var n=this.getFormNode(),r=this.getFormDataNode(),o=this.props.data;"function"==typeof o&&(o=o(t));var a=[];for(var i in o)o.hasOwnProperty(i)&&a.push('<input name="'+i+'" value="'+o[i]+'"/>');r.innerHTML=a.join(""),n.submit(),r.innerHTML="",this.disabledIframe()},getIframeNode:function(){return this.refs.iframe},getIframeDocument:function(){return this.getIframeNode().contentDocument},getFormNode:function(){return this.getIframeDocument().getElementById("form")},getFormInputNode:function(){return this.getIframeDocument().getElementById("input")},getFormDataNode:function(){return this.getIframeDocument().getElementById("data")},getFileForMultiple:function(e){return this.props.multiple?[e]:e},getIframeHTML:function(e){var t="",n="";return e&&(t='<script>document.domain="'+e+'";</script>',n='<input name="_documentDomain" value="'+e+'" />'),'\n <!DOCTYPE html>\n <html>\n <head>\n <meta http-equiv="X-UA-Compatible" content="IE=edge" />\n <style>\n body,html {padding:0;margin:0;border:0;overflow:hidden;}\n </style>\n '+t+'\n </head>\n <body>\n <form method="post"\n encType="multipart/form-data"\n action="'+this.props.action+'" id="form" style="display:block;height:9999px;position:relative;overflow:hidden;">\n <input id="input" type="file"\n name="'+this.props.name+'"\n style="position:absolute;top:0;right:0;height:9999px;font-size:9999px;cursor:pointer;"/>\n '+n+'\n <span id="data"></span>\n </form>\n </body>\n </html>\n '},initIframeSrc:function(){this.domain&&(this.getIframeNode().src="javascript:void((function(){\n var d = document;\n d.open();\n d.domain='"+this.domain+"';\n d.write('');\n d.close();\n })())")},initIframe:function(){var e=this.getIframeNode(),t=e.contentWindow,n=void 0;this.domain=this.domain||"",this.initIframeSrc();try{n=t.document}catch(r){this.domain=document.domain,this.initIframeSrc(),t=e.contentWindow,n=t.document}n.open("text/html","replace"),n.write(this.getIframeHTML(this.domain)),n.close(),this.getFormInputNode().onchange=this.onChange},enableIframe:function(){this.state.disabled&&this.setState({disabled:!1})},disabledIframe:function(){this.state.disabled||this.setState({disabled:!0})},updateIframeWH:function(){var e=l["default"].findDOMNode(this),t=this.getIframeNode();t.style.height=e.offsetHeight+"px",t.style.width=e.offsetWidth+"px"},render:function(){var e=o({},d,{display:this.state.disabled?"none":""});return i["default"].createElement("span",{className:this.state.disabled?this.props.prefixCls+" "+this.props.prefixCls+"-disabled":""+this.props.prefixCls,style:{position:"relative",zIndex:0}},i["default"].createElement("iframe",{ref:"iframe",onLoad:this.onLoad,style:e}),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(){}Object.defineProperty(t,"__esModule",{value:!0});var a=n(1),i=r(a),s=n(388),l=r(s),u=n(389),c=r(u),p=i["default"].createClass({displayName:"Upload",propTypes:{prefixCls:a.PropTypes.string,action:a.PropTypes.string,name:a.PropTypes.string,multipart:a.PropTypes.bool,onError:a.PropTypes.func,onSuccess:a.PropTypes.func,onProgress:a.PropTypes.func,onStart:a.PropTypes.func,data:a.PropTypes.oneOfType([a.PropTypes.object,a.PropTypes.func]),headers:a.PropTypes.object,accept:a.PropTypes.string,multiple:a.PropTypes.bool,beforeUpload:a.PropTypes.func,onReady:a.PropTypes.func,withCredentials:a.PropTypes.bool,supportServerRender:a.PropTypes.bool},getDefaultProps:function(){return{prefixCls:"rc-upload",data:{},headers:{},name:"file",multipart:!1,onProgress:o,onReady:o,onStart:o,onError:o,onSuccess:o,supportServerRender:!1,multiple:!1,beforeUpload:null,withCredentials:!1}},getInitialState:function(){return{Component:null}},componentDidMount:function(){this.props.supportServerRender&&this.setState({Component:this.getComponent()},this.props.onReady)},getComponent:function(){return"undefined"!=typeof FormData?l["default"]:c["default"]},render:function(){if(this.props.supportServerRender){var e=this.state.Component;return e?i["default"].createElement(e,this.props):null}var t=this.getComponent();return i["default"].createElement(t,this.props)}});t["default"]=p,e.exports=t["default"]},function(e,t,n){"use strict";e.exports=n(390)},function(e,t){"use strict";function n(e,t){var n="cannot post "+e.action+" "+t.status+"'",r=new Error(n);return r.status=t.status,r.method="post",r.url=e.action,r}function r(e){var t=e.responseText||e.response;if(!t)return t;try{return JSON.parse(t)}catch(n){return t}}function o(e){if("undefined"!=typeof XMLHttpRequest){var t=new XMLHttpRequest;t.upload&&(t.upload.onprogress=function(t){t.total>0&&(t.percent=t.loaded/t.total*100),e.onProgress(t)});var o=new FormData;e.data&&Object.keys(e.data).map(function(t){o.append(t,e.data[t])}),o.append(e.filename,e.file),t.onerror=function(t){e.onError(t)},t.onload=function(){return t.status<200||t.status>=300?e.onError(n(e,t),r(t)):void e.onSuccess(r(t))},t.open("post",e.action,!0),e.withCredentials&&"withCredentials"in t&&(t.withCredentials=!0);var a=e.headers||{};null!==a["X-Requested-With"]&&t.setRequestHeader("X-Requested-With","XMLHttpRequest");for(var i in a)a.hasOwnProperty(i)&&null!==a[i]&&t.setRequestHeader(i,a[i]);t.send(o)}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o,e.exports=t["default"]},17,function(e,t,n){"use strict";function r(e){return e}var o=n(1);e.exports=function(e){return o.Children.map(e,r)}},function(e,t,n){"use strict";var r=n(1);e.exports=function(e){var t=[];return r.Children.forEach(e,function(e){t.push(e)}),t}},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,i["default"])(e,t,r)}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var a=n(124),i=r(a),s=n(4),l=r(s);e.exports=t["default"]},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,n){"use strict";var r=n(119),o={shouldComponentUpdate:function(e,t){return!r(this.props,e)||!r(this.state,t)}};e.exports=o},function(e,t,n){"use strict";var r=n(120),o=n(2);e.exports=r(o,"`rcUtil.classSet()` is deprecated, use `classNames()` by `require('classnames')` instead")},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";var n=0;e.exports=function(){return Date.now()+"_"+n++}},function(e,t,n){"use strict";var r=n(120),o=n(2);e.exports=r(o,"`rcUtil.joinClasses()` is deprecated, use `classNames()` by `require('classnames')` instead")},function(e,t,n){var r=n(251),o=r&&n(261),a=n(81),i={media:function(e,t){e=a(e),"function"==typeof t&&(t={match:t}),o.register(e,t),this._responsiveMediaHandlers||(this._responsiveMediaHandlers=[]),this._responsiveMediaHandlers.push({query:e,handler:t})},componentWillUnmount:function(){this._responsiveMediaHandlers&&this._responsiveMediaHandlers.forEach(function(e){o.unregister(e.query,e.handler)})}};e.exports=i},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},a=n(1),i=r(a),s=n(2),l=r(s),u=i["default"].createClass({displayName:"PrevArrow",clickHandler:function(e,t){t.preventDefault(),this.props.clickHandler(e,t)},render:function(){var e={"slick-prev":!0},t=this.clickHandler.bind(this,{message:"previous"});!this.props.infinite&&(0===this.props.currentSlide||this.props.slideCount<=this.props.slidesToShow)&&(e["slick-disabled"]=!0,t=null);var n,r={key:"0","data-role":"none",className:(0,l["default"])(e),style:{display:"block"},onClick:t};return n=this.props.prevArrow?i["default"].cloneElement(this.props.prevArrow,r):i["default"].createElement("button",o({key:"0",type:"button"},r)," Previous")}});t.PrevArrow=u;var c=i["default"].createClass({displayName:"NextArrow",clickHandler:function(e,t){t.preventDefault(),this.props.clickHandler(e,t)},render:function(){var e={"slick-next":!0},t=this.clickHandler.bind(this,{message:"next"});this.props.infinite||(this.props.centerMode&&this.props.currentSlide>=this.props.slideCount-1?(e["slick-disabled"]=!0,t=null):this.props.currentSlide>=this.props.slideCount-this.props.slidesToShow&&(e["slick-disabled"]=!0,t=null),this.props.slideCount<=this.props.slidesToShow&&(e["slick-disabled"]=!0,t=null));var n,r={key:"1","data-role":"none",className:(0,l["default"])(e),style:{display:"block"},onClick:t};return n=this.props.nextArrow?i["default"].cloneElement(this.props.nextArrow,r):i["default"].createElement("button",o({key:"1",type:"button"},r)," Next")}});t.NextArrow=c},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),a=r(o),i=n(2),s=r(i),l=function(e){var t;return t=Math.ceil(e.slideCount/e.slidesToScroll)},u=a["default"].createClass({displayName:"Dots",clickHandler:function(e,t){t.preventDefault(),this.props.clickHandler(e)},render:function(){var e=this,t=l({slideCount:this.props.slideCount,slidesToScroll:this.props.slidesToScroll}),n=Array.apply(null,Array(t+1).join("0").split("")).map(function(t,n){var r=(0,s["default"])({"slick-active":e.props.currentSlide===n*e.props.slidesToScroll}),o={message:"dots",index:n,slidesToScroll:e.props.slidesToScroll,currentSlide:e.props.currentSlide};return a["default"].createElement("li",{key:n,className:r},a["default"].createElement("button",{onClick:e.clickHandler.bind(e,o)},n+1))});return a["default"].createElement("ul",{className:this.props.dotsClass,style:{display:"block"}},n)}});t.Dots=u},function(e,t,n){"use strict";e.exports=n(410)},function(e,t){"use strict";var n={animating:!1,dragging:!1,autoPlayTimer:null,currentDirection:0,currentLeft:null,currentSlide:0,direction:1,slideCount:null,slideWidth:null,swipeLeft:null,touchObject:{startX:0,startY:0,curX:0,curY:0},lazyLoadedList:[],initialized:!1,edgeDragged:!1,swiped:!1,trackStyle:{},trackWidth:0};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=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),i=r(a),s=n(409),l=r(s),u=n(117),c=r(u),p=n(407),f=r(p),d=n(115),h=r(d),y=n(2),v=r(y),m=n(411),g=n(405),b=n(404),P=i["default"].createClass({displayName:"InnerSlider",mixins:[c["default"],l["default"]],getInitialState:function(){return f["default"]},getDefaultProps:function(){return h["default"]},componentWillMount:function(){this.props.init&&this.props.init(),this.setState({mounted:!0});for(var e=[],t=0;t<i["default"].Children.count(this.props.children);t++)t>=this.state.currentSlide&&t<this.state.currentSlide+this.props.slidesToShow&&e.push(t);this.props.lazyLoad&&0===this.state.lazyLoadedList.length&&this.setState({lazyLoadedList:e})},componentDidMount:function(){this.initialize(this.props),this.adaptHeight(),window.addEventListener?window.addEventListener("resize",this.onWindowResized):window.attachEvent("onresize",this.onWindowResized)},componentWillUnmount:function(){window.addEventListener?window.removeEventListener("resize",this.onWindowResized):window.detachEvent("onresize",this.onWindowResized),this.state.autoPlayTimer&&window.clearInterval(this.state.autoPlayTimer)},componentWillReceiveProps:function(e){this.props.slickGoTo!=e.slickGoTo?this.changeSlide({message:"index",index:e.slickGoTo,currentSlide:this.state.currentSlide}):this.update(e)},componentDidUpdate:function(){this.adaptHeight()},onWindowResized:function(){this.update(this.props)},render:function(){var e,t=(0,v["default"])("slick-initialized","slick-slider",this.props.className),n={fade:this.props.fade,cssEase:this.props.cssEase,speed:this.props.speed,infinite:this.props.infinite,centerMode:this.props.centerMode,currentSlide:this.state.currentSlide,lazyLoad:this.props.lazyLoad,lazyLoadedList:this.state.lazyLoadedList,rtl:this.props.rtl,slideWidth:this.state.slideWidth,slidesToShow:this.props.slidesToShow,slideCount:this.state.slideCount,trackStyle:this.state.trackStyle,variableWidth:this.props.variableWidth};if(this.props.dots===!0&&this.state.slideCount>this.props.slidesToShow){var r={dotsClass:this.props.dotsClass,slideCount:this.state.slideCount,slidesToShow:this.props.slidesToShow,currentSlide:this.state.currentSlide,slidesToScroll:this.props.slidesToScroll,clickHandler:this.changeSlide};e=i["default"].createElement(g.Dots,r)}var a,s,l={infinite:this.props.infinite,centerMode:this.props.centerMode,currentSlide:this.state.currentSlide,slideCount:this.state.slideCount,slidesToShow:this.props.slidesToShow,prevArrow:this.props.prevArrow,nextArrow:this.props.nextArrow,clickHandler:this.changeSlide};return this.props.arrows&&(a=i["default"].createElement(b.PrevArrow,l),s=i["default"].createElement(b.NextArrow,l)),i["default"].createElement("div",{className:t,onMouseEnter:this.onInnerSliderEnter,onMouseLeave:this.onInnerSliderLeave},i["default"].createElement("div",{ref:"list",className:"slick-list",onMouseDown:this.swipeStart,onMouseMove:this.state.dragging?this.swipeMove:null,onMouseUp:this.swipeEnd,onMouseLeave:this.state.dragging?this.swipeEnd:null,onTouchStart:this.swipeStart,onTouchMove:this.state.dragging?this.swipeMove:null,onTouchEnd:this.swipeEnd,onTouchCancel:this.state.dragging?this.swipeEnd:null},i["default"].createElement(m.Track,o({ref:"track"},n),this.props.children)),a,s,e)}});t.InnerSlider=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=n(118),a=n(117),i=(r(a),n(29)),s=r(i),l={changeSlide:function(e){var t,n,r,o,a;if(o=this.state.slideCount%this.props.slidesToScroll!==0,t=o?0:(this.state.slideCount-this.state.currentSlide)%this.props.slidesToScroll,"previous"===e.message)r=0===t?this.props.slidesToScroll:this.props.slidesToShow-t,a=this.state.currentSlide-r,this.props.lazyLoad&&(n=this.state.currentSlide-r,a=-1===n?this.state.slideCount-1:n);else if("next"===e.message)r=0===t?this.props.slidesToScroll:t,a=this.state.currentSlide+r;else if("dots"===e.message){if(a=e.index*e.slidesToScroll,a===e.currentSlide)return}else if("index"===e.message&&(a=e.index,a===e.currentSlide))return;this.slideHandler(a)},keyHandler:function(e){},selectHandler:function(e){},swipeStart:function(e){var t,n;this.props.swipe===!1||"ontouchend"in document&&this.props.swipe===!1||this.props.draggable===!1&&-1!==e.type.indexOf("mouse")||(t=void 0!==e.touches?e.touches[0].pageX:e.clientX,n=void 0!==e.touches?e.touches[0].pageY:e.clientY,this.setState({dragging:!0,touchObject:{startX:t,startY:n,curX:t,curY:n}}))},swipeMove:function(e){if(this.state.dragging&&!this.state.animating){var t,n,r,a=this.state.touchObject;n=(0,o.getTrackLeft)((0,s["default"])({slideIndex:this.state.currentSlide,trackRef:this.refs.track},this.props,this.state)),a.curX=e.touches?e.touches[0].pageX:e.clientX,a.curY=e.touches?e.touches[0].pageY:e.clientY,a.swipeLength=Math.round(Math.sqrt(Math.pow(a.curX-a.startX,2))),r=(this.props.rtl===!1?1:-1)*(a.curX>a.startX?1:-1);var i=this.state.currentSlide,l=Math.ceil(this.state.slideCount/this.props.slidesToScroll),u=this.swipeDirection(this.state.touchObject),c=a.swipeLength;this.props.infinite===!1&&(0===i&&"right"===u||i+1>=l&&"left"===u)&&(c=a.swipeLength*this.props.edgeFriction,this.state.edgeDragged===!1&&this.props.edgeEvent&&(this.props.edgeEvent(u),this.setState({edgeDragged:!0}))),this.state.swiped===!1&&this.props.swipeEvent&&(this.props.swipeEvent(u),this.setState({swiped:!0})),t=n+c*r,this.setState({touchObject:a,swipeLeft:t,trackStyle:(0,o.getTrackCSS)((0,s["default"])({left:t},this.props,this.state))}),Math.abs(a.curX-a.startX)<.8*Math.abs(a.curY-a.startY)||a.swipeLength>4&&e.preventDefault()}},swipeEnd:function(e){if(this.state.dragging){var t=this.state.touchObject,n=this.state.listWidth/this.props.touchThreshold,r=this.swipeDirection(t);if(this.setState({dragging:!1,edgeDragged:!1,swiped:!1,swipeLeft:null,touchObject:{}}),t.swipeLength)if(t.swipeLength>n)e.preventDefault(),"left"===r?this.slideHandler(this.state.currentSlide+this.props.slidesToScroll):"right"===r?this.slideHandler(this.state.currentSlide-this.props.slidesToScroll):this.slideHandler(this.state.currentSlide);else{var a=(0,o.getTrackLeft)((0,s["default"])({slideIndex:this.state.currentSlide,trackRef:this.refs.track},this.props,this.state));this.setState({trackStyle:(0,o.getTrackAnimateCSS)((0,s["default"])({left:a},this.props,this.state))})}}},onInnerSliderEnter:function(e){this.props.autoplay&&this.props.pauseOnHover&&this.pause()},onInnerSliderLeave:function(e){this.props.autoplay&&this.props.pauseOnHover&&this.autoPlay()}};t["default"]=l,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}var o=n(1),a=r(o),i=n(408),s=n(29),l=r(s),u=n(81),c=r(u),p=n(403),f=r(p),d=n(115),h=r(d),y=a["default"].createClass({displayName:"Slider",mixins:[f["default"]],getInitialState:function(){return{breakpoint:null}},componentDidMount:function(){var e=this;if(this.props.responsive){var t=this.props.responsive.map(function(e){return e.breakpoint});t.sort(function(e,t){return e-t}),t.forEach(function(n,r){var o;o=0===r?(0,c["default"])({minWidth:0,maxWidth:n}):(0,c["default"])({minWidth:t[r-1],maxWidth:n}),e.media(o,function(){e.setState({breakpoint:n})})});var n=(0,c["default"])({minWidth:t.slice(-1)[0]});this.media(n,function(){e.setState({breakpoint:null})})}},render:function(){var e,t,n=this;return this.state.breakpoint?(t=this.props.responsive.filter(function(e){return e.breakpoint===n.state.breakpoint}),e="unslick"===t[0].settings?"unslick":(0,l["default"])({},this.props,t[0].settings)):e=(0,l["default"])({},h["default"],this.props),"unslick"===e?a["default"].createElement("div",null,this.props.children):a["default"].createElement(i.InnerSlider,e,this.props.children)}});e.exports=y},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),a=r(o),i=n(29),s=r(i),l=n(2),u=r(l),c=function(e){var t,n,r,o,a;return a=e.rtl?e.slideCount-1-e.index:e.index,r=0>a||a>=e.slideCount,e.centerMode?(o=Math.floor(e.slidesToShow/2),n=(a-e.currentSlide)%e.slideCount===0,a>e.currentSlide-o-1&&a<=e.currentSlide+o&&(t=!0)):t=e.currentSlide<=a&&a<e.currentSlide+e.slidesToShow,(0,u["default"])({"slick-slide":!0,"slick-active":t,"slick-center":n,"slick-cloned":r})},p=function(e){var t={};return void 0!==e.variableWidth&&e.variableWidth!==!1||(t.width=e.slideWidth),e.fade&&(t.position="relative",t.left=-e.index*e.slideWidth,t.opacity=e.currentSlide===e.index?1:0,t.transition="opacity "+e.speed+"ms "+e.cssEase,t.WebkitTransition="opacity "+e.speed+"ms "+e.cssEase),t},f=function(e,t){return null===e.key||void 0===e.key?t:e.key},d=function(e){var t,n,r=[],o=[],i=[],l=a["default"].Children.count(e.children);return a["default"].Children.forEach(e.children,function(d,h){n=!e.lazyLoad|(e.lazyLoad&&e.lazyLoadedList.indexOf(h)>=0)?d:a["default"].createElement("div",null);var y,v=p((0,s["default"])({},e,{index:h})),m=c((0,s["default"])({index:h},e));if(y=n.props.className?(0,u["default"])(m,n.props.className):m,r.push(a["default"].cloneElement(n,{key:"original"+f(n,h),"data-index":h,className:y,style:(0,s["default"])({},n.props.style||{},v)})),e.infinite&&e.fade===!1){var g=e.variableWidth?e.slidesToShow+1:e.slidesToShow;h>=l-g&&(t=-(l-h),o.push(a["default"].cloneElement(n,{key:"cloned"+f(n,t),"data-index":t,className:y,style:(0,s["default"])({},n.props.style||{},v)}))),g>h&&(t=l+h,i.push(a["default"].cloneElement(n,{key:"cloned"+f(n,t),"data-index":t,className:y,style:(0,s["default"])({},n.props.style||{},v)})))}}),e.rtl?o.concat(r,i).reverse():o.concat(r,i)},h=a["default"].createClass({displayName:"Track",render:function(){var e=d(this.props);return a["default"].createElement("div",{className:"slick-track",style:this.props.trackStyle},e)}});t.Track=h},function(e,t,n){"use strict";var r=n(415),o={shouldComponentUpdate:function(e,t){return r(this,e,t)}};e.exports=o},function(e,t,n){"use strict";function r(){var e=s("animationend"),t=s("transitionend");e&&l.push(e),t&&l.push(t)}function o(e,t,n){e.addEventListener(t,n,!1)}function a(e,t,n){e.removeEventListener(t,n,!1)}var i=n(76),s=n(414),l=[];i.canUseDOM&&r();var u={addEndEventListener:function(e,t){return 0===l.length?void window.setTimeout(t,0):void l.forEach(function(n){o(e,n,t)})},removeEndEventListener:function(e,t){0!==l.length&&l.forEach(function(n){a(e,n,t)})}};e.exports=u},function(e,t,n){"use strict";function r(e,t){var n={};return n[e.toLowerCase()]=t.toLowerCase(),n["Webkit"+e]="webkit"+t,n["Moz"+e]="moz"+t,n["ms"+e]="MS"+t,n["O"+e]="o"+t.toLowerCase(),n}function o(e){if(s[e])return s[e];if(!i[e])return e;var t=i[e];for(var n in t)if(t.hasOwnProperty(n)&&n in l)return s[e]=t[n];return""}var a=n(76),i={animationend:r("Animation","AnimationEnd"),animationiteration:r("Animation","AnimationIteration"),animationstart:r("Animation","AnimationStart"),transitionend:r("Transition","TransitionEnd")},s={},l={};a.canUseDOM&&(l=document.createElement("div").style,"AnimationEvent"in window||(delete i.animationend.animation,delete i.animationiteration.animation,delete i.animationstart.animation),"TransitionEvent"in window||delete i.transitionend.transition),e.exports=o},function(e,t,n){"use strict";function r(e,t,n){return!o(e.props,t)||!o(e.state,n)}var o=n(262);e.exports=r},function(e,t){var n=function(e){return e.replace(/[A-Z]/g,function(e){return"-"+e.toLowerCase()}).toLowerCase()};e.exports=n},function(e,t,n){var r,o;!function(e){function t(e){var t=e.length,r=n.type(e);return"function"===r||n.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===r||0===t||"number"==typeof t&&t>0&&t-1 in e}if(!e.jQuery){var n=function(e,t){return new n.fn.init(e,t)};n.isWindow=function(e){return null!=e&&e==e.window},n.type=function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?o[i.call(e)]||"object":typeof e},n.isArray=Array.isArray||function(e){return"array"===n.type(e)},n.isPlainObject=function(e){var t;if(!e||"object"!==n.type(e)||e.nodeType||n.isWindow(e))return!1;try{if(e.constructor&&!a.call(e,"constructor")&&!a.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(r){return!1}for(t in e);return void 0===t||a.call(e,t)},n.each=function(e,n,r){var o,a=0,i=e.length,s=t(e);if(r){if(s)for(;i>a&&(o=n.apply(e[a],r),o!==!1);a++);else for(a in e)if(o=n.apply(e[a],r),o===!1)break}else if(s)for(;i>a&&(o=n.call(e[a],a,e[a]),o!==!1);a++);else for(a in e)if(o=n.call(e[a],a,e[a]),o===!1)break;return e},n.data=function(e,t,o){if(void 0===o){var a=e[n.expando],i=a&&r[a];if(void 0===t)return i;if(i&&t in i)return i[t]}else if(void 0!==t){var a=e[n.expando]||(e[n.expando]=++n.uuid);return r[a]=r[a]||{},r[a][t]=o,o}},n.removeData=function(e,t){var o=e[n.expando],a=o&&r[o];a&&n.each(t,function(e,t){delete a[t]})},n.extend=function(){var e,t,r,o,a,i,s=arguments[0]||{},l=1,u=arguments.length,c=!1;for("boolean"==typeof s&&(c=s,s=arguments[l]||{},l++),"object"!=typeof s&&"function"!==n.type(s)&&(s={}),l===u&&(s=this,l--);u>l;l++)if(null!=(a=arguments[l]))for(o in a)e=s[o],r=a[o],s!==r&&(c&&r&&(n.isPlainObject(r)||(t=n.isArray(r)))?(t?(t=!1,i=e&&n.isArray(e)?e:[]):i=e&&n.isPlainObject(e)?e:{},s[o]=n.extend(c,i,r)):void 0!==r&&(s[o]=r));return s},n.queue=function(e,r,o){function a(e,n){var r=n||[];return null!=e&&(t(Object(e))?!function(e,t){for(var n=+t.length,r=0,o=e.length;n>r;)e[o++]=t[r++];if(n!==n)for(;void 0!==t[r];)e[o++]=t[r++];return e.length=o,e}(r,"string"==typeof e?[e]:e):[].push.call(r,e)),r}if(e){r=(r||"fx")+"queue";var i=n.data(e,r);return o?(!i||n.isArray(o)?i=n.data(e,r,a(o)):i.push(o),i):i||[]}},n.dequeue=function(e,t){n.each(e.nodeType?[e]:e,function(e,r){t=t||"fx";var o=n.queue(r,t),a=o.shift();"inprogress"===a&&(a=o.shift()),a&&("fx"===t&&o.unshift("inprogress"),a.call(r,function(){n.dequeue(r,t)}))})},n.fn=n.prototype={init:function(e){if(e.nodeType)return this[0]=e,this;throw new Error("Not a DOM node.")},offset:function(){var t=this[0].getBoundingClientRect?this[0].getBoundingClientRect():{top:0,left:0};return{top:t.top+(e.pageYOffset||document.scrollTop||0)-(document.clientTop||0),left:t.left+(e.pageXOffset||document.scrollLeft||0)-(document.clientLeft||0)}},position:function(){function e(){for(var e=this.offsetParent||document;e&&"html"===!e.nodeType.toLowerCase&&"static"===e.style.position;)e=e.offsetParent;return e||document}var t=this[0],e=e.apply(t),r=this.offset(),o=/^(?:body|html)$/i.test(e.nodeName)?{top:0,left:0}:n(e).offset();return r.top-=parseFloat(t.style.marginTop)||0,r.left-=parseFloat(t.style.marginLeft)||0,e.style&&(o.top+=parseFloat(e.style.borderTopWidth)||0,o.left+=parseFloat(e.style.borderLeftWidth)||0),{top:r.top-o.top,left:r.left-o.left}}};var r={};n.expando="velocity"+(new Date).getTime(),n.uuid=0;for(var o={},a=o.hasOwnProperty,i=o.toString,s="Boolean Number String Function Array Date RegExp Object Error".split(" "),l=0;l<s.length;l++)o["[object "+s[l]+"]"]=s[l].toLowerCase();n.fn.init.prototype=n.fn,e.Velocity={Utilities:n}}}(window),function(a){"object"==typeof e&&"object"==typeof e.exports?e.exports=a():(r=a,o="function"==typeof r?r.call(t,n,t,e):r,!(void 0!==o&&(e.exports=o)))}(function(){return function(e,t,n,r){function o(e){for(var t=-1,n=e?e.length:0,r=[];++t<n;){var o=e[t];o&&r.push(o)}return r}function a(e){return y.isWrapped(e)?e=[].slice.call(e):y.isNode(e)&&(e=[e]),e}function i(e){var t=f.data(e,"velocity");return null===t?r:t}function s(e){return function(t){return Math.round(t*e)*(1/e)}}function l(e,n,r,o){function a(e,t){return 1-3*t+3*e}function i(e,t){return 3*t-6*e}function s(e){return 3*e}function l(e,t,n){return((a(t,n)*e+i(t,n))*e+s(t))*e}function u(e,t,n){return 3*a(t,n)*e*e+2*i(t,n)*e+s(t)}function c(t,n){for(var o=0;y>o;++o){var a=u(n,e,r);if(0===a)return n;var i=l(n,e,r)-t;n-=i/a}return n}function p(){for(var t=0;b>t;++t)T[t]=l(t*P,e,r)}function f(t,n,o){var a,i,s=0;do i=n+(o-n)/2,a=l(i,e,r)-t,a>0?o=i:n=i;while(Math.abs(a)>m&&++s<g);return i}function d(t){for(var n=0,o=1,a=b-1;o!=a&&T[o]<=t;++o)n+=P;--o;var i=(t-T[o])/(T[o+1]-T[o]),s=n+i*P,l=u(s,e,r);return l>=v?c(t,s):0==l?s:f(t,n,n+P)}function h(){w=!0,e==n&&r==o||p()}var y=4,v=.001,m=1e-7,g=10,b=11,P=1/(b-1),O="Float32Array"in t;if(4!==arguments.length)return!1;for(var C=0;4>C;++C)if("number"!=typeof arguments[C]||isNaN(arguments[C])||!isFinite(arguments[C]))return!1;e=Math.min(e,1),r=Math.min(r,1),e=Math.max(e,0),r=Math.max(r,0);var T=O?new Float32Array(b):new Array(b),w=!1,x=function(t){return w||h(),e===n&&r===o?t:0===t?0:1===t?1:l(d(t),n,o)};x.getControlPoints=function(){return[{x:e,y:n},{x:r,y:o}]};var E="generateBezier("+[e,n,r,o]+")";return x.toString=function(){return E},x}function u(e,t){var n=e;return y.isString(e)?b.Easings[e]||(n=!1):n=y.isArray(e)&&1===e.length?s.apply(null,e):y.isArray(e)&&2===e.length?P.apply(null,e.concat([t])):y.isArray(e)&&4===e.length?l.apply(null,e):!1,n===!1&&(n=b.Easings[b.defaults.easing]?b.defaults.easing:g),n}function c(e){if(e){var t=(new Date).getTime(),n=b.State.calls.length;n>1e4&&(b.State.calls=o(b.State.calls));for(var a=0;n>a;a++)if(b.State.calls[a]){var s=b.State.calls[a],l=s[0],u=s[2],d=s[3],h=!!d,v=null;d||(d=b.State.calls[a][3]=t-16);for(var m=Math.min((t-d)/u.duration,1),g=0,P=l.length;P>g;g++){var C=l[g],w=C.element;if(i(w)){var x=!1;if(u.display!==r&&null!==u.display&&"none"!==u.display){if("flex"===u.display){var E=["-webkit-box","-moz-box","-ms-flexbox","-webkit-flex"];f.each(E,function(e,t){O.setPropertyValue(w,"display",t)})}O.setPropertyValue(w,"display",u.display)}u.visibility!==r&&"hidden"!==u.visibility&&O.setPropertyValue(w,"visibility",u.visibility);for(var S in C)if("element"!==S){var k,j=C[S],_=y.isString(j.easing)?b.Easings[j.easing]:j.easing; if(1===m)k=j.endValue;else{var N=j.endValue-j.startValue;if(k=j.startValue+N*_(m,u,N),!h&&k===j.currentValue)continue}if(j.currentValue=k,"tween"===S)v=k;else{if(O.Hooks.registered[S]){var M=O.Hooks.getRoot(S),D=i(w).rootPropertyValueCache[M];D&&(j.rootPropertyValue=D)}var A=O.setPropertyValue(w,S,j.currentValue+(0===parseFloat(k)?"":j.unitType),j.rootPropertyValue,j.scrollData);O.Hooks.registered[S]&&(O.Normalizations.registered[M]?i(w).rootPropertyValueCache[M]=O.Normalizations.registered[M]("extract",null,A[1]):i(w).rootPropertyValueCache[M]=A[1]),"transform"===A[0]&&(x=!0)}}u.mobileHA&&i(w).transformCache.translate3d===r&&(i(w).transformCache.translate3d="(0px, 0px, 0px)",x=!0),x&&O.flushTransformCache(w)}}u.display!==r&&"none"!==u.display&&(b.State.calls[a][2].display=!1),u.visibility!==r&&"hidden"!==u.visibility&&(b.State.calls[a][2].visibility=!1),u.progress&&u.progress.call(s[1],s[1],m,Math.max(0,d+u.duration-t),d,v),1===m&&p(a)}}b.State.isTicking&&T(c)}function p(e,t){if(!b.State.calls[e])return!1;for(var n=b.State.calls[e][0],o=b.State.calls[e][1],a=b.State.calls[e][2],s=b.State.calls[e][4],l=!1,u=0,c=n.length;c>u;u++){var p=n[u].element;if(t||a.loop||("none"===a.display&&O.setPropertyValue(p,"display",a.display),"hidden"===a.visibility&&O.setPropertyValue(p,"visibility",a.visibility)),a.loop!==!0&&(f.queue(p)[1]===r||!/\.velocityQueueEntryFlag/i.test(f.queue(p)[1]))&&i(p)){i(p).isAnimating=!1,i(p).rootPropertyValueCache={};var d=!1;f.each(O.Lists.transforms3D,function(e,t){var n=/^scale/.test(t)?1:0,o=i(p).transformCache[t];i(p).transformCache[t]!==r&&new RegExp("^\\("+n+"[^.]").test(o)&&(d=!0,delete i(p).transformCache[t])}),a.mobileHA&&(d=!0,delete i(p).transformCache.translate3d),d&&O.flushTransformCache(p),O.Values.removeClass(p,"velocity-animating")}if(!t&&a.complete&&!a.loop&&u===c-1)try{a.complete.call(o,o)}catch(h){setTimeout(function(){throw h},1)}s&&a.loop!==!0&&s(o),i(p)&&a.loop===!0&&!t&&(f.each(i(p).tweensContainer,function(e,t){/^rotate/.test(e)&&360===parseFloat(t.endValue)&&(t.endValue=0,t.startValue=360),/^backgroundPosition/.test(e)&&100===parseFloat(t.endValue)&&"%"===t.unitType&&(t.endValue=0,t.startValue=100)}),b(p,"reverse",{loop:!0,delay:a.delay})),a.queue!==!1&&f.dequeue(p,a.queue)}b.State.calls[e]=!1;for(var y=0,v=b.State.calls.length;v>y;y++)if(b.State.calls[y]!==!1){l=!0;break}l===!1&&(b.State.isTicking=!1,delete b.State.calls,b.State.calls=[])}var f,d=function(){if(n.documentMode)return n.documentMode;for(var e=7;e>4;e--){var t=n.createElement("div");if(t.innerHTML="<!--[if IE "+e+"]><span></span><![endif]-->",t.getElementsByTagName("span").length)return t=null,e}return r}(),h=function(){var e=0;return t.webkitRequestAnimationFrame||t.mozRequestAnimationFrame||function(t){var n,r=(new Date).getTime();return n=Math.max(0,16-(r-e)),e=r+n,setTimeout(function(){t(r+n)},n)}}(),y={isString:function(e){return"string"==typeof e},isArray:Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)},isFunction:function(e){return"[object Function]"===Object.prototype.toString.call(e)},isNode:function(e){return e&&e.nodeType},isNodeList:function(e){return"object"==typeof e&&/^\[object (HTMLCollection|NodeList|Object)\]$/.test(Object.prototype.toString.call(e))&&e.length!==r&&(0===e.length||"object"==typeof e[0]&&e[0].nodeType>0)},isWrapped:function(e){return e&&(e.jquery||t.Zepto&&t.Zepto.zepto.isZ(e))},isSVG:function(e){return t.SVGElement&&e instanceof t.SVGElement},isEmptyObject:function(e){for(var t in e)return!1;return!0}},v=!1;if(e.fn&&e.fn.jquery?(f=e,v=!0):f=t.Velocity.Utilities,8>=d&&!v)throw new Error("Velocity: IE8 and below require jQuery to be loaded before Velocity.");if(7>=d)return void(jQuery.fn.velocity=jQuery.fn.animate);var m=400,g="swing",b={State:{isMobile:/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),isAndroid:/Android/i.test(navigator.userAgent),isGingerbread:/Android 2\.3\.[3-7]/i.test(navigator.userAgent),isChrome:t.chrome,isFirefox:/Firefox/i.test(navigator.userAgent),prefixElement:n.createElement("div"),prefixMatches:{},scrollAnchor:null,scrollPropertyLeft:null,scrollPropertyTop:null,isTicking:!1,calls:[]},CSS:{},Utilities:f,Redirects:{},Easings:{},Promise:t.Promise,defaults:{queue:"",duration:m,easing:g,begin:r,complete:r,progress:r,display:r,visibility:r,loop:!1,delay:!1,mobileHA:!0,_cacheValues:!0},init:function(e){f.data(e,"velocity",{isSVG:y.isSVG(e),isAnimating:!1,computedStyle:null,tweensContainer:null,rootPropertyValueCache:{},transformCache:{}})},hook:null,mock:!1,version:{major:1,minor:2,patch:2},debug:!1};t.pageYOffset!==r?(b.State.scrollAnchor=t,b.State.scrollPropertyLeft="pageXOffset",b.State.scrollPropertyTop="pageYOffset"):(b.State.scrollAnchor=n.documentElement||n.body.parentNode||n.body,b.State.scrollPropertyLeft="scrollLeft",b.State.scrollPropertyTop="scrollTop");var P=function(){function e(e){return-e.tension*e.x-e.friction*e.v}function t(t,n,r){var o={x:t.x+r.dx*n,v:t.v+r.dv*n,tension:t.tension,friction:t.friction};return{dx:o.v,dv:e(o)}}function n(n,r){var o={dx:n.v,dv:e(n)},a=t(n,.5*r,o),i=t(n,.5*r,a),s=t(n,r,i),l=1/6*(o.dx+2*(a.dx+i.dx)+s.dx),u=1/6*(o.dv+2*(a.dv+i.dv)+s.dv);return n.x=n.x+l*r,n.v=n.v+u*r,n}return function r(e,t,o){var a,i,s,l={x:-1,v:0,tension:null,friction:null},u=[0],c=0,p=1e-4,f=.016;for(e=parseFloat(e)||500,t=parseFloat(t)||20,o=o||null,l.tension=e,l.friction=t,a=null!==o,a?(c=r(e,t),i=c/o*f):i=f;;)if(s=n(s||l,i),u.push(1+s.x),c+=16,!(Math.abs(s.x)>p&&Math.abs(s.v)>p))break;return a?function(e){return u[e*(u.length-1)|0]}:c}}();b.Easings={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2},spring:function(e){return 1-Math.cos(4.5*e*Math.PI)*Math.exp(6*-e)}},f.each([["ease",[.25,.1,.25,1]],["ease-in",[.42,0,1,1]],["ease-out",[0,0,.58,1]],["ease-in-out",[.42,0,.58,1]],["easeInSine",[.47,0,.745,.715]],["easeOutSine",[.39,.575,.565,1]],["easeInOutSine",[.445,.05,.55,.95]],["easeInQuad",[.55,.085,.68,.53]],["easeOutQuad",[.25,.46,.45,.94]],["easeInOutQuad",[.455,.03,.515,.955]],["easeInCubic",[.55,.055,.675,.19]],["easeOutCubic",[.215,.61,.355,1]],["easeInOutCubic",[.645,.045,.355,1]],["easeInQuart",[.895,.03,.685,.22]],["easeOutQuart",[.165,.84,.44,1]],["easeInOutQuart",[.77,0,.175,1]],["easeInQuint",[.755,.05,.855,.06]],["easeOutQuint",[.23,1,.32,1]],["easeInOutQuint",[.86,0,.07,1]],["easeInExpo",[.95,.05,.795,.035]],["easeOutExpo",[.19,1,.22,1]],["easeInOutExpo",[1,0,0,1]],["easeInCirc",[.6,.04,.98,.335]],["easeOutCirc",[.075,.82,.165,1]],["easeInOutCirc",[.785,.135,.15,.86]]],function(e,t){b.Easings[t[0]]=l.apply(null,t[1])});var O=b.CSS={RegEx:{isHex:/^#([A-f\d]{3}){1,2}$/i,valueUnwrap:/^[A-z]+\((.*)\)$/i,wrappedValueAlreadyExtracted:/[0-9.]+ [0-9.]+ [0-9.]+( [0-9.]+)?/,valueSplit:/([A-z]+\(.+\))|(([A-z0-9#-.]+?)(?=\s|$))/gi},Lists:{colors:["fill","stroke","stopColor","color","backgroundColor","borderColor","borderTopColor","borderRightColor","borderBottomColor","borderLeftColor","outlineColor"],transformsBase:["translateX","translateY","scale","scaleX","scaleY","skewX","skewY","rotateZ"],transforms3D:["transformPerspective","translateZ","scaleZ","rotateX","rotateY"]},Hooks:{templates:{textShadow:["Color X Y Blur","black 0px 0px 0px"],boxShadow:["Color X Y Blur Spread","black 0px 0px 0px 0px"],clip:["Top Right Bottom Left","0px 0px 0px 0px"],backgroundPosition:["X Y","0% 0%"],transformOrigin:["X Y Z","50% 50% 0px"],perspectiveOrigin:["X Y","50% 50%"]},registered:{},register:function(){for(var e=0;e<O.Lists.colors.length;e++){var t="color"===O.Lists.colors[e]?"0 0 0 1":"255 255 255 1";O.Hooks.templates[O.Lists.colors[e]]=["Red Green Blue Alpha",t]}var n,r,o;if(d)for(n in O.Hooks.templates){r=O.Hooks.templates[n],o=r[0].split(" ");var a=r[1].match(O.RegEx.valueSplit);"Color"===o[0]&&(o.push(o.shift()),a.push(a.shift()),O.Hooks.templates[n]=[o.join(" "),a.join(" ")])}for(n in O.Hooks.templates){r=O.Hooks.templates[n],o=r[0].split(" ");for(var e in o){var i=n+o[e],s=e;O.Hooks.registered[i]=[n,s]}}},getRoot:function(e){var t=O.Hooks.registered[e];return t?t[0]:e},cleanRootPropertyValue:function(e,t){return O.RegEx.valueUnwrap.test(t)&&(t=t.match(O.RegEx.valueUnwrap)[1]),O.Values.isCSSNullValue(t)&&(t=O.Hooks.templates[e][1]),t},extractValue:function(e,t){var n=O.Hooks.registered[e];if(n){var r=n[0],o=n[1];return t=O.Hooks.cleanRootPropertyValue(r,t),t.toString().match(O.RegEx.valueSplit)[o]}return t},injectValue:function(e,t,n){var r=O.Hooks.registered[e];if(r){var o,a,i=r[0],s=r[1];return n=O.Hooks.cleanRootPropertyValue(i,n),o=n.toString().match(O.RegEx.valueSplit),o[s]=t,a=o.join(" ")}return n}},Normalizations:{registered:{clip:function(e,t,n){switch(e){case"name":return"clip";case"extract":var r;return O.RegEx.wrappedValueAlreadyExtracted.test(n)?r=n:(r=n.toString().match(O.RegEx.valueUnwrap),r=r?r[1].replace(/,(\s+)?/g," "):n),r;case"inject":return"rect("+n+")"}},blur:function(e,t,n){switch(e){case"name":return b.State.isFirefox?"filter":"-webkit-filter";case"extract":var r=parseFloat(n);if(!r&&0!==r){var o=n.toString().match(/blur\(([0-9]+[A-z]+)\)/i);r=o?o[1]:0}return r;case"inject":return parseFloat(n)?"blur("+n+")":"none"}},opacity:function(e,t,n){if(8>=d)switch(e){case"name":return"filter";case"extract":var r=n.toString().match(/alpha\(opacity=(.*)\)/i);return n=r?r[1]/100:1;case"inject":return t.style.zoom=1,parseFloat(n)>=1?"":"alpha(opacity="+parseInt(100*parseFloat(n),10)+")"}else switch(e){case"name":return"opacity";case"extract":return n;case"inject":return n}}},register:function(){9>=d||b.State.isGingerbread||(O.Lists.transformsBase=O.Lists.transformsBase.concat(O.Lists.transforms3D));for(var e=0;e<O.Lists.transformsBase.length;e++)!function(){var t=O.Lists.transformsBase[e];O.Normalizations.registered[t]=function(e,n,o){switch(e){case"name":return"transform";case"extract":return i(n)===r||i(n).transformCache[t]===r?/^scale/i.test(t)?1:0:i(n).transformCache[t].replace(/[()]/g,"");case"inject":var a=!1;switch(t.substr(0,t.length-1)){case"translate":a=!/(%|px|em|rem|vw|vh|\d)$/i.test(o);break;case"scal":case"scale":b.State.isAndroid&&i(n).transformCache[t]===r&&1>o&&(o=1),a=!/(\d)$/i.test(o);break;case"skew":a=!/(deg|\d)$/i.test(o);break;case"rotate":a=!/(deg|\d)$/i.test(o)}return a||(i(n).transformCache[t]="("+o+")"),i(n).transformCache[t]}}}();for(var e=0;e<O.Lists.colors.length;e++)!function(){var t=O.Lists.colors[e];O.Normalizations.registered[t]=function(e,n,o){switch(e){case"name":return t;case"extract":var a;if(O.RegEx.wrappedValueAlreadyExtracted.test(o))a=o;else{var i,s={black:"rgb(0, 0, 0)",blue:"rgb(0, 0, 255)",gray:"rgb(128, 128, 128)",green:"rgb(0, 128, 0)",red:"rgb(255, 0, 0)",white:"rgb(255, 255, 255)"};/^[A-z]+$/i.test(o)?i=s[o]!==r?s[o]:s.black:O.RegEx.isHex.test(o)?i="rgb("+O.Values.hexToRgb(o).join(" ")+")":/^rgba?\(/i.test(o)||(i=s.black),a=(i||o).toString().match(O.RegEx.valueUnwrap)[1].replace(/,(\s+)?/g," ")}return 8>=d||3!==a.split(" ").length||(a+=" 1"),a;case"inject":return 8>=d?4===o.split(" ").length&&(o=o.split(/\s+/).slice(0,3).join(" ")):3===o.split(" ").length&&(o+=" 1"),(8>=d?"rgb":"rgba")+"("+o.replace(/\s+/g,",").replace(/\.(\d)+(?=,)/g,"")+")"}}}()}},Names:{camelCase:function(e){return e.replace(/-(\w)/g,function(e,t){return t.toUpperCase()})},SVGAttribute:function(e){var t="width|height|x|y|cx|cy|r|rx|ry|x1|x2|y1|y2";return(d||b.State.isAndroid&&!b.State.isChrome)&&(t+="|transform"),new RegExp("^("+t+")$","i").test(e)},prefixCheck:function(e){if(b.State.prefixMatches[e])return[b.State.prefixMatches[e],!0];for(var t=["","Webkit","Moz","ms","O"],n=0,r=t.length;r>n;n++){var o;if(o=0===n?e:t[n]+e.replace(/^\w/,function(e){return e.toUpperCase()}),y.isString(b.State.prefixElement.style[o]))return b.State.prefixMatches[e]=o,[o,!0]}return[e,!1]}},Values:{hexToRgb:function(e){var t,n=/^#?([a-f\d])([a-f\d])([a-f\d])$/i,r=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i;return e=e.replace(n,function(e,t,n,r){return t+t+n+n+r+r}),t=r.exec(e),t?[parseInt(t[1],16),parseInt(t[2],16),parseInt(t[3],16)]:[0,0,0]},isCSSNullValue:function(e){return 0==e||/^(none|auto|transparent|(rgba\(0, ?0, ?0, ?0\)))$/i.test(e)},getUnitType:function(e){return/^(rotate|skew)/i.test(e)?"deg":/(^(scale|scaleX|scaleY|scaleZ|alpha|flexGrow|flexHeight|zIndex|fontWeight)$)|((opacity|red|green|blue|alpha)$)/i.test(e)?"":"px"},getDisplayType:function(e){var t=e&&e.tagName.toString().toLowerCase();return/^(b|big|i|small|tt|abbr|acronym|cite|code|dfn|em|kbd|strong|samp|var|a|bdo|br|img|map|object|q|script|span|sub|sup|button|input|label|select|textarea)$/i.test(t)?"inline":/^(li)$/i.test(t)?"list-item":/^(tr)$/i.test(t)?"table-row":/^(table)$/i.test(t)?"table":/^(tbody)$/i.test(t)?"table-row-group":"block"},addClass:function(e,t){e.classList?e.classList.add(t):e.className+=(e.className.length?" ":"")+t},removeClass:function(e,t){e.classList?e.classList.remove(t):e.className=e.className.toString().replace(new RegExp("(^|\\s)"+t.split(" ").join("|")+"(\\s|$)","gi")," ")}},getPropertyValue:function(e,n,o,a){function s(e,n){function o(){u&&O.setPropertyValue(e,"display","none")}var l=0;if(8>=d)l=f.css(e,n);else{var u=!1;if(/^(width|height)$/.test(n)&&0===O.getPropertyValue(e,"display")&&(u=!0,O.setPropertyValue(e,"display",O.Values.getDisplayType(e))),!a){if("height"===n&&"border-box"!==O.getPropertyValue(e,"boxSizing").toString().toLowerCase()){var c=e.offsetHeight-(parseFloat(O.getPropertyValue(e,"borderTopWidth"))||0)-(parseFloat(O.getPropertyValue(e,"borderBottomWidth"))||0)-(parseFloat(O.getPropertyValue(e,"paddingTop"))||0)-(parseFloat(O.getPropertyValue(e,"paddingBottom"))||0);return o(),c}if("width"===n&&"border-box"!==O.getPropertyValue(e,"boxSizing").toString().toLowerCase()){var p=e.offsetWidth-(parseFloat(O.getPropertyValue(e,"borderLeftWidth"))||0)-(parseFloat(O.getPropertyValue(e,"borderRightWidth"))||0)-(parseFloat(O.getPropertyValue(e,"paddingLeft"))||0)-(parseFloat(O.getPropertyValue(e,"paddingRight"))||0);return o(),p}}var h;h=i(e)===r?t.getComputedStyle(e,null):i(e).computedStyle?i(e).computedStyle:i(e).computedStyle=t.getComputedStyle(e,null),"borderColor"===n&&(n="borderTopColor"),l=9===d&&"filter"===n?h.getPropertyValue(n):h[n],""!==l&&null!==l||(l=e.style[n]),o()}if("auto"===l&&/^(top|right|bottom|left)$/i.test(n)){var y=s(e,"position");("fixed"===y||"absolute"===y&&/top|left/i.test(n))&&(l=f(e).position()[n]+"px")}return l}var l;if(O.Hooks.registered[n]){var u=n,c=O.Hooks.getRoot(u);o===r&&(o=O.getPropertyValue(e,O.Names.prefixCheck(c)[0])),O.Normalizations.registered[c]&&(o=O.Normalizations.registered[c]("extract",e,o)),l=O.Hooks.extractValue(u,o)}else if(O.Normalizations.registered[n]){var p,h;p=O.Normalizations.registered[n]("name",e),"transform"!==p&&(h=s(e,O.Names.prefixCheck(p)[0]),O.Values.isCSSNullValue(h)&&O.Hooks.templates[n]&&(h=O.Hooks.templates[n][1])),l=O.Normalizations.registered[n]("extract",e,h)}if(!/^[\d-]/.test(l))if(i(e)&&i(e).isSVG&&O.Names.SVGAttribute(n))if(/^(height|width)$/i.test(n))try{l=e.getBBox()[n]}catch(y){l=0}else l=e.getAttribute(n);else l=s(e,O.Names.prefixCheck(n)[0]);return O.Values.isCSSNullValue(l)&&(l=0),b.debug>=2&&console.log("Get "+n+": "+l),l},setPropertyValue:function(e,n,r,o,a){var s=n;if("scroll"===n)a.container?a.container["scroll"+a.direction]=r:"Left"===a.direction?t.scrollTo(r,a.alternateValue):t.scrollTo(a.alternateValue,r);else if(O.Normalizations.registered[n]&&"transform"===O.Normalizations.registered[n]("name",e))O.Normalizations.registered[n]("inject",e,r),s="transform",r=i(e).transformCache[n];else{if(O.Hooks.registered[n]){var l=n,u=O.Hooks.getRoot(n);o=o||O.getPropertyValue(e,u),r=O.Hooks.injectValue(l,r,o),n=u}if(O.Normalizations.registered[n]&&(r=O.Normalizations.registered[n]("inject",e,r),n=O.Normalizations.registered[n]("name",e)),s=O.Names.prefixCheck(n)[0],8>=d)try{e.style[s]=r}catch(c){b.debug&&console.log("Browser does not support ["+r+"] for ["+s+"]")}else i(e)&&i(e).isSVG&&O.Names.SVGAttribute(n)?e.setAttribute(n,r):e.style[s]=r;b.debug>=2&&console.log("Set "+n+" ("+s+"): "+r)}return[s,r]},flushTransformCache:function(e){function t(t){return parseFloat(O.getPropertyValue(e,t))}var n="";if((d||b.State.isAndroid&&!b.State.isChrome)&&i(e).isSVG){var r={translate:[t("translateX"),t("translateY")],skewX:[t("skewX")],skewY:[t("skewY")],scale:1!==t("scale")?[t("scale"),t("scale")]:[t("scaleX"),t("scaleY")],rotate:[t("rotateZ"),0,0]};f.each(i(e).transformCache,function(e){/^translate/i.test(e)?e="translate":/^scale/i.test(e)?e="scale":/^rotate/i.test(e)&&(e="rotate"),r[e]&&(n+=e+"("+r[e].join(" ")+") ",delete r[e])})}else{var o,a;f.each(i(e).transformCache,function(t){return o=i(e).transformCache[t],"transformPerspective"===t?(a=o,!0):(9===d&&"rotateZ"===t&&(t="rotate"),void(n+=t+o+" "))}),a&&(n="perspective"+a+" "+n)}O.setPropertyValue(e,"transform",n)}};O.Hooks.register(),O.Normalizations.register(),b.hook=function(e,t,n){var o=r;return e=a(e),f.each(e,function(e,a){if(i(a)===r&&b.init(a),n===r)o===r&&(o=b.CSS.getPropertyValue(a,t));else{var s=b.CSS.setPropertyValue(a,t,n);"transform"===s[0]&&b.CSS.flushTransformCache(a),o=s}}),o};var C=function(){function e(){return s?S.promise||null:l}function o(){function e(e){function p(e,t){var n=r,o=r,i=r;return y.isArray(e)?(n=e[0],!y.isArray(e[1])&&/^[\d-]/.test(e[1])||y.isFunction(e[1])||O.RegEx.isHex.test(e[1])?i=e[1]:(y.isString(e[1])&&!O.RegEx.isHex.test(e[1])||y.isArray(e[1]))&&(o=t?e[1]:u(e[1],s.duration),e[2]!==r&&(i=e[2]))):n=e,t||(o=o||s.easing),y.isFunction(n)&&(n=n.call(a,w,T)),y.isFunction(i)&&(i=i.call(a,w,T)),[n||0,o,i]}function d(e,t){var n,r;return r=(t||"0").toString().toLowerCase().replace(/[%A-z]+$/,function(e){return n=e,""}),n||(n=O.Values.getUnitType(e)),[r,n]}function m(){var e={myParent:a.parentNode||n.body,position:O.getPropertyValue(a,"position"),fontSize:O.getPropertyValue(a,"fontSize")},r=e.position===A.lastPosition&&e.myParent===A.lastParent,o=e.fontSize===A.lastFontSize;A.lastParent=e.myParent,A.lastPosition=e.position,A.lastFontSize=e.fontSize;var s=100,l={};if(o&&r)l.emToPx=A.lastEmToPx,l.percentToPxWidth=A.lastPercentToPxWidth,l.percentToPxHeight=A.lastPercentToPxHeight;else{var u=i(a).isSVG?n.createElementNS("http://www.w3.org/2000/svg","rect"):n.createElement("div");b.init(u),e.myParent.appendChild(u),f.each(["overflow","overflowX","overflowY"],function(e,t){b.CSS.setPropertyValue(u,t,"hidden")}),b.CSS.setPropertyValue(u,"position",e.position),b.CSS.setPropertyValue(u,"fontSize",e.fontSize),b.CSS.setPropertyValue(u,"boxSizing","content-box"),f.each(["minWidth","maxWidth","width","minHeight","maxHeight","height"],function(e,t){b.CSS.setPropertyValue(u,t,s+"%")}),b.CSS.setPropertyValue(u,"paddingLeft",s+"em"),l.percentToPxWidth=A.lastPercentToPxWidth=(parseFloat(O.getPropertyValue(u,"width",null,!0))||1)/s,l.percentToPxHeight=A.lastPercentToPxHeight=(parseFloat(O.getPropertyValue(u,"height",null,!0))||1)/s,l.emToPx=A.lastEmToPx=(parseFloat(O.getPropertyValue(u,"paddingLeft"))||1)/s,e.myParent.removeChild(u)}return null===A.remToPx&&(A.remToPx=parseFloat(O.getPropertyValue(n.body,"fontSize"))||16),null===A.vwToPx&&(A.vwToPx=parseFloat(t.innerWidth)/100,A.vhToPx=parseFloat(t.innerHeight)/100),l.remToPx=A.remToPx,l.vwToPx=A.vwToPx,l.vhToPx=A.vhToPx,b.debug>=1&&console.log("Unit ratios: "+JSON.stringify(l),a),l}if(s.begin&&0===w)try{s.begin.call(h,h)}catch(P){setTimeout(function(){throw P},1)}if("scroll"===k){var C,x,E,j=/^x$/i.test(s.axis)?"Left":"Top",_=parseFloat(s.offset)||0;s.container?y.isWrapped(s.container)||y.isNode(s.container)?(s.container=s.container[0]||s.container,C=s.container["scroll"+j],E=C+f(a).position()[j.toLowerCase()]+_):s.container=null:(C=b.State.scrollAnchor[b.State["scrollProperty"+j]],x=b.State.scrollAnchor[b.State["scrollProperty"+("Left"===j?"Top":"Left")]],E=f(a).offset()[j.toLowerCase()]+_),l={scroll:{rootPropertyValue:!1,startValue:C,currentValue:C,endValue:E,unitType:"",easing:s.easing,scrollData:{container:s.container,direction:j,alternateValue:x}},element:a},b.debug&&console.log("tweensContainer (scroll): ",l.scroll,a)}else if("reverse"===k){if(!i(a).tweensContainer)return void f.dequeue(a,s.queue);"none"===i(a).opts.display&&(i(a).opts.display="auto"),"hidden"===i(a).opts.visibility&&(i(a).opts.visibility="visible"),i(a).opts.loop=!1,i(a).opts.begin=null,i(a).opts.complete=null,g.easing||delete s.easing,g.duration||delete s.duration,s=f.extend({},i(a).opts,s);var N=f.extend(!0,{},i(a).tweensContainer);for(var M in N)if("element"!==M){var D=N[M].startValue;N[M].startValue=N[M].currentValue=N[M].endValue,N[M].endValue=D,y.isEmptyObject(g)||(N[M].easing=s.easing),b.debug&&console.log("reverse tweensContainer ("+M+"): "+JSON.stringify(N[M]),a)}l=N}else if("start"===k){var N;i(a).tweensContainer&&i(a).isAnimating===!0&&(N=i(a).tweensContainer),f.each(v,function(e,t){if(RegExp("^"+O.Lists.colors.join("$|^")+"$").test(e)){var n=p(t,!0),o=n[0],a=n[1],i=n[2];if(O.RegEx.isHex.test(o)){for(var s=["Red","Green","Blue"],l=O.Values.hexToRgb(o),u=i?O.Values.hexToRgb(i):r,c=0;c<s.length;c++){var f=[l[c]];a&&f.push(a),u!==r&&f.push(u[c]),v[e+s[c]]=f}delete v[e]}}});for(var V in v){var F=p(v[V]),I=F[0],R=F[1],K=F[2];V=O.Names.camelCase(V);var W=O.Hooks.getRoot(V),H=!1;if(i(a).isSVG||"tween"===W||O.Names.prefixCheck(W)[1]!==!1||O.Normalizations.registered[W]!==r){(s.display!==r&&null!==s.display&&"none"!==s.display||s.visibility!==r&&"hidden"!==s.visibility)&&/opacity|filter/.test(V)&&!K&&0!==I&&(K=0),s._cacheValues&&N&&N[V]?(K===r&&(K=N[V].endValue+N[V].unitType),H=i(a).rootPropertyValueCache[W]):O.Hooks.registered[V]?K===r?(H=O.getPropertyValue(a,W),K=O.getPropertyValue(a,V,H)):H=O.Hooks.templates[W][1]:K===r&&(K=O.getPropertyValue(a,V));var z,B,U,Y=!1;if(z=d(V,K),K=z[0],U=z[1],z=d(V,I),I=z[0].replace(/^([+-\/*])=/,function(e,t){return Y=t,""}),B=z[1],K=parseFloat(K)||0,I=parseFloat(I)||0,"%"===B&&(/^(fontSize|lineHeight)$/.test(V)?(I/=100,B="em"):/^scale/.test(V)?(I/=100,B=""):/(Red|Green|Blue)$/i.test(V)&&(I=I/100*255,B="")),/[\/*]/.test(Y))B=U;else if(U!==B&&0!==K)if(0===I)B=U;else{o=o||m();var q=/margin|padding|left|right|width|text|word|letter/i.test(V)||/X$/.test(V)||"x"===V?"x":"y";switch(U){case"%":K*="x"===q?o.percentToPxWidth:o.percentToPxHeight;break;case"px":break;default:K*=o[U+"ToPx"]}switch(B){case"%":K*=1/("x"===q?o.percentToPxWidth:o.percentToPxHeight);break;case"px":break;default:K*=1/o[B+"ToPx"]}}switch(Y){case"+":I=K+I;break;case"-":I=K-I;break;case"*":I=K*I;break;case"/":I=K/I}l[V]={rootPropertyValue:H,startValue:K,currentValue:K,endValue:I,unitType:B,easing:R},b.debug&&console.log("tweensContainer ("+V+"): "+JSON.stringify(l[V]),a)}else b.debug&&console.log("Skipping ["+W+"] due to a lack of browser support.")}l.element=a}l.element&&(O.Values.addClass(a,"velocity-animating"),L.push(l),""===s.queue&&(i(a).tweensContainer=l,i(a).opts=s),i(a).isAnimating=!0,w===T-1?(b.State.calls.push([L,h,s,null,S.resolver]),b.State.isTicking===!1&&(b.State.isTicking=!0,c())):w++)}var o,a=this,s=f.extend({},b.defaults,g),l={};switch(i(a)===r&&b.init(a),parseFloat(s.delay)&&s.queue!==!1&&f.queue(a,s.queue,function(e){b.velocityQueueEntryFlag=!0,i(a).delayTimer={setTimeout:setTimeout(e,parseFloat(s.delay)),next:e}}),s.duration.toString().toLowerCase()){case"fast":s.duration=200;break;case"normal":s.duration=m;break;case"slow":s.duration=600;break;default:s.duration=parseFloat(s.duration)||1}b.mock!==!1&&(b.mock===!0?s.duration=s.delay=1:(s.duration*=parseFloat(b.mock)||1,s.delay*=parseFloat(b.mock)||1)),s.easing=u(s.easing,s.duration),s.begin&&!y.isFunction(s.begin)&&(s.begin=null),s.progress&&!y.isFunction(s.progress)&&(s.progress=null),s.complete&&!y.isFunction(s.complete)&&(s.complete=null),s.display!==r&&null!==s.display&&(s.display=s.display.toString().toLowerCase(),"auto"===s.display&&(s.display=b.CSS.Values.getDisplayType(a))),s.visibility!==r&&null!==s.visibility&&(s.visibility=s.visibility.toString().toLowerCase()),s.mobileHA=s.mobileHA&&b.State.isMobile&&!b.State.isGingerbread,s.queue===!1?s.delay?setTimeout(e,s.delay):e():f.queue(a,s.queue,function(t,n){return n===!0?(S.promise&&S.resolver(h),!0):(b.velocityQueueEntryFlag=!0,void e(t))}),""!==s.queue&&"fx"!==s.queue||"inprogress"===f.queue(a)[0]||f.dequeue(a)}var s,l,d,h,v,g,P=arguments[0]&&(arguments[0].p||f.isPlainObject(arguments[0].properties)&&!arguments[0].properties.names||y.isString(arguments[0].properties));if(y.isWrapped(this)?(s=!1,d=0,h=this,l=this):(s=!0,d=1,h=P?arguments[0].elements||arguments[0].e:arguments[0]),h=a(h)){P?(v=arguments[0].properties||arguments[0].p,g=arguments[0].options||arguments[0].o):(v=arguments[d],g=arguments[d+1]);var T=h.length,w=0;if(!/^(stop|finish|finishAll)$/i.test(v)&&!f.isPlainObject(g)){var x=d+1;g={};for(var E=x;E<arguments.length;E++)y.isArray(arguments[E])||!/^(fast|normal|slow)$/i.test(arguments[E])&&!/^\d/.test(arguments[E])?y.isString(arguments[E])||y.isArray(arguments[E])?g.easing=arguments[E]:y.isFunction(arguments[E])&&(g.complete=arguments[E]):g.duration=arguments[E]}var S={promise:null,resolver:null,rejecter:null};s&&b.Promise&&(S.promise=new b.Promise(function(e,t){S.resolver=e,S.rejecter=t}));var k;switch(v){case"scroll":k="scroll";break;case"reverse":k="reverse";break;case"finish":case"finishAll":case"stop":f.each(h,function(e,t){i(t)&&i(t).delayTimer&&(clearTimeout(i(t).delayTimer.setTimeout),i(t).delayTimer.next&&i(t).delayTimer.next(),delete i(t).delayTimer),"finishAll"!==v||g!==!0&&!y.isString(g)||(f.each(f.queue(t,y.isString(g)?g:""),function(e,t){y.isFunction(t)&&t()}),f.queue(t,y.isString(g)?g:"",[]))});var j=[];return f.each(b.State.calls,function(e,t){t&&f.each(t[1],function(n,o){var a=g===r?"":g;return a===!0||t[2].queue===a||g===r&&t[2].queue===!1?void f.each(h,function(n,r){r===o&&((g===!0||y.isString(g))&&(f.each(f.queue(r,y.isString(g)?g:""),function(e,t){y.isFunction(t)&&t(null,!0)}),f.queue(r,y.isString(g)?g:"",[])),"stop"===v?(i(r)&&i(r).tweensContainer&&a!==!1&&f.each(i(r).tweensContainer,function(e,t){t.endValue=t.currentValue}),j.push(e)):"finish"!==v&&"finishAll"!==v||(t[2].duration=1))}):!0})}),"stop"===v&&(f.each(j,function(e,t){p(t,!0)}),S.promise&&S.resolver(h)),e();default:if(!f.isPlainObject(v)||y.isEmptyObject(v)){if(y.isString(v)&&b.Redirects[v]){var _=f.extend({},g),N=_.duration,M=_.delay||0;return _.backwards===!0&&(h=f.extend(!0,[],h).reverse()),f.each(h,function(e,t){parseFloat(_.stagger)?_.delay=M+parseFloat(_.stagger)*e:y.isFunction(_.stagger)&&(_.delay=M+_.stagger.call(t,e,T)),_.drag&&(_.duration=parseFloat(N)||(/^(callout|transition)/.test(v)?1e3:m),_.duration=Math.max(_.duration*(_.backwards?1-e/T:(e+1)/T),.75*_.duration,200)),b.Redirects[v].call(t,t,_||{},e,T,h,S.promise?S:r)}),e()}var D="Velocity: First argument ("+v+") was not a property map, a known action, or a registered redirect. Aborting.";return S.promise?S.rejecter(new Error(D)):console.log(D),e()}k="start"}var A={lastParent:null,lastPosition:null,lastFontSize:null,lastPercentToPxWidth:null,lastPercentToPxHeight:null,lastEmToPx:null,remToPx:null,vwToPx:null,vhToPx:null},L=[];f.each(h,function(e,t){y.isNode(t)&&o.call(t)});var V,_=f.extend({},b.defaults,g);if(_.loop=parseInt(_.loop),V=2*_.loop-1,_.loop)for(var F=0;V>F;F++){var I={delay:_.delay,progress:_.progress};F===V-1&&(I.display=_.display,I.visibility=_.visibility,I.complete=_.complete),C(h,"reverse",I)}return e()}};b=f.extend(C,b),b.animate=C;var T=t.requestAnimationFrame||h;return b.State.isMobile||n.hidden===r||n.addEventListener("visibilitychange",function(){n.hidden?(T=function(e){return setTimeout(function(){e(!0)},16)},c()):T=t.requestAnimationFrame||h}),e.Velocity=b,e!==t&&(e.fn.velocity=C,e.fn.velocity.defaults=b.defaults),f.each(["Down","Up"],function(e,t){b.Redirects["slide"+t]=function(e,n,o,a,i,s){var l=f.extend({},n),u=l.begin,c=l.complete,p={height:"",marginTop:"",marginBottom:"",paddingTop:"",paddingBottom:""},d={};l.display===r&&(l.display="Down"===t?"inline"===b.CSS.Values.getDisplayType(e)?"inline-block":"block":"none"),l.begin=function(){u&&u.call(i,i);for(var n in p){d[n]=e.style[n];var r=b.CSS.getPropertyValue(e,n);p[n]="Down"===t?[r,0]:[0,r]}d.overflow=e.style.overflow,e.style.overflow="hidden"},l.complete=function(){for(var t in d)e.style[t]=d[t];c&&c.call(i,i),s&&s.resolver(i)},b(e,p,l)}}),f.each(["In","Out"],function(e,t){b.Redirects["fade"+t]=function(e,n,o,a,i,s){var l=f.extend({},n),u={opacity:"In"===t?1:0},c=l.complete;o!==a-1?l.complete=l.begin=null:l.complete=function(){c&&c.call(i,i),s&&s.resolver(i)},l.display===r&&(l.display="In"===t?"auto":"none"),b(this,u,l)}}),b}(window.jQuery||window.Zepto||window,window,document)})},3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,function(e,t,n,r){"use strict";n(3),n(r)},function(e,t,n,r){"use strict";n(3),n(r),n(13)},function(e,t,n,r){"use strict";n(3),n(r),n(23)}]))}); //# sourceMappingURL=antd.min.js.map
website/src/pages/index.js
Pop-Code/keystone
import React, { Component } from 'react'; import Helmet from 'react-helmet'; import Hero from './components/home/Hero'; import ValueProps from './components/home/ValueProps'; import CommunityResponse from './components/home/CommunityResponse'; import AdminInterface from './components/home/AdminInterface'; import ValueProps2 from './components/home/ValueProps2'; import WhereNext from './components/home/WhereNext'; import Footer from './components/home/Footer'; export default class HomePage extends Component { render () { return ( <div> <Helmet defaultTitle={'KeystoneJS'} titleTemplate={'%s | KeystoneJS'}> <meta name="twitter:site" content="@keystonejs" /> <meta name="og:type" content="website" /> <meta name="og:site_name" content="KeystoneJS" /> <html lang="en" /> </Helmet> <Hero /> <ValueProps /> <CommunityResponse /> <AdminInterface /> <ValueProps2 /> <WhereNext /> <Footer /> </div> ); } }
src/components/collection/types/Attack.js
chaoticbackup/chaoticbackup.github.io
import { observer, inject } from 'mobx-react'; import React from 'react'; import { FlavorText, Rarity, Unique, Name, ElementIcon, Ability, AttackIcon } from '../../Snippets'; import API from '../../SpreadsheetData'; import { Thumbnail } from './helpers'; @inject((stores, props, context) => props) @observer export default class Attack extends React.Component { render() { const { card } = this.props; if (this.props.ext == false) return ( <div className="card attack"> <Thumbnail {...this.props} /> <div className="left"> <Name name={card.gsx$name} /> <Rarity set={card.gsx$set} rarity={card.gsx$rarity} /> <span><AttackIcon bp={card.gsx$bp} /> Attack - {card.gsx$bp}</span><br /> <div> <span className="bp bigger" >{card.gsx$base}</span> |&nbsp; <ElementIcon element="fire" value={card.gsx$fire} />{card.gsx$fire}&nbsp; <ElementIcon element="air" value={card.gsx$air} />{card.gsx$air}&nbsp; <ElementIcon element="earth" value={card.gsx$earth} />{card.gsx$earth}&nbsp; <ElementIcon element="water" value={card.gsx$water} />{card.gsx$water} </div> </div> <br /> <div className="right" > <Ability ability={card.gsx$ability} /> <Unique data={{ unique: card.gsx$unique, loyal: card.gsx$loyal, legendary: card.gsx$legendary }} /> <FlavorText flavortext={card.gsx$flavortext} /> </div> </div> ); else return ( <div className="card attack"> <div className="fullcard"><img src={API.cardImage(card)} width="250px" height="350px" /></div> <div className="right"> <Name name={card.gsx$name} /> <Rarity set={card.gsx$set} rarity={card.gsx$rarity} id={card.gsx$id} /> <Ability ability={card.gsx$ability} /> <Unique data={{ unique: card.gsx$unique, loyal: card.gsx$loyal, legendary: card.gsx$legendary }} /> <FlavorText flavortext={card.gsx$flavortext} /> <div>Art By: {card.gsx$artist}</div> </div> </div> ); } }
app/containers/NotFoundPage/index.js
hukid/yung
/** * NotFoundPage * * This is the page we show when the user visits a url that doesn't have a route * * NOTE: while this component should technically be a stateless functional * component (SFC), hot reloading does not currently support SFCs. If hot * reloading is not a necessity for you then you can refactor it and remove * the linting exception. */ import React from 'react'; import { FormattedMessage } from 'react-intl'; import messages from './messages'; export default class NotFound extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function render() { return ( <h1> <FormattedMessage {...messages.header} /> </h1> ); } }
packages/material-ui-icons/src/SignalWifi2BarTwoTone.js
Kagami/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path fillOpacity=".3" d="M23.64 7c-.45-.34-4.93-4-11.64-4C5.28 3 .81 6.66.36 7L12 21.5 23.64 7z" /><path d="M4.79 12.52L12 21.5l7.21-8.99C18.85 12.24 16.1 10 12 10s-6.85 2.24-7.21 2.52z" /></g></React.Fragment> , 'SignalWifi2BarTwoTone');
index.ios.js
aksharora/ReactNativeDemoBasic
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, } from 'react-native'; import BaseComponent from './src/BaseComponent'; export default class ReactDemoProject extends Component { render() { return ( <BaseComponent/> ); } } AppRegistry.registerComponent('ReactDemoProject', () => ReactDemoProject);
packages/mineral-ui-icons/src/IconExposureNeg1.js
mineral-ui/mineral-ui
/* @flow */ import React from 'react'; import Icon from 'mineral-ui/Icon'; import type { IconProps } from 'mineral-ui/Icon/types'; /* eslint-disable prettier/prettier */ export default function IconExposureNeg1(props: IconProps) { const iconProps = { rtl: false, ...props }; return ( <Icon {...iconProps}> <g> <path d="M4 11v2h8v-2H4zm15 7h-2V7.38L14 8.4V6.7L18.7 5h.3v13z"/> </g> </Icon> ); } IconExposureNeg1.displayName = 'IconExposureNeg1'; IconExposureNeg1.category = 'image';
DoD/ui/src/VirtualSchemaControl.js
mitdbg/aurum-datadiscovery
import React, { Component } from 'react'; function ButtonPanel(props) { const addRow = props.add_row; const removeRow = props.remove_row; const addColumn = props.add_column; const removeColumn = props.remove_column; const findView = props.find_view; return ( <div> <div className="row"> <div className="col mt-1"> <button type="button" className="button-addrow" data-toggle="tooltip" data-placement="left" data-html="true" title="Add <b>ROW</b>" onClick={addRow}> <span className="fas fa-arrow-circle-down"></span> </button> <button type="button" className="button-removerow" data-toggle="tooltip" data-placement="top" data-html="true" title="Remove <b>ROW</b>" onClick={removeRow}> <span className="fas fa-arrow-circle-up"></span> </button> </div> </div> <div className="row"> <div className="col mt-1"> <button type="button" className="button-addcol" data-toggle="tooltip" data-placement="left" data-html="true" title="Add <b>COLUMN</b>" onClick={addColumn}> <span className="fas fa-arrow-circle-right"></span> </button> <button type="button" className="button-removecol" data-toggle="tooltip" data-placement="right" data-html="true" title="Remove <b>COL</b>" onClick={removeColumn}> <span className="fas fa-arrow-circle-left"></span> </button> </div> </div> <div className="row"> <div className="col mt-1"> <button type="button" className="button-find" data-toggle="tooltip" data-placement="left" data-html="true" title="Find <em>views</em>" onClick={findView}> <span className="fas fa-play-circle"></span> </button> </div> </div> </div> ) } class VirtualSchemaControl extends Component { constructor(props) { super(props); } render() { return ( <div className="VirtualSchemaControl"> <ButtonPanel add_row={this.props.add_row} remove_row={this.props.remove_row} add_column={this.props.add_column} remove_column={this.props.remove_column} find_view={this.props.find_view} /> </div> ) } } export default VirtualSchemaControl;