text: // Version: 3.7.8
  (function(){
  var ca=void 0,v=!0,y=null,z=!1;function A(){return function(){}}
  window.JSON&&window.JSON.stringify||function(){function a(){try{return this.valueOf()}catch(a){return y}}function d(a){c.lastIndex=0;return c.test(a)?'"'+a.replace(c,function(a){var b=q[a];return"string"===typeof b?b:"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+a+'"'}function b(c,q){var u,r,f,h,m,g=e,l=q[c];l&&"object"===typeof l&&(l=a.call(l));"function"===typeof j&&(l=j.call(q,c,l));switch(typeof l){case "string":return d(l);case "number":return isFinite(l)?String(l):"null";case "boolean":case "null":return String(l);
  case "object":if(!l)return"null";e+=p;m=[];if("[object Array]"===Object.prototype.toString.apply(l)){h=l.length;for(u=0;u<h;u+=1)m[u]=b(u,l)||"null";f=0===m.length?"[]":e?"[\n"+e+m.join(",\n"+e)+"\n"+g+"]":"["+m.join(",")+"]";e=g;return f}if(j&&"object"===typeof j){h=j.length;for(u=0;u<h;u+=1)r=j[u],"string"===typeof r&&(f=b(r,l))&&m.push(d(r)+(e?": ":":")+f)}else for(r in l)Object.hasOwnProperty.call(l,r)&&(f=b(r,l))&&m.push(d(r)+(e?": ":":")+f);f=0===m.length?"{}":e?"{\n"+e+m.join(",\n"+e)+"\n"+
  g+"}":"{"+m.join(",")+"}";e=g;return f}}window.JSON||(window.JSON={});var c=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,e,p,q={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},j;"function"!==typeof JSON.stringify&&(JSON.stringify=function(a,c,d){var q;p=e="";if("number"===typeof d)for(q=0;q<d;q+=1)p+=" ";else"string"===typeof d&&(p=d);if((j=c)&&"function"!==typeof c&&("object"!==typeof c||"number"!==
  typeof c.length))throw Error("JSON.stringify");return b("",{"":a})});"function"!==typeof JSON.parse&&(JSON.parse=function(a){return eval("("+a+")")})}();var da=1,ea=z,fa=[],ga="-pnpres",E=1E3,ja="/",ka="&",la=/{([\w\-]+)}/g;function ma(){return"x"+ ++da+""+ +new Date}function G(){return+new Date}var pa,qa=Math.floor(20*Math.random());pa=function(a,d){return 0<a.indexOf("pubsub.")&&a.replace("pubsub","ps"+(d?ra().split("-")[0]:20>++qa?qa:qa=1))||a};
  function sa(a,d){var b=a.join(ja),c=[];if(!d)return b;M(d,function(a,b){var d="object"==typeof b?JSON.stringify(b):b;"undefined"!=typeof b&&(b!=y&&0<encodeURIComponent(d).length)&&c.push(a+"="+encodeURIComponent(d))});return b+="?"+c.join(ka)}function ta(a,d){function b(){e+d>G()?(clearTimeout(c),c=setTimeout(b,d)):(e=G(),a())}var c,e=0;return b}function ua(a,d){var b=[];M(a||[],function(a){d(a)&&b.push(a)});return b}function va(a,d){return a.replace(la,function(a,c){return d[c]||a})}
  function ra(a){var d="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(a){var c=16*Math.random()|0;return("x"==a?c:c&3|8).toString(16)});a&&a(d);return d}function wa(a){return!!a&&"string"!==typeof a&&(Array.isArray&&Array.isArray(a)||"number"===typeof a.length)}function M(a,d){if(a&&d)if(wa(a))for(var b=0,c=a.length;b<c;)d.call(a[b],a[b],b++);else for(b in a)a.hasOwnProperty&&a.hasOwnProperty(b)&&d.call(a[b],b,a[b])}
  function xa(a,d){var b=[];M(a||[],function(a,e){b.push(d(a,e))});return b}function ya(a,d){var b=[];M(a,function(a,e){d?0>a.search("-pnpres")&&e.e&&b.push(a):e.e&&b.push(a)});return b.sort()}function za(a,d){var b=[];M(a,function(a,e){d?0>a.search("-pnpres")&&e.e&&b.push(a):e.e&&b.push(a)});return b.sort()}function Aa(){setTimeout(function(){ea||(ea=1,M(fa,function(a){a()}))},E)}var T,U=14,X=8,Ba=z;
  function Ca(a,d){var b="",c,e;if(d){c=a[15];if(16<c)throw"Decryption error: Maybe bad key";if(16==c)return"";for(e=0;e<16-c;e++)b+=String.fromCharCode(a[e])}else for(e=0;16>e;e++)b+=String.fromCharCode(a[e]);return b}function Da(a,d){var b=[],c;if(!d)try{a=unescape(encodeURIComponent(a))}catch(e){throw"Error on UTF-8 encode";}for(c=0;c<a.length;c++)b[c]=a.charCodeAt(c);return b}
  function Ea(a,d){var b=12<=U?3:2,c=[],e=[],c=[],e=[],p=a.concat(d),q;c[0]=GibberishAES.p.q(p);e=c[0];for(q=1;q<b;q++)c[q]=GibberishAES.p.q(c[q-1].concat(p)),e=e.concat(c[q]);c=e.slice(0,4*X);e=e.slice(4*X,4*X+16);return{key:c,l:e}}
  function Fa(a,d,b){var d=Ga(d),c=Math.ceil(a.length/16),e=[],p,q=[];for(p=0;p<c;p++){var j=e,s=p,C=a.slice(16*p,16*p+16),u=[],r=ca,r=ca;16>C.length&&(r=16-C.length,u=[r,r,r,r,r,r,r,r,r,r,r,r,r,r,r,r]);for(r=0;r<C.length;r++)u[r]=C[r];j[s]=u}0===a.length%16&&e.push([16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16]);for(p=0;p<e.length;p++)e[p]=0===p?Ha(e[p],b):Ha(e[p],q[p-1]),q[p]=Ia(e[p],d);return q}
  function Ka(a,d,b,c){var d=Ga(d),e=a.length/16,p=[],q,j=[],s="";for(q=0;q<e;q++)p.push(a.slice(16*q,16*(q+1)));for(q=p.length-1;0<=q;q--)j[q]=La(p[q],d),j[q]=0===q?Ha(j[q],b):Ha(j[q],p[q-1]);for(q=0;q<e-1;q++)s+=Ca(j[q]);var s=s+Ca(j[q],v),C;if(c)C=s;else try{C=decodeURIComponent(escape(s))}catch(u){throw"Bad Key";}return C}function Ia(a,d){Ba=z;var b=Ma(a,d,0),c;for(c=1;c<U+1;c++)b=Na(b),b=Ua(b),c<U&&(b=Va(b)),b=Ma(b,d,c);return b}
  function La(a,d){Ba=v;var b=Ma(a,d,U),c;for(c=U-1;-1<c;c--)b=Ua(b),b=Na(b),b=Ma(b,d,c),0<c&&(b=Va(b));return b}function Na(a){var d=Ba?Wa:Xa,b=[],c;for(c=0;16>c;c++)b[c]=d[a[c]];return b}function Ua(a){var d=[],b=Ba?[0,13,10,7,4,1,14,11,8,5,2,15,12,9,6,3]:[0,5,10,15,4,9,14,3,8,13,2,7,12,1,6,11],c;for(c=0;16>c;c++)d[c]=a[b[c]];return d}
  function Va(a){var d=[],b;if(Ba)for(b=0;4>b;b++)d[4*b]=Ya[a[4*b]]^Za[a[1+4*b]]^$a[a[2+4*b]]^bb[a[3+4*b]],d[1+4*b]=bb[a[4*b]]^Ya[a[1+4*b]]^Za[a[2+4*b]]^$a[a[3+4*b]],d[2+4*b]=$a[a[4*b]]^bb[a[1+4*b]]^Ya[a[2+4*b]]^Za[a[3+4*b]],d[3+4*b]=Za[a[4*b]]^$a[a[1+4*b]]^bb[a[2+4*b]]^Ya[a[3+4*b]];else for(b=0;4>b;b++)d[4*b]=cb[a[4*b]]^ib[a[1+4*b]]^a[2+4*b]^a[3+4*b],d[1+4*b]=a[4*b]^cb[a[1+4*b]]^ib[a[2+4*b]]^a[3+4*b],d[2+4*b]=a[4*b]^a[1+4*b]^cb[a[2+4*b]]^ib[a[3+4*b]],d[3+4*b]=ib[a[4*b]]^a[1+4*b]^a[2+4*b]^cb[a[3+4*
  b]];return d}function Ma(a,d,b){var c=[],e;for(e=0;16>e;e++)c[e]=a[e]^d[b][e];return c}function Ha(a,d){var b=[],c;for(c=0;16>c;c++)b[c]=a[c]^d[c];return b}
  function Ga(a){var d=[],b=[],c,e,p=[];for(c=0;c<X;c++)e=[a[4*c],a[4*c+1],a[4*c+2],a[4*c+3]],d[c]=e;for(c=X;c<4*(U+1);c++){d[c]=[];for(a=0;4>a;a++)b[a]=d[c-1][a];if(0===c%X){a=b[0];e=ca;for(e=0;4>e;e++)b[e]=b[e+1];b[3]=a;b=jb(b);b[0]^=kb[c/X-1]}else 6<X&&4==c%X&&(b=jb(b));for(a=0;4>a;a++)d[c][a]=d[c-X][a]^b[a]}for(c=0;c<U+1;c++){p[c]=[];for(b=0;4>b;b++)p[c].push(d[4*c+b][0],d[4*c+b][1],d[4*c+b][2],d[4*c+b][3])}return p}function jb(a){for(var d=0;4>d;d++)a[d]=Xa[a[d]];return a}
  function lb(a,d){var b=[];for(i=0;i<a.length;i+=d)b[i/d]=parseInt(a.substr(i,d),16);return b}function mb(a){for(var d=[],b=0;256>b;b++){for(var c=a,e=b,p=ca,q=ca,p=q=0;8>p;p++)q=1==(e&1)?q^c:q,c=127<c?283^c<<1:c<<1,e>>>=1;d[b]=q}return d}
  var Xa=lb("637c777bf26b6fc53001672bfed7ab76ca82c97dfa5947f0add4a2af9ca472c0b7fd9326363ff7cc34a5e5f171d8311504c723c31896059a071280e2eb27b27509832c1a1b6e5aa0523bd6b329e32f8453d100ed20fcb15b6acbbe394a4c58cfd0efaafb434d338545f9027f503c9fa851a3408f929d38f5bcb6da2110fff3d2cd0c13ec5f974417c4a77e3d645d197360814fdc222a908846eeb814de5e0bdbe0323a0a4906245cc2d3ac629195e479e7c8376d8dd54ea96c56f4ea657aae08ba78252e1ca6b4c6e8dd741f4bbd8b8a703eb5664803f60e613557b986c11d9ee1f8981169d98e949b1e87e9ce5528df8ca1890dbfe6426841992d0fb054bb16",2),
  Wa,nb=Xa,ob=[];for(i=0;i<nb.length;i++)ob[nb[i]]=i;Wa=ob;var kb=lb("01020408102040801b366cd8ab4d9a2f5ebc63c697356ad4b37dfaefc591",2),cb=mb(2),ib=mb(3),bb=mb(9),Za=mb(11),$a=mb(13),Ya=mb(14),pb,qb="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",rb=qb.split("");"function"===typeof Array.indexOf&&(qb=rb);
  pb={encode:function(a){var d=[],b="",c;for(c=0;c<16*a.length;c++)d.push(a[Math.floor(c/16)][c%16]);for(c=0;c<d.length;c+=3)b+=rb[d[c]>>2],b+=rb[(d[c]&3)<<4|d[c+1]>>4],b=d[c+1]!==ca?b+rb[(d[c+1]&15)<<2|d[c+2]>>6]:b+"=",b=d[c+2]!==ca?b+rb[d[c+2]&63]:b+"=";a=b.slice(0,64);for(c=1;c<Math.ceil(b.length/64);c++)a+=b.slice(64*c,64*c+64)+(Math.ceil(b.length/64)==c+1?"":"\n");return a},decode:function(a){var a=a.replace(/\n/g,""),d=[],b=[],c=[],e;for(e=0;e<a.length;e+=4)b[0]=qb.indexOf(a.charAt(e)),b[1]=qb.indexOf(a.charAt(e+
  1)),b[2]=qb.indexOf(a.charAt(e+2)),b[3]=qb.indexOf(a.charAt(e+3)),c[0]=b[0]<<2|b[1]>>4,c[1]=(b[1]&15)<<4|b[2]>>2,c[2]=(b[2]&3)<<6|b[3],d.push(c[0],c[1],c[2]);return d=d.slice(0,d.length-d.length%16)}};
  T={size:function(a){switch(a){case 128:U=10;X=4;break;case 192:U=12;X=6;break;case 256:U=14;X=8;break;default:throw"Invalid Key Size Specified:"+a;}},h2a:function(a){var d=[];a.replace(/(..)/g,function(a){d.push(parseInt(a,16))});return d},expandKey:Ga,encryptBlock:Ia,decryptBlock:La,Decrypt:Ba,s2a:Da,rawEncrypt:Fa,rawDecrypt:Ka,dec:function(a,d,b){var a=pb.s(a),c=a.slice(8,16),c=Ea(Da(d,b),c),d=c.key,c=c.l,a=a.slice(16,a.length);return a=Ka(a,d,c,b)},openSSLKey:Ea,a2h:function(a){var d="",b;for(b=
  0;b<a.length;b++)d+=(16>a[b]?"0":"")+a[b].toString(16);return d},enc:function(a,d,b){var c;c=[];var e;for(e=0;8>e;e++)c=c.concat(Math.floor(256*Math.random()));e=Ea(Da(d,b),c);d=e.key;e=e.l;c=[[83,97,108,116,101,100,95,95].concat(c)];a=Da(a,b);a=Fa(a,d,e);a=c.concat(a);return pb.t(a)},Hash:{MD5:function(a){function d(a,b){var c,d,e,f,j;e=a&2147483648;f=b&2147483648;c=a&1073741824;d=b&1073741824;j=(a&1073741823)+(b&1073741823);return c&d?j^2147483648^e^f:c|d?j&1073741824?j^3221225472^e^f:j^1073741824^
  e^f:j^e^f}function b(a,b,c,e,f,j,h){a=d(a,d(d(b&c|~b&e,f),h));return d(a<<j|a>>>32-j,b)}function c(a,b,c,e,f,j,h){a=d(a,d(d(b&e|c&~e,f),h));return d(a<<j|a>>>32-j,b)}function e(a,b,c,e,j,f,h){a=d(a,d(d(b^c^e,j),h));return d(a<<f|a>>>32-f,b)}function p(a,b,c,e,f,j,h){a=d(a,d(d(c^(b|~e),f),h));return d(a<<j|a>>>32-j,b)}function q(a){var b,c,d=[];for(c=0;3>=c;c++)b=a>>>8*c&255,d=d.concat(b);return d}var j=[],s,C,u,r,f,h,m,g,l=lb("67452301efcdab8998badcfe10325476d76aa478e8c7b756242070dbc1bdceeef57c0faf4787c62aa8304613fd469501698098d88b44f7afffff5bb1895cd7be6b901122fd987193a679438e49b40821f61e2562c040b340265e5a51e9b6c7aad62f105d02441453d8a1e681e7d3fbc821e1cde6c33707d6f4d50d87455a14eda9e3e905fcefa3f8676f02d98d2a4c8afffa39428771f6816d9d6122fde5380ca4beea444bdecfa9f6bb4b60bebfbc70289b7ec6eaa127fad4ef308504881d05d9d4d039e6db99e51fa27cf8c4ac5665f4292244432aff97ab9423a7fc93a039655b59c38f0ccc92ffeff47d85845dd16fa87e4ffe2ce6e0a30143144e0811a1f7537e82bd3af2352ad7d2bbeb86d391",
  8),j=a.length;s=j+8;C=16*((s-s%64)/64+1);u=[];for(f=r=0;f<j;)s=(f-f%4)/4,r=8*(f%4),u[s]|=a[f]<<r,f++;s=(f-f%4)/4;u[s]|=128<<8*(f%4);u[C-2]=j<<3;u[C-1]=j>>>29;j=u;f=l[0];h=l[1];m=l[2];g=l[3];for(a=0;a<j.length;a+=16)s=f,C=h,u=m,r=g,f=b(f,h,m,g,j[a+0],7,l[4]),g=b(g,f,h,m,j[a+1],12,l[5]),m=b(m,g,f,h,j[a+2],17,l[6]),h=b(h,m,g,f,j[a+3],22,l[7]),f=b(f,h,m,g,j[a+4],7,l[8]),g=b(g,f,h,m,j[a+5],12,l[9]),m=b(m,g,f,h,j[a+6],17,l[10]),h=b(h,m,g,f,j[a+7],22,l[11]),f=b(f,h,m,g,j[a+8],7,l[12]),g=b(g,f,h,m,j[a+9],
  12,l[13]),m=b(m,g,f,h,j[a+10],17,l[14]),h=b(h,m,g,f,j[a+11],22,l[15]),f=b(f,h,m,g,j[a+12],7,l[16]),g=b(g,f,h,m,j[a+13],12,l[17]),m=b(m,g,f,h,j[a+14],17,l[18]),h=b(h,m,g,f,j[a+15],22,l[19]),f=c(f,h,m,g,j[a+1],5,l[20]),g=c(g,f,h,m,j[a+6],9,l[21]),m=c(m,g,f,h,j[a+11],14,l[22]),h=c(h,m,g,f,j[a+0],20,l[23]),f=c(f,h,m,g,j[a+5],5,l[24]),g=c(g,f,h,m,j[a+10],9,l[25]),m=c(m,g,f,h,j[a+15],14,l[26]),h=c(h,m,g,f,j[a+4],20,l[27]),f=c(f,h,m,g,j[a+9],5,l[28]),g=c(g,f,h,m,j[a+14],9,l[29]),m=c(m,g,f,h,j[a+3],14,l[30]),
  h=c(h,m,g,f,j[a+8],20,l[31]),f=c(f,h,m,g,j[a+13],5,l[32]),g=c(g,f,h,m,j[a+2],9,l[33]),m=c(m,g,f,h,j[a+7],14,l[34]),h=c(h,m,g,f,j[a+12],20,l[35]),f=e(f,h,m,g,j[a+5],4,l[36]),g=e(g,f,h,m,j[a+8],11,l[37]),m=e(m,g,f,h,j[a+11],16,l[38]),h=e(h,m,g,f,j[a+14],23,l[39]),f=e(f,h,m,g,j[a+1],4,l[40]),g=e(g,f,h,m,j[a+4],11,l[41]),m=e(m,g,f,h,j[a+7],16,l[42]),h=e(h,m,g,f,j[a+10],23,l[43]),f=e(f,h,m,g,j[a+13],4,l[44]),g=e(g,f,h,m,j[a+0],11,l[45]),m=e(m,g,f,h,j[a+3],16,l[46]),h=e(h,m,g,f,j[a+6],23,l[47]),f=e(f,h,
  m,g,j[a+9],4,l[48]),g=e(g,f,h,m,j[a+12],11,l[49]),m=e(m,g,f,h,j[a+15],16,l[50]),h=e(h,m,g,f,j[a+2],23,l[51]),f=p(f,h,m,g,j[a+0],6,l[52]),g=p(g,f,h,m,j[a+7],10,l[53]),m=p(m,g,f,h,j[a+14],15,l[54]),h=p(h,m,g,f,j[a+5],21,l[55]),f=p(f,h,m,g,j[a+12],6,l[56]),g=p(g,f,h,m,j[a+3],10,l[57]),m=p(m,g,f,h,j[a+10],15,l[58]),h=p(h,m,g,f,j[a+1],21,l[59]),f=p(f,h,m,g,j[a+8],6,l[60]),g=p(g,f,h,m,j[a+15],10,l[61]),m=p(m,g,f,h,j[a+6],15,l[62]),h=p(h,m,g,f,j[a+13],21,l[63]),f=p(f,h,m,g,j[a+4],6,l[64]),g=p(g,f,h,m,j[a+
  11],10,l[65]),m=p(m,g,f,h,j[a+2],15,l[66]),h=p(h,m,g,f,j[a+9],21,l[67]),f=d(f,s),h=d(h,C),m=d(m,u),g=d(g,r);return q(f).concat(q(h),q(m),q(g))}},Base64:pb};
  if(!window.PUBNUB){var sb=function(a,d){return CryptoJS.HmacSHA256(a,d).toString(CryptoJS.enc.Base64)},tb=function(a){return document.getElementById(a)},ub=function(a){console.error(a)},vb=function(a,d){var b=[];M(a.split(/\s+/),function(a){M((d||document).getElementsByTagName(a),function(a){b.push(a)})});return b},wb=function(a,d,b){M(a.split(","),function(a){function e(a){a||(a=window.event);b(a)||(a.cancelBubble=v,a.preventDefault&&a.preventDefault(),a.stopPropagation&&a.stopPropagation())}d.addEventListener?
  d.addEventListener(a,e,z):d.attachEvent?d.attachEvent("on"+a,e):d["on"+a]=e})},xb=function(){return vb("head")[0]},zb=function(a,d,b){if(b)a.setAttribute(d,b);else return a&&a.getAttribute&&a.getAttribute(d)},Ab=function(a,d){for(var b in d)if(d.hasOwnProperty(b))try{a.style[b]=d[b]+(0<"|width|height|top|left|".indexOf(b)&&"number"==typeof d[b]?"px":"")}catch(c){}},Bb=function(a){return document.createElement(a)},Eb=function(){return Cb||Z()?0:ma()},Fb=function(a){function d(a,b){x||(x=1,l.onerror=
  y,clearTimeout(Ja),a||!b||ab(b),setTimeout(function(){a&&Y();var b=tb(D),c=b&&b.parentNode;c&&c.removeChild(b)},E))}if(Cb||Z()){a:{var b,c,e=function(){if(!q){q=1;clearTimeout(s);try{c=JSON.parse(b.responseText)}catch(a){return h(1)}p=1;r(c)}},p=0,q=0,j=a.timeout||1E4,s=setTimeout(function(){h(1,{message:"timeout"})},j),C=a.b||A(),u=a.data||{},r=a.c||A(),f=!a.h,h=function(a,c){p||(p=1,clearTimeout(s),b&&(b.onerror=b.onload=y,b.abort&&b.abort(),b=y),a&&C(c))};try{b=Z()||window.XDomainRequest&&new XDomainRequest||
  new XMLHttpRequest;b.onerror=b.onabort=function(){h(1,b.responseText||{error:"Network Connection Error"})};b.onload=b.onloadend=e;b.onreadystatechange=function(){if(b&&4==b.readyState)switch(b.status){case 401:case 402:case 403:try{c=JSON.parse(b.responseText),h(1,c)}catch(a){return h(1,b.responseText)}}};var m=sa(a.url,u);b.open("GET",m,f);f&&(b.timeout=j);b.send()}catch(g){h(0);Cb=0;a=Fb(a);break a}a=h}return a}var l=Bb("script"),e=a.a,D=ma(),x=0,Ja=setTimeout(function(){d(1,{message:"timeout"})},
  a.timeout||1E4),Y=a.b||A(),j=a.data||{},ab=a.c||A();window[e]=function(a){d(0,a)};a.h||(l[Gb]=Gb);l.onerror=function(){d(1)};l.src=sa(a.url,j);zb(l,"id",D);xb().appendChild(l);return d},Hb=function(){if(!("onLine"in navigator))return 1;try{return navigator.onLine}catch(a){return v}},Z=function(){if(!Ib||!Ib.get)return 0;var a={id:Z.id++,send:A(),abort:function(){a.id={}},open:function(d,b){Z[a.id]=a;Ib.get(a.id,b)}};return a},Gb="async",Ob=navigator.userAgent,Cb=-1==Ob.indexOf("MSIE 6");window.console||
  (window.console=window.console||{});console.log||(console.log=console.error=(window.opera||{}).postError||A());var Pb,Qb={},Rb=z;try{Rb=window.localStorage}catch(Sb){}var Tb=function(a){return-1==document.cookie.indexOf(a)?y:((document.cookie||"").match(RegExp(a+"=([^;]+)"))||[])[1]||y},Ub=function(a,d){document.cookie=a+"="+d+"; expires=Thu, 1 Aug 2030 20:00:00 UTC; path=/"},Vb;try{Ub("pnctest","1"),Vb="1"===Tb("pnctest")}catch(Xb){Vb=z}Pb={get:function(a){try{return Rb?Rb.getItem(a):Vb?Tb(a):Qb[a]}catch(d){return Qb[a]}},
  set:function(a,d){try{if(Rb)return Rb.setItem(a,d)&&0;Vb&&Ub(a,d);Qb[a]=d}catch(b){Qb[a]=d}}};var Yb={list:{},unbind:function(a){Yb.list[a]=[]},bind:function(a,d){(Yb.list[a]=Yb.list[a]||[]).push(d)},fire:function(a,d){M(Yb.list[a]||[],function(a){a(d)})}},Zb=tb("pubnub")||0,ac=function(a){function d(){}function b(a,b){function c(b){b&&(db=G()-(b/1E4+(G()-d)/2),a&&a(db))}var d=G();b&&c(b)||B.time(c)}function c(a,b){Oa&&Oa(a,b);Oa=y;clearTimeout($);clearTimeout(R)}function e(){bc&&B.time(function(a){b(A(),
  a);a||c(1,{error:"Heartbeat failed to connect to Pubnub Servers.Please check your network settings."});R&&clearTimeout(R);R=setTimeout(e,Db)})}function p(){cc()||c(1,{error:"Offline. Please check your network settings. "});$&&clearTimeout($);$=setTimeout(p,E)}function q(a,b,c,d){var b=a.callback||b,e=a.error||t,f=I(),d=d||{};d.auth||(d.auth=a.auth_key||J);a=[L,"v1","channel-registration","sub-key",w];a.push.apply(a,c);f&&(d.callback=f);H({a:f,data:D(d),c:function(a){s(a,b,e)},b:function(a){j(a,e)},
  url:a})}function j(a,b){if("object"==typeof a&&a.error){var c={};a.message&&(c.message=a.message);a.payload&&(c.payload=a.payload);b&&b(c)}else b&&b(a)}function s(a,b,c){if("object"==typeof a){if(a.error){b={};a.message&&(b.message=a.message);a.payload&&(b.payload=a.payload);c&&c(b);return}if(a.payload){a.next_page?b&&b(a.payload,a.next_page):b&&b(a.payload);return}}b&&b(a)}function C(a){var b=0;M(ya(F),function(c){if(c=F[c])b++,(a||A())(c)});return b}function u(a){var b=0;M(za(N),function(c){if(c=
  N[c])b++,(a||A())(c)})}function r(a){if(dc){if(!aa.length)return}else{a&&(aa.n=0);if(aa.n||!aa.length)return;aa.n=1}H(aa.shift())}function f(){!eb&&h()}function h(){clearTimeout(Pa);!O||500<=O||1>O||!ya(F,v).length&&!za(N,v).length?eb=z:(eb=v,B.presence_heartbeat({callback:function(){Pa=setTimeout(h,O*E)},error:function(a){t&&t("Presence Heartbeat unable to reach Pubnub servers."+JSON.stringify(a));Pa=setTimeout(h,O*E)}}))}function m(a,b){return Qa.decrypt(a,b||V)||Qa.decrypt(a,V)||a}function g(a,
  b,c){var d=z;if("number"===typeof a)d=5<a||0==a?z:v;else{if("boolean"===typeof a)return a?30:0;d=v}return d?(c&&c("Presence Heartbeat value invalid. Valid range ( x > 5 or x = 0). Current Value : "+(b||5)),b||5):a}function l(a){var b="",c=[];M(a,function(a){c.push(a)});var d=c.sort(),e;for(e in d){var f=d[e],b=b+(f+"="+encodeURIComponent(a[f]));e!=d.length-1&&(b+="&")}return b}function D(a){a||(a={});M(P,function(b,c){b in a||(a[b]=c)});return a}function x(a){return ac(a)}function Ja(a){function b(a,
  c){var d=(a&65535)+(c&65535);return(a>>16)+(c>>16)+(d>>16)<<16|d&65535}function c(a,b){return a>>>b|a<<32-b}var d;d=a.replace(/\r\n/g,"\n");for(var a="",e=0;e<d.length;e++){var f=d.charCodeAt(e);128>f?a+=String.fromCharCode(f):(127<f&&2048>f?a+=String.fromCharCode(f>>6|192):(a+=String.fromCharCode(f>>12|224),a+=String.fromCharCode(f>>6&63|128)),a+=String.fromCharCode(f&63|128))}e=a;d=[];for(f=0;f<8*e.length;f+=8)d[f>>5]|=(e.charCodeAt(f/8)&255)<<24-f%32;var j=8*a.length,e=[1116352408,1899447441,3049323471,
  3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,
  659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],a=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],f=Array(64),h,m,l,g,p,q,t,r,s,u,w;d[j>>5]|=128<<24-j%32;d[(j+64>>9<<4)+15]=j;for(r=0;r<d.length;r+=16){j=a[0];h=a[1];m=a[2];l=a[3];g=a[4];p=a[5];q=a[6];t=a[7];for(s=0;64>s;s++)f[s]=16>s?d[s+r]:b(b(b(c(f[s-2],17)^c(f[s-2],19)^f[s-2]>>>10,f[s-7]),c(f[s-15],7)^
  c(f[s-15],18)^f[s-15]>>>3),f[s-16]),u=b(b(b(b(t,c(g,6)^c(g,11)^c(g,25)),g&p^~g&q),e[s]),f[s]),w=b(c(j,2)^c(j,13)^c(j,22),j&h^j&m^h&m),t=q,q=p,p=g,g=b(l,u),l=m,m=h,h=j,j=b(u,w);a[0]=b(j,a[0]);a[1]=b(h,a[1]);a[2]=b(m,a[2]);a[3]=b(l,a[3]);a[4]=b(g,a[4]);a[5]=b(p,a[5]);a[6]=b(q,a[6]);a[7]=b(t,a[7])}d="";for(e=0;e<4*a.length;e++)d+="0123456789abcdef".charAt(a[e>>2]>>8*(3-e%4)+4&15)+"0123456789abcdef".charAt(a[e>>2]>>8*(3-e%4)&15);return d}Cb=a.jsonp?0:-1==Ob.indexOf("MSIE 6");var Y=a.subscribe_key||"";
  a.uuid||Pb.get(Y+"uuid");var ab=a.leave_on_unload||0;a.xdr=Fb;a.db=Pb;a.error=a.error||ub;a._is_online=Hb;a.jsonp_cb=Eb;a.hmac_SHA256=sb;T.size(256);var yb=T.s2a("0123456789012345");a.crypto_obj={encrypt:function(a,b){if(!b)return a;var c=T.s2a(Ja(b).slice(0,32)),d=T.s2a(JSON.stringify(a)),c=T.rawEncrypt(d,c,yb);return T.Base64.encode(c)||a},decrypt:function(a,b){if(!b)return a;var c=T.s2a(Ja(b).slice(0,32));try{var d=T.Base64.decode(a),e=T.rawDecrypt(d,c,yb,z);return JSON.parse(e)}catch(f){}}};a.params=
  {pnsdk:"PubNub-JS-Web/3.7.8"};var Wb=+a.windowing||10,$b=(+a.timeout||310)*E,Db=(+a.keepalive||60)*E,bc=a.timecheck||0,Jb=a.noleave||0,Q=a.publish_key||"demo",w=a.subscribe_key||"demo",J=a.auth_key||"",Ra=a.secret_key||"",Kb=a.hmac_SHA256,ba=a.ssl?"s":"",oa="http"+ba+"://"+(a.origin||"pubsub.pubnub.com"),L=pa(oa),Lb=pa(oa),aa=[],fb=v,db=0,gb=0,Mb=0,Oa=0,Sa=a.restore||0,ha=0,hb=z,F={},N={},S={},Pa=y,W=g(a.heartbeat||a.pnexpires||0,a.error),O=a.heartbeat_interval||W-3,eb=z,dc=a.no_wait_for_pending,
  Nb=a["compatible_3.5"]||z,H=a.xdr,P=a.params||{},t=a.error||A(),cc=a._is_online||function(){return 1},I=a.jsonp_cb||function(){return 0},ia=a.db||{get:A(),set:A()},V=a.cipher_key,K=a.uuid||!a.unique_uuid&&ia&&ia.get(w+"uuid")||"",$,R,Qa=a.crypto_obj||{encrypt:function(a){return a},decrypt:function(a){return a}},B={LEAVE:function(a,b,c,d,e){var c={uuid:K,auth:c||J},f=pa(oa),d=d||A(),h=e||A(),e=I();if(0<a.indexOf(ga))return v;if(Nb&&(!ba||"0"==e)||Jb)return z;"0"!=e&&(c.callback=e);H({h:b||ba,timeout:2E3,
  a:e,data:D(c),c:function(a){s(a,d,h)},b:function(a){j(a,h)},url:[f,"v2","presence","sub_key",w,"channel",encodeURIComponent(a),"leave"]});return v},LEAVE_GROUP:function(a,b,c,d,e){var c={uuid:K,auth:c||J},f=pa(oa),d=d||A(),h=e||A(),e=I();if(0<a.indexOf(ga))return v;if(Nb&&(!ba||"0"==e)||Jb)return z;"0"!=e&&(c.callback=e);a&&0<a.length&&(c["channel-group"]=a);H({h:b||ba,timeout:5E3,a:e,data:D(c),c:function(a){s(a,d,h)},b:function(a){j(a,h)},url:[f,"v2","presence","sub_key",w,"channel",encodeURIComponent(","),
  "leave"]});return v},set_resumed:function(a){hb=a},get_cipher_key:function(){return V},set_cipher_key:function(a){V=a},raw_encrypt:function(a,b){return Qa.encrypt(a,b||V)||a},raw_decrypt:function(a,b){return m(a,b)},get_heartbeat:function(){return W},set_heartbeat:function(a){W=g(a,O,t);O=1<=W-3?W-3:1;d();h()},get_heartbeat_interval:function(){return O},set_heartbeat_interval:function(a){O=a;h()},get_version:function(){return"3.7.8"},getGcmMessageObject:function(a){return{data:a}},getApnsMessageObject:function(a){var b=
  {aps:{badge:1,alert:""}};for(k in a)k[b]=a[k];return b},newPnMessage:function(){var a={};gcm&&(a.pn_gcm=gcm);apns&&(a.pn_apns=apns);for(k in n)a[k]=n[k];return a},_add_param:function(a,b){P[a]=b},channel_group:function(a,b){var c=a.channel_group,d=a.channels||a.channel,e=a.cloak,f,j,h=[],m={},g=a.mode||"add";c&&(c=c.split(":"),1<c.length?(f="*"===c[0]?y:c[0],j=c[1]):j=c[0]);f&&h.push("namespace")&&h.push(encodeURIComponent(f));h.push("channel-group");j&&"*"!==j&&h.push(j);d?(wa(d)&&(d=d.join(",")),
  m[g]=d,m.cloak=fb?"true":"false"):"remove"===g&&h.push("remove");"undefined"!=typeof e&&(m.cloak=e?"true":"false");q(a,b,h,m)},channel_group_list_groups:function(a,b){var c;(c=a.namespace||a.ns||a.channel_group||y)&&(a.channel_group=c+":*");B.channel_group(a,b)},channel_group_list_channels:function(a,b){if(!a.channel_group)return t("Missing Channel Group");B.channel_group(a,b)},channel_group_remove_channel:function(a,b){if(!a.channel_group)return t("Missing Channel Group");if(!a.channel&&!a.channels)return t("Missing Channel");
  a.mode="remove";B.channel_group(a,b)},channel_group_remove_group:function(a,b){if(!a.channel_group)return t("Missing Channel Group");if(a.channel)return t("Use channel_group_remove_channel if you want to remove a channel from a group.");a.mode="remove";B.channel_group(a,b)},channel_group_add_channel:function(a,b){if(!a.channel_group)return t("Missing Channel Group");if(!a.channel&&!a.channels)return t("Missing Channel");B.channel_group(a,b)},channel_group_cloak:function(a,b){"undefined"==typeof a.cloak?
  b(fb):(fb=a.cloak,B.channel_group(a,b))},channel_group_list_namespaces:function(a,b){q(a,b,["namespace"])},channel_group_remove_namespace:function(a,b){q(a,b,["namespace",a.namespace,"remove"])},history:function(a,b){var b=a.callback||b,c=a.count||a.limit||100,d=a.reverse||"false",e=a.error||A(),f=a.auth_key||J,h=a.cipher_key,g=a.channel,l=a.channel_group,p=a.start,q=a.end,s=a.include_token,r={},u=I();if(!g&&!l)return t("Missing Channel");if(!b)return t("Missing Callback");if(!w)return t("Missing Subscribe Key");
  r.stringtoken="true";r.count=c;r.reverse=d;r.auth=f;l&&(r["channel-group"]=l,g||(g=","));u&&(r.callback=u);p&&(r.start=p);q&&(r.end=q);s&&(r.include_token="true");H({a:u,data:D(r),c:function(a){if("object"==typeof a&&a.error)e({message:a.message,payload:a.payload});else{for(var c=a[0],d=[],f=0;f<c.length;f++){var j=m(c[f],h);try{d.push(JSON.parse(j))}catch(gc){d.push(j)}}b([d,a[1],a[2]])}},b:function(a){j(a,e)},url:[L,"v2","history","sub-key",w,"channel",encodeURIComponent(g)]})},replay:function(a,
  b){var b=b||a.callback||A(),c=a.auth_key||J,d=a.source,e=a.destination,f=a.stop,j=a.start,h=a.end,m=a.reverse,g=a.limit,l=I(),p={};if(!d)return t("Missing Source Channel");if(!e)return t("Missing Destination Channel");if(!Q)return t("Missing Publish Key");if(!w)return t("Missing Subscribe Key");"0"!=l&&(p.callback=l);f&&(p.stop="all");m&&(p.reverse="true");j&&(p.start=j);h&&(p.end=h);g&&(p.count=g);p.auth=c;H({a:l,c:function(a){s(a,b,err)},b:function(){b([0,"Disconnected"])},url:[L,"v1","replay",
  Q,w,d,e],data:D(p)})},auth:function(a){J=a;d()},time:function(a){var b=I();H({a:b,data:D({uuid:K,auth:J}),timeout:5*E,url:[L,"time",b],c:function(b){a(b[0])},b:function(){a(0)}})},publish:function(a,b){var c=a.message;if(!c)return t("Missing Message");var b=b||a.callback||c.callback||A(),d=a.channel||c.channel,e=a.auth_key||J,f=a.cipher_key,h=a.error||c.error||A(),m=a.post||z,g="store_in_history"in a?a.store_in_history:v,l=I(),p="push";a.prepend&&(p="unshift");if(!d)return t("Missing Channel");if(!Q)return t("Missing Publish Key");
  if(!w)return t("Missing Subscribe Key");c.getPubnubMessage&&(c=c.getPubnubMessage());c=JSON.stringify(Qa.encrypt(c,f||V)||c);c=[L,"publish",Q,w,0,encodeURIComponent(d),l,encodeURIComponent(c)];P={uuid:K,auth:e};g||(P.store="0");aa[p]({a:l,timeout:5*E,url:c,data:D(P),b:function(a){j(a,h);r(1)},c:function(a){s(a,b,h);r(1)},mode:m?"POST":"GET"});r()},unsubscribe:function(a,b){var c=a.channel,e=a.channel_group,f=a.auth_key||J,b=b||a.callback||A(),j=a.error||A();ha=0;c&&(c=xa((c.join?c.join(","):""+c).split(","),
  function(a){if(F[a])return a+","+a+ga}).join(","),M(c.split(","),function(a){var c=v;a&&(F[a]=0,a in S&&delete S[a],ea&&(c=B.LEAVE(a,0,f,b,j)),c||b({action:"leave"}))}));e&&(e=xa((e.join?e.join(","):""+e).split(","),function(a){if(N[a])return a+","+a+ga}).join(","),M(e.split(","),function(a){var c=v;a&&(N[a]=0,a in S&&delete S[a],ea&&(c=B.LEAVE_GROUP(a,0,f,b,j)),c||b({action:"leave"}))}));d()},subscribe:function(a,b){function e(a){a?setTimeout(d,E):(L=pa(oa,1),Lb=pa(oa,1),setTimeout(function(){B.time(e)},
  E));C(function(b){if(a&&b.d)return b.d=0,b.k(b.name);!a&&!b.d&&(b.d=1,b.j(b.name))});u(function(b){if(a&&b.d)return b.d=0,b.k(b.name);!a&&!b.d&&(b.d=1,b.j(b.name))})}function h(){var a=I(),b=ya(F).join(","),g=za(N).join(",");if(b||g){b||(b=",");c();var l=D({uuid:K,auth:p});g&&(l["channel-group"]=g);2<JSON.stringify(S).length&&(l.state=JSON.stringify(S));W&&(l.heartbeat=W);f();Oa=H({timeout:aa,a:a,b:function(a){a.error&&a.service?(j(a,x),e(1)):B.time(function(b){!b&&j(a,x);e(b)})},data:D(l),url:[Lb,
  "subscribe",w,encodeURIComponent(b),a,ha],c:function(a){if(!a||"object"==typeof a&&"error"in a&&a.error)return x(a.error),setTimeout(d,E);O(a[1]);ha=!ha&&Sa&&ia.get(w)||a[1];C(function(a){a.f||(a.f=1,a.i(a.name))});u(function(a){a.f||(a.f=1,a.i(a.name))});if(hb&&!Sa)ha=0,hb=z,ia.set(w,0);else{Q&&(ha=1E4,Q=0);ia.set(w,a[1]);var b,c="",e="";3<a.length?(c=a[3],e=a[2]):c=2<a.length?a[2]:xa(ya(F),function(b){return xa(Array(a[0].length).join(",").split(","),function(){return b})}).join(",");var f=c.split(","),
  j=e?e.split(","):[];b=function(){var a=f.shift()||Mb,b=j.shift(),c={};b?(a&&(0<=a.indexOf("-pnpres")&&0>b.indexOf("-pnpres"))&&(b+="-pnpres"),c=N[b]||F[b]||{callback:A()}):c=F[a];a=[c.a||gb,a.split(ga)[0]];b&&a.push(b.split(ga)[0]);return a};var g=G()-db-+a[1]/1E4;M(a[0],function(c){var d=b(),c=m(c,F[d[1]]?F[d[1]].cipher_key:y);d[0]&&d[0](c,a,d[2]||d[1],g,d[1])})}setTimeout(h,$)}})}}var g=a.channel,l=a.channel_group,b=(b=b||a.callback)||a.message,p=a.auth_key||J,q=a.connect||A(),r=a.reconnect||A(),
  s=a.disconnect||A(),x=a.error||A(),O=a.idle||A(),na=a.presence||0,P=a.noheresync||0,Q=a.backfill||0,Y=a.timetoken||0,aa=a.timeout||$b,$=a.windowing||Wb,R=a.state,V=a.heartbeat||a.pnexpires,ba=a.restore||Sa;Sa=ba;ha=Y;if(!g&&!l)return t("Missing Channel");if(!b)return t("Missing Callback");if(!w)return t("Missing Subscribe Key");(V||0===V)&&B.set_heartbeat(V);g&&M((g.join?g.join(","):""+g).split(","),function(c){var d=F[c]||{};F[Mb=c]={name:c,f:d.f,d:d.d,e:1,a:gb=b,cipher_key:a.cipher_key,i:q,j:s,
  k:r};R&&(S[c]=c in R?R[c]:R);na&&(B.subscribe({channel:c+ga,callback:na,restore:ba}),!d.e&&!P&&B.here_now({channel:c,callback:function(a){M("uuids"in a?a.uuids:[],function(b){na({action:"join",uuid:b,timestamp:Math.floor(G()/1E3),occupancy:a.occupancy||1},a,c)})}}))});l&&M((l.join?l.join(","):""+l).split(","),function(c){var d=N[c]||{};N[c]={name:c,f:d.f,d:d.d,e:1,a:gb=b,cipher_key:a.cipher_key,i:q,j:s,k:r};na&&(B.subscribe({channel_group:c+ga,callback:na,restore:ba}),!d.e&&!P&&B.here_now({channel_group:c,
  callback:function(a){M("uuids"in a?a.uuids:[],function(b){na({action:"join",uuid:b,timestamp:Math.floor(G()/1E3),occupancy:a.occupancy||1},a,c)})}}))});d=function(){c();setTimeout(h,$)};if(!ea)return fa.push(d);d()},here_now:function(a,b){var b=a.callback||b,c=a.error||A(),d=a.auth_key||J,e=a.channel,f=a.channel_group,h=I(),g=a.state,d={uuid:K,auth:d};if(!("uuids"in a?a.uuids:1))d.disable_uuids=1;g&&(d.state=1);if(!b)return t("Missing Callback");if(!w)return t("Missing Subscribe Key");g=[L,"v2","presence",
  "sub_key",w];e&&g.push("channel")&&g.push(encodeURIComponent(e));"0"!=h&&(d.callback=h);f&&(d["channel-group"]=f,!e&&g.push("channel")&&g.push(","));H({a:h,data:D(d),c:function(a){s(a,b,c)},b:function(a){j(a,c)},url:g})},where_now:function(a,b){var b=a.callback||b,c=a.error||A(),d=a.auth_key||J,e=I(),f=a.uuid||K,d={auth:d};if(!b)return t("Missing Callback");if(!w)return t("Missing Subscribe Key");"0"!=e&&(d.callback=e);H({a:e,data:D(d),c:function(a){s(a,b,c)},b:function(a){j(a,c)},url:[L,"v2","presence",
  "sub_key",w,"uuid",encodeURIComponent(f)]})},state:function(a,b){var b=a.callback||b||A(),c=a.error||A(),d=a.auth_key||J,e=I(),f=a.state,h=a.uuid||K,g=a.channel,l=a.channel_group,d=D({auth:d});if(!w)return t("Missing Subscribe Key");if(!h)return t("Missing UUID");if(!g&&!l)return t("Missing Channel");"0"!=e&&(d.callback=e);"undefined"!=typeof g&&F[g]&&F[g].e&&f&&(S[g]=f);"undefined"!=typeof l&&(N[l]&&N[l].e)&&(f&&(S[l]=f),d["channel-group"]=l,g||(g=","));d.state=JSON.stringify(f);f=f?[L,"v2","presence",
  "sub-key",w,"channel",g,"uuid",h,"data"]:[L,"v2","presence","sub-key",w,"channel",g,"uuid",encodeURIComponent(h)];H({a:e,data:D(d),c:function(a){s(a,b,c)},b:function(a){j(a,c)},url:f})},grant:function(a,b){var b=a.callback||b,c=a.error||A(),d=a.channel,e=a.channel_group,f=I(),h=a.ttl,g=a.read?"1":"0",m=a.write?"1":"0",p=a.manage?"1":"0",q=a.auth_key;if(!b)return t("Missing Callback");if(!w)return t("Missing Subscribe Key");if(!Q)return t("Missing Publish Key");if(!Ra)return t("Missing Secret Key");
  var r=w+"\n"+Q+"\ngrant\n",g={w:m,r:g,timestamp:Math.floor((new Date).getTime()/1E3)};a.manage&&(g.m=p);"undefined"!=typeof d&&(d!=y&&0<d.length)&&(g.channel=d);"undefined"!=typeof e&&(e!=y&&0<e.length)&&(g["channel-group"]=e);"0"!=f&&(g.callback=f);if(h||0===h)g.ttl=h;q&&(g.auth=q);g=D(g);q||delete g.auth;r+=l(g);d=Kb(r,Ra);d=d.replace(/\+/g,"-");d=d.replace(/\//g,"_");g.signature=d;H({a:f,data:g,c:function(a){s(a,b,c)},b:function(a){j(a,c)},url:[L,"v1","auth","grant","sub-key",w]})},mobile_gw_provision:function(a){var b=
  a.callback||A(),c=a.auth_key||J,d=a.error||A(),e=I(),f=a.channel,g=a.op,h=a.gw_type,a=a.device_id;if(!a)return t("Missing Device ID (device_id)");if(!h)return t("Missing GW Type (gw_type: gcm or apns)");if(!g)return t("Missing GW Operation (op: add or remove)");if(!f)return t("Missing gw destination Channel (channel)");if(!Q)return t("Missing Publish Key");if(!w)return t("Missing Subscribe Key");a=[L,"v1/push/sub-key",w,"devices",a];P={uuid:K,auth:c,type:h};"add"==g?P.add=f:"remove"==g&&(P.remove=
  f);H({a:e,data:P,c:function(a){s(a,b,d)},b:function(a){j(a,d)},url:a})},audit:function(a,b){var b=a.callback||b,c=a.error||A(),d=a.channel,e=a.channel_group,f=a.auth_key,g=I();if(!b)return t("Missing Callback");if(!w)return t("Missing Subscribe Key");if(!Q)return t("Missing Publish Key");if(!Ra)return t("Missing Secret Key");var h=w+"\n"+Q+"\naudit\n",m={timestamp:Math.floor((new Date).getTime()/1E3)};"0"!=g&&(m.callback=g);"undefined"!=typeof d&&(d!=y&&0<d.length)&&(m.channel=d);"undefined"!=typeof e&&
  (e!=y&&0<e.length)&&(m["channel-group"]=e);f&&(m.auth=f);m=D(m);f||delete m.auth;h+=l(m);d=Kb(h,Ra);d=d.replace(/\+/g,"-");d=d.replace(/\//g,"_");m.signature=d;H({a:g,data:m,c:function(a){s(a,b,c)},b:function(a){j(a,c)},url:[L,"v1","auth","audit","sub-key",w]})},revoke:function(a,b){a.read=z;a.write=z;B.grant(a,b)},set_uuid:function(a){K=a;d()},get_uuid:function(){return K},isArray:function(a){return wa(a)},get_subscibed_channels:function(){return ya(F,v)},presence_heartbeat:function(a){var b=a.callback||
  A(),c=a.error||A(),a=I(),d={uuid:K,auth:J};2<JSON.stringify(S).length&&(d.state=JSON.stringify(S));0<W&&320>W&&(d.heartbeat=W);"0"!=a&&(d.callback=a);var e;e=ya(F,v).join(",");e=encodeURIComponent(e);var f=za(N,v).join(",");e||(e=",");f&&(d["channel-group"]=f);H({a:a,data:D(d),timeout:5*E,url:[L,"v2","presence","sub-key",w,"channel",e,"heartbeat"],c:function(a){s(a,b,c)},b:function(a){j(a,c)}})},stop_timers:function(){clearTimeout($);clearTimeout(R)},xdr:H,ready:Aa,db:ia,uuid:ra,map:xa,each:M,"each-channel":C,
  grep:ua,offline:function(){c(1,{message:"Offline. Please check your network settings."})},supplant:va,now:G,unique:ma,updater:ta};K||(K=B.uuid());ia.set(w+"uuid",K);$=setTimeout(p,E);R=setTimeout(e,Db);Pa=setTimeout(f,(O-3)*E);b();var Y=B,Ta;for(Ta in Y)Y.hasOwnProperty(Ta)&&(x[Ta]=Y[Ta]);x.css=Ab;x.$=tb;x.create=Bb;x.bind=wb;x.head=xb;x.search=vb;x.attr=zb;x.events=Yb;x.init=x;x.secure=x;wb("beforeunload",window,function(){if(ab)x["each-channel"](function(a){x.LEAVE(a.name,0)});return v});if(a.notest)return x;
  wb("offline",window,x.offline);wb("offline",document,x.offline);return x};ac.init=ac;ac.secure=ac;"complete"===document.readyState?setTimeout(Aa,0):wb("load",window,function(){setTimeout(Aa,0)});var ec=Zb||{};PUBNUB=ac({notest:1,publish_key:zb(ec,"pub-key"),subscribe_key:zb(ec,"sub-key"),ssl:!document.location.href.indexOf("https")||"on"==zb(ec,"ssl"),origin:zb(ec,"origin"),uuid:zb(ec,"uuid")});window.jQuery&&(window.jQuery.PUBNUB=ac);"undefined"!==typeof module&&(module.exports=PUBNUB)&&Aa();var Ib=
  tb("pubnubs")||0;if(Zb){Ab(Zb,{position:"absolute",top:-E});if("opera"in window||zb(Zb,"flash"))Zb.innerHTML="<object id=pubnubs data=https://pubnub.a.ssl.fastly.net/pubnub.swf><param name=movie value=https://pubnub.a.ssl.fastly.net/pubnub.swf><param name=allowscriptaccess value=always></object>";PUBNUB.rdx=function(a,d){if(!d)return Z[a].onerror();Z[a].responseText=unescape(d);Z[a].onload()};Z.id=E}}
  var fc=PUBNUB.ws=function(a,d){if(!(this instanceof fc))return new fc(a,d);var b=this,a=b.url=a||"";b.protocol=d||"Sec-WebSocket-Protocol";var c=a.split("/"),c={ssl:"wss:"===c[0],origin:c[2],publish_key:c[3],subscribe_key:c[4],channel:c[5]};b.CONNECTING=0;b.OPEN=1;b.CLOSING=2;b.CLOSED=3;b.CLOSE_NORMAL=1E3;b.CLOSE_GOING_AWAY=1001;b.CLOSE_PROTOCOL_ERROR=1002;b.CLOSE_UNSUPPORTED=1003;b.CLOSE_TOO_LARGE=1004;b.CLOSE_NO_STATUS=1005;b.CLOSE_ABNORMAL=1006;b.onclose=b.onerror=b.onmessage=b.onopen=b.onsend=
  A();b.binaryType="";b.extensions="";b.bufferedAmount=0;b.trasnmitting=z;b.buffer=[];b.readyState=b.CONNECTING;if(!a)return b.readyState=b.CLOSED,b.onclose({code:b.CLOSE_ABNORMAL,reason:"Missing URL",wasClean:v}),b;b.g=PUBNUB.init(c);b.g.o=c;b.o=c;b.g.subscribe({restore:z,channel:c.channel,disconnect:b.onerror,reconnect:b.onopen,error:function(){b.onclose({code:b.CLOSE_ABNORMAL,reason:"Missing URL",wasClean:z})},callback:function(a){b.onmessage({data:a})},connect:function(){b.readyState=b.OPEN;b.onopen()}})};
  fc.prototype.send=function(a){var d=this;d.g.publish({channel:d.g.o.channel,message:a,callback:function(a){d.onsend({data:a})}})};
  })();
  /*
  CryptoJS v3.1.2
  code.google.com/p/crypto-js
  (c) 2009-2013 by Jeff Mott. All rights reserved.
  code.google.com/p/crypto-js/wiki/License
  */
  var CryptoJS=CryptoJS||function(h,s){var f={},g=f.lib={},q=function(){},m=g.Base={extend:function(a){q.prototype=this;var c=new q;a&&c.mixIn(a);c.hasOwnProperty("init")||(c.init=function(){c.$super.init.apply(this,arguments)});c.init.prototype=c;c.$super=this;return c},create:function(){var a=this.extend();a.init.apply(a,arguments);return a},init:function(){},mixIn:function(a){for(var c in a)a.hasOwnProperty(c)&&(this[c]=a[c]);a.hasOwnProperty("toString")&&(this.toString=a.toString)},clone:function(){return this.init.prototype.extend(this)}},
  r=g.WordArray=m.extend({init:function(a,c){a=this.words=a||[];this.sigBytes=c!=s?c:4*a.length},toString:function(a){return(a||k).stringify(this)},concat:function(a){var c=this.words,d=a.words,b=this.sigBytes;a=a.sigBytes;this.clamp();if(b%4)for(var e=0;e<a;e++)c[b+e>>>2]|=(d[e>>>2]>>>24-8*(e%4)&255)<<24-8*((b+e)%4);else if(65535<d.length)for(e=0;e<a;e+=4)c[b+e>>>2]=d[e>>>2];else c.push.apply(c,d);this.sigBytes+=a;return this},clamp:function(){var a=this.words,c=this.sigBytes;a[c>>>2]&=4294967295<<
  32-8*(c%4);a.length=h.ceil(c/4)},clone:function(){var a=m.clone.call(this);a.words=this.words.slice(0);return a},random:function(a){for(var c=[],d=0;d<a;d+=4)c.push(4294967296*h.random()|0);return new r.init(c,a)}}),l=f.enc={},k=l.Hex={stringify:function(a){var c=a.words;a=a.sigBytes;for(var d=[],b=0;b<a;b++){var e=c[b>>>2]>>>24-8*(b%4)&255;d.push((e>>>4).toString(16));d.push((e&15).toString(16))}return d.join("")},parse:function(a){for(var c=a.length,d=[],b=0;b<c;b+=2)d[b>>>3]|=parseInt(a.substr(b,
  2),16)<<24-4*(b%8);return new r.init(d,c/2)}},n=l.Latin1={stringify:function(a){var c=a.words;a=a.sigBytes;for(var d=[],b=0;b<a;b++)d.push(String.fromCharCode(c[b>>>2]>>>24-8*(b%4)&255));return d.join("")},parse:function(a){for(var c=a.length,d=[],b=0;b<c;b++)d[b>>>2]|=(a.charCodeAt(b)&255)<<24-8*(b%4);return new r.init(d,c)}},j=l.Utf8={stringify:function(a){try{return decodeURIComponent(escape(n.stringify(a)))}catch(c){throw Error("Malformed UTF-8 data");}},parse:function(a){return n.parse(unescape(encodeURIComponent(a)))}},
  u=g.BufferedBlockAlgorithm=m.extend({reset:function(){this._data=new r.init;this._nDataBytes=0},_append:function(a){"string"==typeof a&&(a=j.parse(a));this._data.concat(a);this._nDataBytes+=a.sigBytes},_process:function(a){var c=this._data,d=c.words,b=c.sigBytes,e=this.blockSize,f=b/(4*e),f=a?h.ceil(f):h.max((f|0)-this._minBufferSize,0);a=f*e;b=h.min(4*a,b);if(a){for(var g=0;g<a;g+=e)this._doProcessBlock(d,g);g=d.splice(0,a);c.sigBytes-=b}return new r.init(g,b)},clone:function(){var a=m.clone.call(this);
  a._data=this._data.clone();return a},_minBufferSize:0});g.Hasher=u.extend({cfg:m.extend(),init:function(a){this.cfg=this.cfg.extend(a);this.reset()},reset:function(){u.reset.call(this);this._doReset()},update:function(a){this._append(a);this._process();return this},finalize:function(a){a&&this._append(a);return this._doFinalize()},blockSize:16,_createHelper:function(a){return function(c,d){return(new a.init(d)).finalize(c)}},_createHmacHelper:function(a){return function(c,d){return(new t.HMAC.init(a,
  d)).finalize(c)}}});var t=f.algo={};return f}(Math);
  (function(h){for(var s=CryptoJS,f=s.lib,g=f.WordArray,q=f.Hasher,f=s.algo,m=[],r=[],l=function(a){return 4294967296*(a-(a|0))|0},k=2,n=0;64>n;){var j;a:{j=k;for(var u=h.sqrt(j),t=2;t<=u;t++)if(!(j%t)){j=!1;break a}j=!0}j&&(8>n&&(m[n]=l(h.pow(k,0.5))),r[n]=l(h.pow(k,1/3)),n++);k++}var a=[],f=f.SHA256=q.extend({_doReset:function(){this._hash=new g.init(m.slice(0))},_doProcessBlock:function(c,d){for(var b=this._hash.words,e=b[0],f=b[1],g=b[2],j=b[3],h=b[4],m=b[5],n=b[6],q=b[7],p=0;64>p;p++){if(16>p)a[p]=
  c[d+p]|0;else{var k=a[p-15],l=a[p-2];a[p]=((k<<25|k>>>7)^(k<<14|k>>>18)^k>>>3)+a[p-7]+((l<<15|l>>>17)^(l<<13|l>>>19)^l>>>10)+a[p-16]}k=q+((h<<26|h>>>6)^(h<<21|h>>>11)^(h<<7|h>>>25))+(h&m^~h&n)+r[p]+a[p];l=((e<<30|e>>>2)^(e<<19|e>>>13)^(e<<10|e>>>22))+(e&f^e&g^f&g);q=n;n=m;m=h;h=j+k|0;j=g;g=f;f=e;e=k+l|0}b[0]=b[0]+e|0;b[1]=b[1]+f|0;b[2]=b[2]+g|0;b[3]=b[3]+j|0;b[4]=b[4]+h|0;b[5]=b[5]+m|0;b[6]=b[6]+n|0;b[7]=b[7]+q|0},_doFinalize:function(){var a=this._data,d=a.words,b=8*this._nDataBytes,e=8*a.sigBytes;
  d[e>>>5]|=128<<24-e%32;d[(e+64>>>9<<4)+14]=h.floor(b/4294967296);d[(e+64>>>9<<4)+15]=b;a.sigBytes=4*d.length;this._process();return this._hash},clone:function(){var a=q.clone.call(this);a._hash=this._hash.clone();return a}});s.SHA256=q._createHelper(f);s.HmacSHA256=q._createHmacHelper(f)})(Math);
  (function(){var h=CryptoJS,s=h.enc.Utf8;h.algo.HMAC=h.lib.Base.extend({init:function(f,g){f=this._hasher=new f.init;"string"==typeof g&&(g=s.parse(g));var h=f.blockSize,m=4*h;g.sigBytes>m&&(g=f.finalize(g));g.clamp();for(var r=this._oKey=g.clone(),l=this._iKey=g.clone(),k=r.words,n=l.words,j=0;j<h;j++)k[j]^=1549556828,n[j]^=909522486;r.sigBytes=l.sigBytes=m;this.reset()},reset:function(){var f=this._hasher;f.reset();f.update(this._iKey)},update:function(f){this._hasher.update(f);return this},finalize:function(f){var g=
  this._hasher;f=g.finalize(f);g.reset();return g.finalize(this._oKey.clone().concat(f))}})})();
  /*
  CryptoJS v3.1.2
  code.google.com/p/crypto-js
  (c) 2009-2013 by Jeff Mott. All rights reserved.
  code.google.com/p/crypto-js/wiki/License
  */
  (function(){var h=CryptoJS,j=h.lib.WordArray;h.enc.Base64={stringify:function(b){var e=b.words,f=b.sigBytes,c=this._map;b.clamp();b=[];for(var a=0;a<f;a+=3)for(var d=(e[a>>>2]>>>24-8*(a%4)&255)<<16|(e[a+1>>>2]>>>24-8*((a+1)%4)&255)<<8|e[a+2>>>2]>>>24-8*((a+2)%4)&255,g=0;4>g&&a+0.75*g<f;g++)b.push(c.charAt(d>>>6*(3-g)&63));if(e=c.charAt(64))for(;b.length%4;)b.push(e);return b.join("")},parse:function(b){var e=b.length,f=this._map,c=f.charAt(64);c&&(c=b.indexOf(c),-1!=c&&(e=c));for(var c=[],a=0,d=0;d<
  e;d++)if(d%4){var g=f.indexOf(b.charAt(d-1))<<2*(d%4),h=f.indexOf(b.charAt(d))>>>6-2*(d%4);c[a>>>2]|=(g|h)<<24-8*(a%4);a++}return j.create(c,a)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}})();
  
  var subsub = {
    observers: {},
    message: function(message, env, channel) {
  
      for(var i in subsub.observers[channel]) {
        subsub.observers[channel][i](message, env, channel);
      }
  
    },
    subscribe: function(pubnub, channel, connect, callback) {
  
      if(typeof(subsub.observers[channel]) == "undefined") {
  
        subsub.observers[channel] = [callback];
  
        connect = connect || function(){};
  
        pubnub.subscribe({
          channel: channel,
          connect: connect,
          message: function(message, env, channel) {
            subsub.message(message, env, channel );
          }
        });
  
      } else {
        subsub.observers[channel].push(callback);
      }
  
    }
  };
  !function(){function n(n){return n&&(n.ownerDocument||n.document||n).documentElement}function t(n){return n&&(n.ownerDocument&&n.ownerDocument.defaultView||n.document&&n||n.defaultView)}function e(n,t){return t>n?-1:n>t?1:n>=t?0:0/0}function r(n){return null===n?0/0:+n}function u(n){return!isNaN(n)}function i(n){return{left:function(t,e,r,u){for(arguments.length<3&&(r=0),arguments.length<4&&(u=t.length);u>r;){var i=r+u>>>1;n(t[i],e)<0?r=i+1:u=i}return r},right:function(t,e,r,u){for(arguments.length<3&&(r=0),arguments.length<4&&(u=t.length);u>r;){var i=r+u>>>1;n(t[i],e)>0?u=i:r=i+1}return r}}}function o(n){return n.length}function a(n){for(var t=1;n*t%1;)t*=10;return t}function c(n,t){for(var e in t)Object.defineProperty(n.prototype,e,{value:t[e],enumerable:!1})}function l(){this._=Object.create(null)}function s(n){return(n+="")===pa||n[0]===va?va+n:n}function f(n){return(n+="")[0]===va?n.slice(1):n}function h(n){return s(n)in this._}function g(n){return(n=s(n))in this._&&delete this._[n]}function p(){var n=[];for(var t in this._)n.push(f(t));return n}function v(){var n=0;for(var t in this._)++n;return n}function d(){for(var n in this._)return!1;return!0}function m(){this._=Object.create(null)}function y(n){return n}function M(n,t,e){return function(){var r=e.apply(t,arguments);return r===t?n:r}}function x(n,t){if(t in n)return t;t=t.charAt(0).toUpperCase()+t.slice(1);for(var e=0,r=da.length;r>e;++e){var u=da[e]+t;if(u in n)return u}}function b(){}function _(){}function w(n){function t(){for(var t,r=e,u=-1,i=r.length;++u<i;)(t=r[u].on)&&t.apply(this,arguments);return n}var e=[],r=new l;return t.on=function(t,u){var i,o=r.get(t);return arguments.length<2?o&&o.on:(o&&(o.on=null,e=e.slice(0,i=e.indexOf(o)).concat(e.slice(i+1)),r.remove(t)),u&&e.push(r.set(t,{on:u})),n)},t}function S(){ta.event.preventDefault()}function k(){for(var n,t=ta.event;n=t.sourceEvent;)t=n;return t}function E(n){for(var t=new _,e=0,r=arguments.length;++e<r;)t[arguments[e]]=w(t);return t.of=function(e,r){return function(u){try{var i=u.sourceEvent=ta.event;u.target=n,ta.event=u,t[u.type].apply(e,r)}finally{ta.event=i}}},t}function A(n){return ya(n,_a),n}function N(n){return"function"==typeof n?n:function(){return Ma(n,this)}}function C(n){return"function"==typeof n?n:function(){return xa(n,this)}}function z(n,t){function e(){this.removeAttribute(n)}function r(){this.removeAttributeNS(n.space,n.local)}function u(){this.setAttribute(n,t)}function i(){this.setAttributeNS(n.space,n.local,t)}function o(){var e=t.apply(this,arguments);null==e?this.removeAttribute(n):this.setAttribute(n,e)}function a(){var e=t.apply(this,arguments);null==e?this.removeAttributeNS(n.space,n.local):this.setAttributeNS(n.space,n.local,e)}return n=ta.ns.qualify(n),null==t?n.local?r:e:"function"==typeof t?n.local?a:o:n.local?i:u}function q(n){return n.trim().replace(/\s+/g," ")}function L(n){return new RegExp("(?:^|\\s+)"+ta.requote(n)+"(?:\\s+|$)","g")}function T(n){return(n+"").trim().split(/^|\s+/)}function R(n,t){function e(){for(var e=-1;++e<u;)n[e](this,t)}function r(){for(var e=-1,r=t.apply(this,arguments);++e<u;)n[e](this,r)}n=T(n).map(D);var u=n.length;return"function"==typeof t?r:e}function D(n){var t=L(n);return function(e,r){if(u=e.classList)return r?u.add(n):u.remove(n);var u=e.getAttribute("class")||"";r?(t.lastIndex=0,t.test(u)||e.setAttribute("class",q(u+" "+n))):e.setAttribute("class",q(u.replace(t," ")))}}function P(n,t,e){function r(){this.style.removeProperty(n)}function u(){this.style.setProperty(n,t,e)}function i(){var r=t.apply(this,arguments);null==r?this.style.removeProperty(n):this.style.setProperty(n,r,e)}return null==t?r:"function"==typeof t?i:u}function U(n,t){function e(){delete this[n]}function r(){this[n]=t}function u(){var e=t.apply(this,arguments);null==e?delete this[n]:this[n]=e}return null==t?e:"function"==typeof t?u:r}function j(n){function t(){var t=this.ownerDocument,e=this.namespaceURI;return e?t.createElementNS(e,n):t.createElement(n)}function e(){return this.ownerDocument.createElementNS(n.space,n.local)}return"function"==typeof n?n:(n=ta.ns.qualify(n)).local?e:t}function F(){var n=this.parentNode;n&&n.removeChild(this)}function H(n){return{__data__:n}}function O(n){return function(){return ba(this,n)}}function I(n){return arguments.length||(n=e),function(t,e){return t&&e?n(t.__data__,e.__data__):!t-!e}}function Y(n,t){for(var e=0,r=n.length;r>e;e++)for(var u,i=n[e],o=0,a=i.length;a>o;o++)(u=i[o])&&t(u,o,e);return n}function Z(n){return ya(n,Sa),n}function V(n){var t,e;return function(r,u,i){var o,a=n[i].update,c=a.length;for(i!=e&&(e=i,t=0),u>=t&&(t=u+1);!(o=a[t])&&++t<c;);return o}}function X(n,t,e){function r(){var t=this[o];t&&(this.removeEventListener(n,t,t.$),delete this[o])}function u(){var u=c(t,ra(arguments));r.call(this),this.addEventListener(n,this[o]=u,u.$=e),u._=t}function i(){var t,e=new RegExp("^__on([^.]+)"+ta.requote(n)+"$");for(var r in this)if(t=r.match(e)){var u=this[r];this.removeEventListener(t[1],u,u.$),delete this[r]}}var o="__on"+n,a=n.indexOf("."),c=$;a>0&&(n=n.slice(0,a));var l=ka.get(n);return l&&(n=l,c=B),a?t?u:r:t?b:i}function $(n,t){return function(e){var r=ta.event;ta.event=e,t[0]=this.__data__;try{n.apply(this,t)}finally{ta.event=r}}}function B(n,t){var e=$(n,t);return function(n){var t=this,r=n.relatedTarget;r&&(r===t||8&r.compareDocumentPosition(t))||e.call(t,n)}}function W(e){var r=".dragsuppress-"+ ++Aa,u="click"+r,i=ta.select(t(e)).on("touchmove"+r,S).on("dragstart"+r,S).on("selectstart"+r,S);if(null==Ea&&(Ea="onselectstart"in e?!1:x(e.style,"userSelect")),Ea){var o=n(e).style,a=o[Ea];o[Ea]="none"}return function(n){if(i.on(r,null),Ea&&(o[Ea]=a),n){var t=function(){i.on(u,null)};i.on(u,function(){S(),t()},!0),setTimeout(t,0)}}}function J(n,e){e.changedTouches&&(e=e.changedTouches[0]);var r=n.ownerSVGElement||n;if(r.createSVGPoint){var u=r.createSVGPoint();if(0>Na){var i=t(n);if(i.scrollX||i.scrollY){r=ta.select("body").append("svg").style({position:"absolute",top:0,left:0,margin:0,padding:0,border:"none"},"important");var o=r[0][0].getScreenCTM();Na=!(o.f||o.e),r.remove()}}return Na?(u.x=e.pageX,u.y=e.pageY):(u.x=e.clientX,u.y=e.clientY),u=u.matrixTransform(n.getScreenCTM().inverse()),[u.x,u.y]}var a=n.getBoundingClientRect();return[e.clientX-a.left-n.clientLeft,e.clientY-a.top-n.clientTop]}function G(){return ta.event.changedTouches[0].identifier}function K(n){return n>0?1:0>n?-1:0}function Q(n,t,e){return(t[0]-n[0])*(e[1]-n[1])-(t[1]-n[1])*(e[0]-n[0])}function nt(n){return n>1?0:-1>n?qa:Math.acos(n)}function tt(n){return n>1?Ra:-1>n?-Ra:Math.asin(n)}function et(n){return((n=Math.exp(n))-1/n)/2}function rt(n){return((n=Math.exp(n))+1/n)/2}function ut(n){return((n=Math.exp(2*n))-1)/(n+1)}function it(n){return(n=Math.sin(n/2))*n}function ot(){}function at(n,t,e){return this instanceof at?(this.h=+n,this.s=+t,void(this.l=+e)):arguments.length<2?n instanceof at?new at(n.h,n.s,n.l):bt(""+n,_t,at):new at(n,t,e)}function ct(n,t,e){function r(n){return n>360?n-=360:0>n&&(n+=360),60>n?i+(o-i)*n/60:180>n?o:240>n?i+(o-i)*(240-n)/60:i}function u(n){return Math.round(255*r(n))}var i,o;return n=isNaN(n)?0:(n%=360)<0?n+360:n,t=isNaN(t)?0:0>t?0:t>1?1:t,e=0>e?0:e>1?1:e,o=.5>=e?e*(1+t):e+t-e*t,i=2*e-o,new mt(u(n+120),u(n),u(n-120))}function lt(n,t,e){return this instanceof lt?(this.h=+n,this.c=+t,void(this.l=+e)):arguments.length<2?n instanceof lt?new lt(n.h,n.c,n.l):n instanceof ft?gt(n.l,n.a,n.b):gt((n=wt((n=ta.rgb(n)).r,n.g,n.b)).l,n.a,n.b):new lt(n,t,e)}function st(n,t,e){return isNaN(n)&&(n=0),isNaN(t)&&(t=0),new ft(e,Math.cos(n*=Da)*t,Math.sin(n)*t)}function ft(n,t,e){return this instanceof ft?(this.l=+n,this.a=+t,void(this.b=+e)):arguments.length<2?n instanceof ft?new ft(n.l,n.a,n.b):n instanceof lt?st(n.h,n.c,n.l):wt((n=mt(n)).r,n.g,n.b):new ft(n,t,e)}function ht(n,t,e){var r=(n+16)/116,u=r+t/500,i=r-e/200;return u=pt(u)*Xa,r=pt(r)*$a,i=pt(i)*Ba,new mt(dt(3.2404542*u-1.5371385*r-.4985314*i),dt(-.969266*u+1.8760108*r+.041556*i),dt(.0556434*u-.2040259*r+1.0572252*i))}function gt(n,t,e){return n>0?new lt(Math.atan2(e,t)*Pa,Math.sqrt(t*t+e*e),n):new lt(0/0,0/0,n)}function pt(n){return n>.206893034?n*n*n:(n-4/29)/7.787037}function vt(n){return n>.008856?Math.pow(n,1/3):7.787037*n+4/29}function dt(n){return Math.round(255*(.00304>=n?12.92*n:1.055*Math.pow(n,1/2.4)-.055))}function mt(n,t,e){return this instanceof mt?(this.r=~~n,this.g=~~t,void(this.b=~~e)):arguments.length<2?n instanceof mt?new mt(n.r,n.g,n.b):bt(""+n,mt,ct):new mt(n,t,e)}function yt(n){return new mt(n>>16,n>>8&255,255&n)}function Mt(n){return yt(n)+""}function xt(n){return 16>n?"0"+Math.max(0,n).toString(16):Math.min(255,n).toString(16)}function bt(n,t,e){n=n.toLowerCase();var r,u,i,o=0,a=0,c=0;if(r=/([a-z]+)\((.*)\)/.exec(n))switch(u=r[2].split(","),r[1]){case"hsl":return e(parseFloat(u[0]),parseFloat(u[1])/100,parseFloat(u[2])/100);case"rgb":return t(kt(u[0]),kt(u[1]),kt(u[2]))}return(i=Ga.get(n))?t(i.r,i.g,i.b):(null==n||"#"!==n.charAt(0)||isNaN(i=parseInt(n.slice(1),16))||(4===n.length?(o=(3840&i)>>4,o=o>>4|o,a=240&i,a=a>>4|a,c=15&i,c=c<<4|c):7===n.length&&(o=(16711680&i)>>16,a=(65280&i)>>8,c=255&i)),t(o,a,c))}function _t(n,t,e){var r,u,i=Math.min(n/=255,t/=255,e/=255),o=Math.max(n,t,e),a=o-i,c=(o+i)/2;return a?(u=.5>c?a/(o+i):a/(2-o-i),r=n==o?(t-e)/a+(e>t?6:0):t==o?(e-n)/a+2:(n-t)/a+4,r*=60):(r=0/0,u=c>0&&1>c?0:r),new at(r,u,c)}function wt(n,t,e){n=St(n),t=St(t),e=St(e);var r=vt((.4124564*n+.3575761*t+.1804375*e)/Xa),u=vt((.2126729*n+.7151522*t+.072175*e)/$a),i=vt((.0193339*n+.119192*t+.9503041*e)/Ba);return ft(116*u-16,500*(r-u),200*(u-i))}function St(n){return(n/=255)<=.04045?n/12.92:Math.pow((n+.055)/1.055,2.4)}function kt(n){var t=parseFloat(n);return"%"===n.charAt(n.length-1)?Math.round(2.55*t):t}function Et(n){return"function"==typeof n?n:function(){return n}}function At(n){return function(t,e,r){return 2===arguments.length&&"function"==typeof e&&(r=e,e=null),Nt(t,e,n,r)}}function Nt(n,t,e,r){function u(){var n,t=c.status;if(!t&&zt(c)||t>=200&&300>t||304===t){try{n=e.call(i,c)}catch(r){return void o.error.call(i,r)}o.load.call(i,n)}else o.error.call(i,c)}var i={},o=ta.dispatch("beforesend","progress","load","error"),a={},c=new XMLHttpRequest,l=null;return!this.XDomainRequest||"withCredentials"in c||!/^(http(s)?:)?\/\//.test(n)||(c=new XDomainRequest),"onload"in c?c.onload=c.onerror=u:c.onreadystatechange=function(){c.readyState>3&&u()},c.onprogress=function(n){var t=ta.event;ta.event=n;try{o.progress.call(i,c)}finally{ta.event=t}},i.header=function(n,t){return n=(n+"").toLowerCase(),arguments.length<2?a[n]:(null==t?delete a[n]:a[n]=t+"",i)},i.mimeType=function(n){return arguments.length?(t=null==n?null:n+"",i):t},i.responseType=function(n){return arguments.length?(l=n,i):l},i.response=function(n){return e=n,i},["get","post"].forEach(function(n){i[n]=function(){return i.send.apply(i,[n].concat(ra(arguments)))}}),i.send=function(e,r,u){if(2===arguments.length&&"function"==typeof r&&(u=r,r=null),c.open(e,n,!0),null==t||"accept"in a||(a.accept=t+",*/*"),c.setRequestHeader)for(var s in a)c.setRequestHeader(s,a[s]);return null!=t&&c.overrideMimeType&&c.overrideMimeType(t),null!=l&&(c.responseType=l),null!=u&&i.on("error",u).on("load",function(n){u(null,n)}),o.beforesend.call(i,c),c.send(null==r?null:r),i},i.abort=function(){return c.abort(),i},ta.rebind(i,o,"on"),null==r?i:i.get(Ct(r))}function Ct(n){return 1===n.length?function(t,e){n(null==t?e:null)}:n}function zt(n){var t=n.responseType;return t&&"text"!==t?n.response:n.responseText}function qt(){var n=Lt(),t=Tt()-n;t>24?(isFinite(t)&&(clearTimeout(tc),tc=setTimeout(qt,t)),nc=0):(nc=1,rc(qt))}function Lt(){var n=Date.now();for(ec=Ka;ec;)n>=ec.t&&(ec.f=ec.c(n-ec.t)),ec=ec.n;return n}function Tt(){for(var n,t=Ka,e=1/0;t;)t.f?t=n?n.n=t.n:Ka=t.n:(t.t<e&&(e=t.t),t=(n=t).n);return Qa=n,e}function Rt(n,t){return t-(n?Math.ceil(Math.log(n)/Math.LN10):1)}function Dt(n,t){var e=Math.pow(10,3*ga(8-t));return{scale:t>8?function(n){return n/e}:function(n){return n*e},symbol:n}}function Pt(n){var t=n.decimal,e=n.thousands,r=n.grouping,u=n.currency,i=r&&e?function(n,t){for(var u=n.length,i=[],o=0,a=r[0],c=0;u>0&&a>0&&(c+a+1>t&&(a=Math.max(1,t-c)),i.push(n.substring(u-=a,u+a)),!((c+=a+1)>t));)a=r[o=(o+1)%r.length];return i.reverse().join(e)}:y;return function(n){var e=ic.exec(n),r=e[1]||" ",o=e[2]||">",a=e[3]||"-",c=e[4]||"",l=e[5],s=+e[6],f=e[7],h=e[8],g=e[9],p=1,v="",d="",m=!1,y=!0;switch(h&&(h=+h.substring(1)),(l||"0"===r&&"="===o)&&(l=r="0",o="="),g){case"n":f=!0,g="g";break;case"%":p=100,d="%",g="f";break;case"p":p=100,d="%",g="r";break;case"b":case"o":case"x":case"X":"#"===c&&(v="0"+g.toLowerCase());case"c":y=!1;case"d":m=!0,h=0;break;case"s":p=-1,g="r"}"$"===c&&(v=u[0],d=u[1]),"r"!=g||h||(g="g"),null!=h&&("g"==g?h=Math.max(1,Math.min(21,h)):("e"==g||"f"==g)&&(h=Math.max(0,Math.min(20,h)))),g=oc.get(g)||Ut;var M=l&&f;return function(n){var e=d;if(m&&n%1)return"";var u=0>n||0===n&&0>1/n?(n=-n,"-"):"-"===a?"":a;if(0>p){var c=ta.formatPrefix(n,h);n=c.scale(n),e=c.symbol+d}else n*=p;n=g(n,h);var x,b,_=n.lastIndexOf(".");if(0>_){var w=y?n.lastIndexOf("e"):-1;0>w?(x=n,b=""):(x=n.substring(0,w),b=n.substring(w))}else x=n.substring(0,_),b=t+n.substring(_+1);!l&&f&&(x=i(x,1/0));var S=v.length+x.length+b.length+(M?0:u.length),k=s>S?new Array(S=s-S+1).join(r):"";return M&&(x=i(k+x,k.length?s-b.length:1/0)),u+=v,n=x+b,("<"===o?u+n+k:">"===o?k+u+n:"^"===o?k.substring(0,S>>=1)+u+n+k.substring(S):u+(M?n:k+n))+e}}}function Ut(n){return n+""}function jt(){this._=new Date(arguments.length>1?Date.UTC.apply(this,arguments):arguments[0])}function Ft(n,t,e){function r(t){var e=n(t),r=i(e,1);return r-t>t-e?e:r}function u(e){return t(e=n(new cc(e-1)),1),e}function i(n,e){return t(n=new cc(+n),e),n}function o(n,r,i){var o=u(n),a=[];if(i>1)for(;r>o;)e(o)%i||a.push(new Date(+o)),t(o,1);else for(;r>o;)a.push(new Date(+o)),t(o,1);return a}function a(n,t,e){try{cc=jt;var r=new jt;return r._=n,o(r,t,e)}finally{cc=Date}}n.floor=n,n.round=r,n.ceil=u,n.offset=i,n.range=o;var c=n.utc=Ht(n);return c.floor=c,c.round=Ht(r),c.ceil=Ht(u),c.offset=Ht(i),c.range=a,n}function Ht(n){return function(t,e){try{cc=jt;var r=new jt;return r._=t,n(r,e)._}finally{cc=Date}}}function Ot(n){function t(n){function t(t){for(var e,u,i,o=[],a=-1,c=0;++a<r;)37===n.charCodeAt(a)&&(o.push(n.slice(c,a)),null!=(u=sc[e=n.charAt(++a)])&&(e=n.charAt(++a)),(i=N[e])&&(e=i(t,null==u?"e"===e?" ":"0":u)),o.push(e),c=a+1);return o.push(n.slice(c,a)),o.join("")}var r=n.length;return t.parse=function(t){var r={y:1900,m:0,d:1,H:0,M:0,S:0,L:0,Z:null},u=e(r,n,t,0);if(u!=t.length)return null;"p"in r&&(r.H=r.H%12+12*r.p);var i=null!=r.Z&&cc!==jt,o=new(i?jt:cc);return"j"in r?o.setFullYear(r.y,0,r.j):"w"in r&&("W"in r||"U"in r)?(o.setFullYear(r.y,0,1),o.setFullYear(r.y,0,"W"in r?(r.w+6)%7+7*r.W-(o.getDay()+5)%7:r.w+7*r.U-(o.getDay()+6)%7)):o.setFullYear(r.y,r.m,r.d),o.setHours(r.H+(r.Z/100|0),r.M+r.Z%100,r.S,r.L),i?o._:o},t.toString=function(){return n},t}function e(n,t,e,r){for(var u,i,o,a=0,c=t.length,l=e.length;c>a;){if(r>=l)return-1;if(u=t.charCodeAt(a++),37===u){if(o=t.charAt(a++),i=C[o in sc?t.charAt(a++):o],!i||(r=i(n,e,r))<0)return-1}else if(u!=e.charCodeAt(r++))return-1}return r}function r(n,t,e){_.lastIndex=0;var r=_.exec(t.slice(e));return r?(n.w=w.get(r[0].toLowerCase()),e+r[0].length):-1}function u(n,t,e){x.lastIndex=0;var r=x.exec(t.slice(e));return r?(n.w=b.get(r[0].toLowerCase()),e+r[0].length):-1}function i(n,t,e){E.lastIndex=0;var r=E.exec(t.slice(e));return r?(n.m=A.get(r[0].toLowerCase()),e+r[0].length):-1}function o(n,t,e){S.lastIndex=0;var r=S.exec(t.slice(e));return r?(n.m=k.get(r[0].toLowerCase()),e+r[0].length):-1}function a(n,t,r){return e(n,N.c.toString(),t,r)}function c(n,t,r){return e(n,N.x.toString(),t,r)}function l(n,t,r){return e(n,N.X.toString(),t,r)}function s(n,t,e){var r=M.get(t.slice(e,e+=2).toLowerCase());return null==r?-1:(n.p=r,e)}var f=n.dateTime,h=n.date,g=n.time,p=n.periods,v=n.days,d=n.shortDays,m=n.months,y=n.shortMonths;t.utc=function(n){function e(n){try{cc=jt;var t=new cc;return t._=n,r(t)}finally{cc=Date}}var r=t(n);return e.parse=function(n){try{cc=jt;var t=r.parse(n);return t&&t._}finally{cc=Date}},e.toString=r.toString,e},t.multi=t.utc.multi=ae;var M=ta.map(),x=Yt(v),b=Zt(v),_=Yt(d),w=Zt(d),S=Yt(m),k=Zt(m),E=Yt(y),A=Zt(y);p.forEach(function(n,t){M.set(n.toLowerCase(),t)});var N={a:function(n){return d[n.getDay()]},A:function(n){return v[n.getDay()]},b:function(n){return y[n.getMonth()]},B:function(n){return m[n.getMonth()]},c:t(f),d:function(n,t){return It(n.getDate(),t,2)},e:function(n,t){return It(n.getDate(),t,2)},H:function(n,t){return It(n.getHours(),t,2)},I:function(n,t){return It(n.getHours()%12||12,t,2)},j:function(n,t){return It(1+ac.dayOfYear(n),t,3)},L:function(n,t){return It(n.getMilliseconds(),t,3)},m:function(n,t){return It(n.getMonth()+1,t,2)},M:function(n,t){return It(n.getMinutes(),t,2)},p:function(n){return p[+(n.getHours()>=12)]},S:function(n,t){return It(n.getSeconds(),t,2)},U:function(n,t){return It(ac.sundayOfYear(n),t,2)},w:function(n){return n.getDay()},W:function(n,t){return It(ac.mondayOfYear(n),t,2)},x:t(h),X:t(g),y:function(n,t){return It(n.getFullYear()%100,t,2)},Y:function(n,t){return It(n.getFullYear()%1e4,t,4)},Z:ie,"%":function(){return"%"}},C={a:r,A:u,b:i,B:o,c:a,d:Qt,e:Qt,H:te,I:te,j:ne,L:ue,m:Kt,M:ee,p:s,S:re,U:Xt,w:Vt,W:$t,x:c,X:l,y:Wt,Y:Bt,Z:Jt,"%":oe};return t}function It(n,t,e){var r=0>n?"-":"",u=(r?-n:n)+"",i=u.length;return r+(e>i?new Array(e-i+1).join(t)+u:u)}function Yt(n){return new RegExp("^(?:"+n.map(ta.requote).join("|")+")","i")}function Zt(n){for(var t=new l,e=-1,r=n.length;++e<r;)t.set(n[e].toLowerCase(),e);return t}function Vt(n,t,e){fc.lastIndex=0;var r=fc.exec(t.slice(e,e+1));return r?(n.w=+r[0],e+r[0].length):-1}function Xt(n,t,e){fc.lastIndex=0;var r=fc.exec(t.slice(e));return r?(n.U=+r[0],e+r[0].length):-1}function $t(n,t,e){fc.lastIndex=0;var r=fc.exec(t.slice(e));return r?(n.W=+r[0],e+r[0].length):-1}function Bt(n,t,e){fc.lastIndex=0;var r=fc.exec(t.slice(e,e+4));return r?(n.y=+r[0],e+r[0].length):-1}function Wt(n,t,e){fc.lastIndex=0;var r=fc.exec(t.slice(e,e+2));return r?(n.y=Gt(+r[0]),e+r[0].length):-1}function Jt(n,t,e){return/^[+-]\d{4}$/.test(t=t.slice(e,e+5))?(n.Z=-t,e+5):-1}function Gt(n){return n+(n>68?1900:2e3)}function Kt(n,t,e){fc.lastIndex=0;var r=fc.exec(t.slice(e,e+2));return r?(n.m=r[0]-1,e+r[0].length):-1}function Qt(n,t,e){fc.lastIndex=0;var r=fc.exec(t.slice(e,e+2));return r?(n.d=+r[0],e+r[0].length):-1}function ne(n,t,e){fc.lastIndex=0;var r=fc.exec(t.slice(e,e+3));return r?(n.j=+r[0],e+r[0].length):-1}function te(n,t,e){fc.lastIndex=0;var r=fc.exec(t.slice(e,e+2));return r?(n.H=+r[0],e+r[0].length):-1}function ee(n,t,e){fc.lastIndex=0;var r=fc.exec(t.slice(e,e+2));return r?(n.M=+r[0],e+r[0].length):-1}function re(n,t,e){fc.lastIndex=0;var r=fc.exec(t.slice(e,e+2));return r?(n.S=+r[0],e+r[0].length):-1}function ue(n,t,e){fc.lastIndex=0;var r=fc.exec(t.slice(e,e+3));return r?(n.L=+r[0],e+r[0].length):-1}function ie(n){var t=n.getTimezoneOffset(),e=t>0?"-":"+",r=ga(t)/60|0,u=ga(t)%60;return e+It(r,"0",2)+It(u,"0",2)}function oe(n,t,e){hc.lastIndex=0;var r=hc.exec(t.slice(e,e+1));return r?e+r[0].length:-1}function ae(n){for(var t=n.length,e=-1;++e<t;)n[e][0]=this(n[e][0]);return function(t){for(var e=0,r=n[e];!r[1](t);)r=n[++e];return r[0](t)}}function ce(){}function le(n,t,e){var r=e.s=n+t,u=r-n,i=r-u;e.t=n-i+(t-u)}function se(n,t){n&&dc.hasOwnProperty(n.type)&&dc[n.type](n,t)}function fe(n,t,e){var r,u=-1,i=n.length-e;for(t.lineStart();++u<i;)r=n[u],t.point(r[0],r[1],r[2]);t.lineEnd()}function he(n,t){var e=-1,r=n.length;for(t.polygonStart();++e<r;)fe(n[e],t,1);t.polygonEnd()}function ge(){function n(n,t){n*=Da,t=t*Da/2+qa/4;var e=n-r,o=e>=0?1:-1,a=o*e,c=Math.cos(t),l=Math.sin(t),s=i*l,f=u*c+s*Math.cos(a),h=s*o*Math.sin(a);yc.add(Math.atan2(h,f)),r=n,u=c,i=l}var t,e,r,u,i;Mc.point=function(o,a){Mc.point=n,r=(t=o)*Da,u=Math.cos(a=(e=a)*Da/2+qa/4),i=Math.sin(a)},Mc.lineEnd=function(){n(t,e)}}function pe(n){var t=n[0],e=n[1],r=Math.cos(e);return[r*Math.cos(t),r*Math.sin(t),Math.sin(e)]}function ve(n,t){return n[0]*t[0]+n[1]*t[1]+n[2]*t[2]}function de(n,t){return[n[1]*t[2]-n[2]*t[1],n[2]*t[0]-n[0]*t[2],n[0]*t[1]-n[1]*t[0]]}function me(n,t){n[0]+=t[0],n[1]+=t[1],n[2]+=t[2]}function ye(n,t){return[n[0]*t,n[1]*t,n[2]*t]}function Me(n){var t=Math.sqrt(n[0]*n[0]+n[1]*n[1]+n[2]*n[2]);n[0]/=t,n[1]/=t,n[2]/=t}function xe(n){return[Math.atan2(n[1],n[0]),tt(n[2])]}function be(n,t){return ga(n[0]-t[0])<Ca&&ga(n[1]-t[1])<Ca}function _e(n,t){n*=Da;var e=Math.cos(t*=Da);we(e*Math.cos(n),e*Math.sin(n),Math.sin(t))}function we(n,t,e){++xc,_c+=(n-_c)/xc,wc+=(t-wc)/xc,Sc+=(e-Sc)/xc}function Se(){function n(n,u){n*=Da;var i=Math.cos(u*=Da),o=i*Math.cos(n),a=i*Math.sin(n),c=Math.sin(u),l=Math.atan2(Math.sqrt((l=e*c-r*a)*l+(l=r*o-t*c)*l+(l=t*a-e*o)*l),t*o+e*a+r*c);bc+=l,kc+=l*(t+(t=o)),Ec+=l*(e+(e=a)),Ac+=l*(r+(r=c)),we(t,e,r)}var t,e,r;qc.point=function(u,i){u*=Da;var o=Math.cos(i*=Da);t=o*Math.cos(u),e=o*Math.sin(u),r=Math.sin(i),qc.point=n,we(t,e,r)}}function ke(){qc.point=_e}function Ee(){function n(n,t){n*=Da;var e=Math.cos(t*=Da),o=e*Math.cos(n),a=e*Math.sin(n),c=Math.sin(t),l=u*c-i*a,s=i*o-r*c,f=r*a-u*o,h=Math.sqrt(l*l+s*s+f*f),g=r*o+u*a+i*c,p=h&&-nt(g)/h,v=Math.atan2(h,g);Nc+=p*l,Cc+=p*s,zc+=p*f,bc+=v,kc+=v*(r+(r=o)),Ec+=v*(u+(u=a)),Ac+=v*(i+(i=c)),we(r,u,i)}var t,e,r,u,i;qc.point=function(o,a){t=o,e=a,qc.point=n,o*=Da;var c=Math.cos(a*=Da);r=c*Math.cos(o),u=c*Math.sin(o),i=Math.sin(a),we(r,u,i)},qc.lineEnd=function(){n(t,e),qc.lineEnd=ke,qc.point=_e}}function Ae(n,t){function e(e,r){return e=n(e,r),t(e[0],e[1])}return n.invert&&t.invert&&(e.invert=function(e,r){return e=t.invert(e,r),e&&n.invert(e[0],e[1])}),e}function Ne(){return!0}function Ce(n,t,e,r,u){var i=[],o=[];if(n.forEach(function(n){if(!((t=n.length-1)<=0)){var t,e=n[0],r=n[t];if(be(e,r)){u.lineStart();for(var a=0;t>a;++a)u.point((e=n[a])[0],e[1]);return void u.lineEnd()}var c=new qe(e,n,null,!0),l=new qe(e,null,c,!1);c.o=l,i.push(c),o.push(l),c=new qe(r,n,null,!1),l=new qe(r,null,c,!0),c.o=l,i.push(c),o.push(l)}}),o.sort(t),ze(i),ze(o),i.length){for(var a=0,c=e,l=o.length;l>a;++a)o[a].e=c=!c;for(var s,f,h=i[0];;){for(var g=h,p=!0;g.v;)if((g=g.n)===h)return;s=g.z,u.lineStart();do{if(g.v=g.o.v=!0,g.e){if(p)for(var a=0,l=s.length;l>a;++a)u.point((f=s[a])[0],f[1]);else r(g.x,g.n.x,1,u);g=g.n}else{if(p){s=g.p.z;for(var a=s.length-1;a>=0;--a)u.point((f=s[a])[0],f[1])}else r(g.x,g.p.x,-1,u);g=g.p}g=g.o,s=g.z,p=!p}while(!g.v);u.lineEnd()}}}function ze(n){if(t=n.length){for(var t,e,r=0,u=n[0];++r<t;)u.n=e=n[r],e.p=u,u=e;u.n=e=n[0],e.p=u}}function qe(n,t,e,r){this.x=n,this.z=t,this.o=e,this.e=r,this.v=!1,this.n=this.p=null}function Le(n,t,e,r){return function(u,i){function o(t,e){var r=u(t,e);n(t=r[0],e=r[1])&&i.point(t,e)}function a(n,t){var e=u(n,t);d.point(e[0],e[1])}function c(){y.point=a,d.lineStart()}function l(){y.point=o,d.lineEnd()}function s(n,t){v.push([n,t]);var e=u(n,t);x.point(e[0],e[1])}function f(){x.lineStart(),v=[]}function h(){s(v[0][0],v[0][1]),x.lineEnd();var n,t=x.clean(),e=M.buffer(),r=e.length;if(v.pop(),p.push(v),v=null,r)if(1&t){n=e[0];var u,r=n.length-1,o=-1;if(r>0){for(b||(i.polygonStart(),b=!0),i.lineStart();++o<r;)i.point((u=n[o])[0],u[1]);i.lineEnd()}}else r>1&&2&t&&e.push(e.pop().concat(e.shift())),g.push(e.filter(Te))}var g,p,v,d=t(i),m=u.invert(r[0],r[1]),y={point:o,lineStart:c,lineEnd:l,polygonStart:function(){y.point=s,y.lineStart=f,y.lineEnd=h,g=[],p=[]},polygonEnd:function(){y.point=o,y.lineStart=c,y.lineEnd=l,g=ta.merge(g);var n=Fe(m,p);g.length?(b||(i.polygonStart(),b=!0),Ce(g,De,n,e,i)):n&&(b||(i.polygonStart(),b=!0),i.lineStart(),e(null,null,1,i),i.lineEnd()),b&&(i.polygonEnd(),b=!1),g=p=null},sphere:function(){i.polygonStart(),i.lineStart(),e(null,null,1,i),i.lineEnd(),i.polygonEnd()}},M=Re(),x=t(M),b=!1;return y}}function Te(n){return n.length>1}function Re(){var n,t=[];return{lineStart:function(){t.push(n=[])},point:function(t,e){n.push([t,e])},lineEnd:b,buffer:function(){var e=t;return t=[],n=null,e},rejoin:function(){t.length>1&&t.push(t.pop().concat(t.shift()))}}}function De(n,t){return((n=n.x)[0]<0?n[1]-Ra-Ca:Ra-n[1])-((t=t.x)[0]<0?t[1]-Ra-Ca:Ra-t[1])}function Pe(n){var t,e=0/0,r=0/0,u=0/0;return{lineStart:function(){n.lineStart(),t=1},point:function(i,o){var a=i>0?qa:-qa,c=ga(i-e);ga(c-qa)<Ca?(n.point(e,r=(r+o)/2>0?Ra:-Ra),n.point(u,r),n.lineEnd(),n.lineStart(),n.point(a,r),n.point(i,r),t=0):u!==a&&c>=qa&&(ga(e-u)<Ca&&(e-=u*Ca),ga(i-a)<Ca&&(i-=a*Ca),r=Ue(e,r,i,o),n.point(u,r),n.lineEnd(),n.lineStart(),n.point(a,r),t=0),n.point(e=i,r=o),u=a},lineEnd:function(){n.lineEnd(),e=r=0/0},clean:function(){return 2-t}}}function Ue(n,t,e,r){var u,i,o=Math.sin(n-e);return ga(o)>Ca?Math.atan((Math.sin(t)*(i=Math.cos(r))*Math.sin(e)-Math.sin(r)*(u=Math.cos(t))*Math.sin(n))/(u*i*o)):(t+r)/2}function je(n,t,e,r){var u;if(null==n)u=e*Ra,r.point(-qa,u),r.point(0,u),r.point(qa,u),r.point(qa,0),r.point(qa,-u),r.point(0,-u),r.point(-qa,-u),r.point(-qa,0),r.point(-qa,u);else if(ga(n[0]-t[0])>Ca){var i=n[0]<t[0]?qa:-qa;u=e*i/2,r.point(-i,u),r.point(0,u),r.point(i,u)}else r.point(t[0],t[1])}function Fe(n,t){var e=n[0],r=n[1],u=[Math.sin(e),-Math.cos(e),0],i=0,o=0;yc.reset();for(var a=0,c=t.length;c>a;++a){var l=t[a],s=l.length;if(s)for(var f=l[0],h=f[0],g=f[1]/2+qa/4,p=Math.sin(g),v=Math.cos(g),d=1;;){d===s&&(d=0),n=l[d];var m=n[0],y=n[1]/2+qa/4,M=Math.sin(y),x=Math.cos(y),b=m-h,_=b>=0?1:-1,w=_*b,S=w>qa,k=p*M;if(yc.add(Math.atan2(k*_*Math.sin(w),v*x+k*Math.cos(w))),i+=S?b+_*La:b,S^h>=e^m>=e){var E=de(pe(f),pe(n));Me(E);var A=de(u,E);Me(A);var N=(S^b>=0?-1:1)*tt(A[2]);(r>N||r===N&&(E[0]||E[1]))&&(o+=S^b>=0?1:-1)}if(!d++)break;h=m,p=M,v=x,f=n}}return(-Ca>i||Ca>i&&0>yc)^1&o}function He(n){function t(n,t){return Math.cos(n)*Math.cos(t)>i}function e(n){var e,i,c,l,s;return{lineStart:function(){l=c=!1,s=1},point:function(f,h){var g,p=[f,h],v=t(f,h),d=o?v?0:u(f,h):v?u(f+(0>f?qa:-qa),h):0;if(!e&&(l=c=v)&&n.lineStart(),v!==c&&(g=r(e,p),(be(e,g)||be(p,g))&&(p[0]+=Ca,p[1]+=Ca,v=t(p[0],p[1]))),v!==c)s=0,v?(n.lineStart(),g=r(p,e),n.point(g[0],g[1])):(g=r(e,p),n.point(g[0],g[1]),n.lineEnd()),e=g;else if(a&&e&&o^v){var m;d&i||!(m=r(p,e,!0))||(s=0,o?(n.lineStart(),n.point(m[0][0],m[0][1]),n.point(m[1][0],m[1][1]),n.lineEnd()):(n.point(m[1][0],m[1][1]),n.lineEnd(),n.lineStart(),n.point(m[0][0],m[0][1])))}!v||e&&be(e,p)||n.point(p[0],p[1]),e=p,c=v,i=d},lineEnd:function(){c&&n.lineEnd(),e=null},clean:function(){return s|(l&&c)<<1}}}function r(n,t,e){var r=pe(n),u=pe(t),o=[1,0,0],a=de(r,u),c=ve(a,a),l=a[0],s=c-l*l;if(!s)return!e&&n;var f=i*c/s,h=-i*l/s,g=de(o,a),p=ye(o,f),v=ye(a,h);me(p,v);var d=g,m=ve(p,d),y=ve(d,d),M=m*m-y*(ve(p,p)-1);if(!(0>M)){var x=Math.sqrt(M),b=ye(d,(-m-x)/y);if(me(b,p),b=xe(b),!e)return b;var _,w=n[0],S=t[0],k=n[1],E=t[1];w>S&&(_=w,w=S,S=_);var A=S-w,N=ga(A-qa)<Ca,C=N||Ca>A;if(!N&&k>E&&(_=k,k=E,E=_),C?N?k+E>0^b[1]<(ga(b[0]-w)<Ca?k:E):k<=b[1]&&b[1]<=E:A>qa^(w<=b[0]&&b[0]<=S)){var z=ye(d,(-m+x)/y);return me(z,p),[b,xe(z)]}}}function u(t,e){var r=o?n:qa-n,u=0;return-r>t?u|=1:t>r&&(u|=2),-r>e?u|=4:e>r&&(u|=8),u}var i=Math.cos(n),o=i>0,a=ga(i)>Ca,c=gr(n,6*Da);return Le(t,e,c,o?[0,-n]:[-qa,n-qa])}function Oe(n,t,e,r){return function(u){var i,o=u.a,a=u.b,c=o.x,l=o.y,s=a.x,f=a.y,h=0,g=1,p=s-c,v=f-l;if(i=n-c,p||!(i>0)){if(i/=p,0>p){if(h>i)return;g>i&&(g=i)}else if(p>0){if(i>g)return;i>h&&(h=i)}if(i=e-c,p||!(0>i)){if(i/=p,0>p){if(i>g)return;i>h&&(h=i)}else if(p>0){if(h>i)return;g>i&&(g=i)}if(i=t-l,v||!(i>0)){if(i/=v,0>v){if(h>i)return;g>i&&(g=i)}else if(v>0){if(i>g)return;i>h&&(h=i)}if(i=r-l,v||!(0>i)){if(i/=v,0>v){if(i>g)return;i>h&&(h=i)}else if(v>0){if(h>i)return;g>i&&(g=i)}return h>0&&(u.a={x:c+h*p,y:l+h*v}),1>g&&(u.b={x:c+g*p,y:l+g*v}),u}}}}}}function Ie(n,t,e,r){function u(r,u){return ga(r[0]-n)<Ca?u>0?0:3:ga(r[0]-e)<Ca?u>0?2:1:ga(r[1]-t)<Ca?u>0?1:0:u>0?3:2}function i(n,t){return o(n.x,t.x)}function o(n,t){var e=u(n,1),r=u(t,1);return e!==r?e-r:0===e?t[1]-n[1]:1===e?n[0]-t[0]:2===e?n[1]-t[1]:t[0]-n[0]}return function(a){function c(n){for(var t=0,e=d.length,r=n[1],u=0;e>u;++u)for(var i,o=1,a=d[u],c=a.length,l=a[0];c>o;++o)i=a[o],l[1]<=r?i[1]>r&&Q(l,i,n)>0&&++t:i[1]<=r&&Q(l,i,n)<0&&--t,l=i;return 0!==t}function l(i,a,c,l){var s=0,f=0;if(null==i||(s=u(i,c))!==(f=u(a,c))||o(i,a)<0^c>0){do l.point(0===s||3===s?n:e,s>1?r:t);while((s=(s+c+4)%4)!==f)}else l.point(a[0],a[1])}function s(u,i){return u>=n&&e>=u&&i>=t&&r>=i}function f(n,t){s(n,t)&&a.point(n,t)}function h(){C.point=p,d&&d.push(m=[]),S=!0,w=!1,b=_=0/0}function g(){v&&(p(y,M),x&&w&&A.rejoin(),v.push(A.buffer())),C.point=f,w&&a.lineEnd()}function p(n,t){n=Math.max(-Tc,Math.min(Tc,n)),t=Math.max(-Tc,Math.min(Tc,t));var e=s(n,t);if(d&&m.push([n,t]),S)y=n,M=t,x=e,S=!1,e&&(a.lineStart(),a.point(n,t));else if(e&&w)a.point(n,t);else{var r={a:{x:b,y:_},b:{x:n,y:t}};N(r)?(w||(a.lineStart(),a.point(r.a.x,r.a.y)),a.point(r.b.x,r.b.y),e||a.lineEnd(),k=!1):e&&(a.lineStart(),a.point(n,t),k=!1)}b=n,_=t,w=e}var v,d,m,y,M,x,b,_,w,S,k,E=a,A=Re(),N=Oe(n,t,e,r),C={point:f,lineStart:h,lineEnd:g,polygonStart:function(){a=A,v=[],d=[],k=!0},polygonEnd:function(){a=E,v=ta.merge(v);var t=c([n,r]),e=k&&t,u=v.length;(e||u)&&(a.polygonStart(),e&&(a.lineStart(),l(null,null,1,a),a.lineEnd()),u&&Ce(v,i,t,l,a),a.polygonEnd()),v=d=m=null}};return C}}function Ye(n){var t=0,e=qa/3,r=ir(n),u=r(t,e);return u.parallels=function(n){return arguments.length?r(t=n[0]*qa/180,e=n[1]*qa/180):[t/qa*180,e/qa*180]},u}function Ze(n,t){function e(n,t){var e=Math.sqrt(i-2*u*Math.sin(t))/u;return[e*Math.sin(n*=u),o-e*Math.cos(n)]}var r=Math.sin(n),u=(r+Math.sin(t))/2,i=1+r*(2*u-r),o=Math.sqrt(i)/u;return e.invert=function(n,t){var e=o-t;return[Math.atan2(n,e)/u,tt((i-(n*n+e*e)*u*u)/(2*u))]},e}function Ve(){function n(n,t){Dc+=u*n-r*t,r=n,u=t}var t,e,r,u;Hc.point=function(i,o){Hc.point=n,t=r=i,e=u=o},Hc.lineEnd=function(){n(t,e)}}function Xe(n,t){Pc>n&&(Pc=n),n>jc&&(jc=n),Uc>t&&(Uc=t),t>Fc&&(Fc=t)}function $e(){function n(n,t){o.push("M",n,",",t,i)}function t(n,t){o.push("M",n,",",t),a.point=e}function e(n,t){o.push("L",n,",",t)}function r(){a.point=n}function u(){o.push("Z")}var i=Be(4.5),o=[],a={point:n,lineStart:function(){a.point=t},lineEnd:r,polygonStart:function(){a.lineEnd=u},polygonEnd:function(){a.lineEnd=r,a.point=n},pointRadius:function(n){return i=Be(n),a},result:function(){if(o.length){var n=o.join("");return o=[],n}}};return a}function Be(n){return"m0,"+n+"a"+n+","+n+" 0 1,1 0,"+-2*n+"a"+n+","+n+" 0 1,1 0,"+2*n+"z"}function We(n,t){_c+=n,wc+=t,++Sc}function Je(){function n(n,r){var u=n-t,i=r-e,o=Math.sqrt(u*u+i*i);kc+=o*(t+n)/2,Ec+=o*(e+r)/2,Ac+=o,We(t=n,e=r)}var t,e;Ic.point=function(r,u){Ic.point=n,We(t=r,e=u)}}function Ge(){Ic.point=We}function Ke(){function n(n,t){var e=n-r,i=t-u,o=Math.sqrt(e*e+i*i);kc+=o*(r+n)/2,Ec+=o*(u+t)/2,Ac+=o,o=u*n-r*t,Nc+=o*(r+n),Cc+=o*(u+t),zc+=3*o,We(r=n,u=t)}var t,e,r,u;Ic.point=function(i,o){Ic.point=n,We(t=r=i,e=u=o)},Ic.lineEnd=function(){n(t,e)}}function Qe(n){function t(t,e){n.moveTo(t+o,e),n.arc(t,e,o,0,La)}function e(t,e){n.moveTo(t,e),a.point=r}function r(t,e){n.lineTo(t,e)}function u(){a.point=t}function i(){n.closePath()}var o=4.5,a={point:t,lineStart:function(){a.point=e},lineEnd:u,polygonStart:function(){a.lineEnd=i},polygonEnd:function(){a.lineEnd=u,a.point=t},pointRadius:function(n){return o=n,a},result:b};return a}function nr(n){function t(n){return(a?r:e)(n)}function e(t){return rr(t,function(e,r){e=n(e,r),t.point(e[0],e[1])})}function r(t){function e(e,r){e=n(e,r),t.point(e[0],e[1])}function r(){M=0/0,S.point=i,t.lineStart()}function i(e,r){var i=pe([e,r]),o=n(e,r);u(M,x,y,b,_,w,M=o[0],x=o[1],y=e,b=i[0],_=i[1],w=i[2],a,t),t.point(M,x)}function o(){S.point=e,t.lineEnd()}function c(){r(),S.point=l,S.lineEnd=s}function l(n,t){i(f=n,h=t),g=M,p=x,v=b,d=_,m=w,S.point=i}function s(){u(M,x,y,b,_,w,g,p,f,v,d,m,a,t),S.lineEnd=o,o()}var f,h,g,p,v,d,m,y,M,x,b,_,w,S={point:e,lineStart:r,lineEnd:o,polygonStart:function(){t.polygonStart(),S.lineStart=c
  },polygonEnd:function(){t.polygonEnd(),S.lineStart=r}};return S}function u(t,e,r,a,c,l,s,f,h,g,p,v,d,m){var y=s-t,M=f-e,x=y*y+M*M;if(x>4*i&&d--){var b=a+g,_=c+p,w=l+v,S=Math.sqrt(b*b+_*_+w*w),k=Math.asin(w/=S),E=ga(ga(w)-1)<Ca||ga(r-h)<Ca?(r+h)/2:Math.atan2(_,b),A=n(E,k),N=A[0],C=A[1],z=N-t,q=C-e,L=M*z-y*q;(L*L/x>i||ga((y*z+M*q)/x-.5)>.3||o>a*g+c*p+l*v)&&(u(t,e,r,a,c,l,N,C,E,b/=S,_/=S,w,d,m),m.point(N,C),u(N,C,E,b,_,w,s,f,h,g,p,v,d,m))}}var i=.5,o=Math.cos(30*Da),a=16;return t.precision=function(n){return arguments.length?(a=(i=n*n)>0&&16,t):Math.sqrt(i)},t}function tr(n){var t=nr(function(t,e){return n([t*Pa,e*Pa])});return function(n){return or(t(n))}}function er(n){this.stream=n}function rr(n,t){return{point:t,sphere:function(){n.sphere()},lineStart:function(){n.lineStart()},lineEnd:function(){n.lineEnd()},polygonStart:function(){n.polygonStart()},polygonEnd:function(){n.polygonEnd()}}}function ur(n){return ir(function(){return n})()}function ir(n){function t(n){return n=a(n[0]*Da,n[1]*Da),[n[0]*h+c,l-n[1]*h]}function e(n){return n=a.invert((n[0]-c)/h,(l-n[1])/h),n&&[n[0]*Pa,n[1]*Pa]}function r(){a=Ae(o=lr(m,M,x),i);var n=i(v,d);return c=g-n[0]*h,l=p+n[1]*h,u()}function u(){return s&&(s.valid=!1,s=null),t}var i,o,a,c,l,s,f=nr(function(n,t){return n=i(n,t),[n[0]*h+c,l-n[1]*h]}),h=150,g=480,p=250,v=0,d=0,m=0,M=0,x=0,b=Lc,_=y,w=null,S=null;return t.stream=function(n){return s&&(s.valid=!1),s=or(b(o,f(_(n)))),s.valid=!0,s},t.clipAngle=function(n){return arguments.length?(b=null==n?(w=n,Lc):He((w=+n)*Da),u()):w},t.clipExtent=function(n){return arguments.length?(S=n,_=n?Ie(n[0][0],n[0][1],n[1][0],n[1][1]):y,u()):S},t.scale=function(n){return arguments.length?(h=+n,r()):h},t.translate=function(n){return arguments.length?(g=+n[0],p=+n[1],r()):[g,p]},t.center=function(n){return arguments.length?(v=n[0]%360*Da,d=n[1]%360*Da,r()):[v*Pa,d*Pa]},t.rotate=function(n){return arguments.length?(m=n[0]%360*Da,M=n[1]%360*Da,x=n.length>2?n[2]%360*Da:0,r()):[m*Pa,M*Pa,x*Pa]},ta.rebind(t,f,"precision"),function(){return i=n.apply(this,arguments),t.invert=i.invert&&e,r()}}function or(n){return rr(n,function(t,e){n.point(t*Da,e*Da)})}function ar(n,t){return[n,t]}function cr(n,t){return[n>qa?n-La:-qa>n?n+La:n,t]}function lr(n,t,e){return n?t||e?Ae(fr(n),hr(t,e)):fr(n):t||e?hr(t,e):cr}function sr(n){return function(t,e){return t+=n,[t>qa?t-La:-qa>t?t+La:t,e]}}function fr(n){var t=sr(n);return t.invert=sr(-n),t}function hr(n,t){function e(n,t){var e=Math.cos(t),a=Math.cos(n)*e,c=Math.sin(n)*e,l=Math.sin(t),s=l*r+a*u;return[Math.atan2(c*i-s*o,a*r-l*u),tt(s*i+c*o)]}var r=Math.cos(n),u=Math.sin(n),i=Math.cos(t),o=Math.sin(t);return e.invert=function(n,t){var e=Math.cos(t),a=Math.cos(n)*e,c=Math.sin(n)*e,l=Math.sin(t),s=l*i-c*o;return[Math.atan2(c*i+l*o,a*r+s*u),tt(s*r-a*u)]},e}function gr(n,t){var e=Math.cos(n),r=Math.sin(n);return function(u,i,o,a){var c=o*t;null!=u?(u=pr(e,u),i=pr(e,i),(o>0?i>u:u>i)&&(u+=o*La)):(u=n+o*La,i=n-.5*c);for(var l,s=u;o>0?s>i:i>s;s-=c)a.point((l=xe([e,-r*Math.cos(s),-r*Math.sin(s)]))[0],l[1])}}function pr(n,t){var e=pe(t);e[0]-=n,Me(e);var r=nt(-e[1]);return((-e[2]<0?-r:r)+2*Math.PI-Ca)%(2*Math.PI)}function vr(n,t,e){var r=ta.range(n,t-Ca,e).concat(t);return function(n){return r.map(function(t){return[n,t]})}}function dr(n,t,e){var r=ta.range(n,t-Ca,e).concat(t);return function(n){return r.map(function(t){return[t,n]})}}function mr(n){return n.source}function yr(n){return n.target}function Mr(n,t,e,r){var u=Math.cos(t),i=Math.sin(t),o=Math.cos(r),a=Math.sin(r),c=u*Math.cos(n),l=u*Math.sin(n),s=o*Math.cos(e),f=o*Math.sin(e),h=2*Math.asin(Math.sqrt(it(r-t)+u*o*it(e-n))),g=1/Math.sin(h),p=h?function(n){var t=Math.sin(n*=h)*g,e=Math.sin(h-n)*g,r=e*c+t*s,u=e*l+t*f,o=e*i+t*a;return[Math.atan2(u,r)*Pa,Math.atan2(o,Math.sqrt(r*r+u*u))*Pa]}:function(){return[n*Pa,t*Pa]};return p.distance=h,p}function xr(){function n(n,u){var i=Math.sin(u*=Da),o=Math.cos(u),a=ga((n*=Da)-t),c=Math.cos(a);Yc+=Math.atan2(Math.sqrt((a=o*Math.sin(a))*a+(a=r*i-e*o*c)*a),e*i+r*o*c),t=n,e=i,r=o}var t,e,r;Zc.point=function(u,i){t=u*Da,e=Math.sin(i*=Da),r=Math.cos(i),Zc.point=n},Zc.lineEnd=function(){Zc.point=Zc.lineEnd=b}}function br(n,t){function e(t,e){var r=Math.cos(t),u=Math.cos(e),i=n(r*u);return[i*u*Math.sin(t),i*Math.sin(e)]}return e.invert=function(n,e){var r=Math.sqrt(n*n+e*e),u=t(r),i=Math.sin(u),o=Math.cos(u);return[Math.atan2(n*i,r*o),Math.asin(r&&e*i/r)]},e}function _r(n,t){function e(n,t){o>0?-Ra+Ca>t&&(t=-Ra+Ca):t>Ra-Ca&&(t=Ra-Ca);var e=o/Math.pow(u(t),i);return[e*Math.sin(i*n),o-e*Math.cos(i*n)]}var r=Math.cos(n),u=function(n){return Math.tan(qa/4+n/2)},i=n===t?Math.sin(n):Math.log(r/Math.cos(t))/Math.log(u(t)/u(n)),o=r*Math.pow(u(n),i)/i;return i?(e.invert=function(n,t){var e=o-t,r=K(i)*Math.sqrt(n*n+e*e);return[Math.atan2(n,e)/i,2*Math.atan(Math.pow(o/r,1/i))-Ra]},e):Sr}function wr(n,t){function e(n,t){var e=i-t;return[e*Math.sin(u*n),i-e*Math.cos(u*n)]}var r=Math.cos(n),u=n===t?Math.sin(n):(r-Math.cos(t))/(t-n),i=r/u+n;return ga(u)<Ca?ar:(e.invert=function(n,t){var e=i-t;return[Math.atan2(n,e)/u,i-K(u)*Math.sqrt(n*n+e*e)]},e)}function Sr(n,t){return[n,Math.log(Math.tan(qa/4+t/2))]}function kr(n){var t,e=ur(n),r=e.scale,u=e.translate,i=e.clipExtent;return e.scale=function(){var n=r.apply(e,arguments);return n===e?t?e.clipExtent(null):e:n},e.translate=function(){var n=u.apply(e,arguments);return n===e?t?e.clipExtent(null):e:n},e.clipExtent=function(n){var o=i.apply(e,arguments);if(o===e){if(t=null==n){var a=qa*r(),c=u();i([[c[0]-a,c[1]-a],[c[0]+a,c[1]+a]])}}else t&&(o=null);return o},e.clipExtent(null)}function Er(n,t){return[Math.log(Math.tan(qa/4+t/2)),-n]}function Ar(n){return n[0]}function Nr(n){return n[1]}function Cr(n){for(var t=n.length,e=[0,1],r=2,u=2;t>u;u++){for(;r>1&&Q(n[e[r-2]],n[e[r-1]],n[u])<=0;)--r;e[r++]=u}return e.slice(0,r)}function zr(n,t){return n[0]-t[0]||n[1]-t[1]}function qr(n,t,e){return(e[0]-t[0])*(n[1]-t[1])<(e[1]-t[1])*(n[0]-t[0])}function Lr(n,t,e,r){var u=n[0],i=e[0],o=t[0]-u,a=r[0]-i,c=n[1],l=e[1],s=t[1]-c,f=r[1]-l,h=(a*(c-l)-f*(u-i))/(f*o-a*s);return[u+h*o,c+h*s]}function Tr(n){var t=n[0],e=n[n.length-1];return!(t[0]-e[0]||t[1]-e[1])}function Rr(){tu(this),this.edge=this.site=this.circle=null}function Dr(n){var t=el.pop()||new Rr;return t.site=n,t}function Pr(n){Xr(n),Qc.remove(n),el.push(n),tu(n)}function Ur(n){var t=n.circle,e=t.x,r=t.cy,u={x:e,y:r},i=n.P,o=n.N,a=[n];Pr(n);for(var c=i;c.circle&&ga(e-c.circle.x)<Ca&&ga(r-c.circle.cy)<Ca;)i=c.P,a.unshift(c),Pr(c),c=i;a.unshift(c),Xr(c);for(var l=o;l.circle&&ga(e-l.circle.x)<Ca&&ga(r-l.circle.cy)<Ca;)o=l.N,a.push(l),Pr(l),l=o;a.push(l),Xr(l);var s,f=a.length;for(s=1;f>s;++s)l=a[s],c=a[s-1],Kr(l.edge,c.site,l.site,u);c=a[0],l=a[f-1],l.edge=Jr(c.site,l.site,null,u),Vr(c),Vr(l)}function jr(n){for(var t,e,r,u,i=n.x,o=n.y,a=Qc._;a;)if(r=Fr(a,o)-i,r>Ca)a=a.L;else{if(u=i-Hr(a,o),!(u>Ca)){r>-Ca?(t=a.P,e=a):u>-Ca?(t=a,e=a.N):t=e=a;break}if(!a.R){t=a;break}a=a.R}var c=Dr(n);if(Qc.insert(t,c),t||e){if(t===e)return Xr(t),e=Dr(t.site),Qc.insert(c,e),c.edge=e.edge=Jr(t.site,c.site),Vr(t),void Vr(e);if(!e)return void(c.edge=Jr(t.site,c.site));Xr(t),Xr(e);var l=t.site,s=l.x,f=l.y,h=n.x-s,g=n.y-f,p=e.site,v=p.x-s,d=p.y-f,m=2*(h*d-g*v),y=h*h+g*g,M=v*v+d*d,x={x:(d*y-g*M)/m+s,y:(h*M-v*y)/m+f};Kr(e.edge,l,p,x),c.edge=Jr(l,n,null,x),e.edge=Jr(n,p,null,x),Vr(t),Vr(e)}}function Fr(n,t){var e=n.site,r=e.x,u=e.y,i=u-t;if(!i)return r;var o=n.P;if(!o)return-1/0;e=o.site;var a=e.x,c=e.y,l=c-t;if(!l)return a;var s=a-r,f=1/i-1/l,h=s/l;return f?(-h+Math.sqrt(h*h-2*f*(s*s/(-2*l)-c+l/2+u-i/2)))/f+r:(r+a)/2}function Hr(n,t){var e=n.N;if(e)return Fr(e,t);var r=n.site;return r.y===t?r.x:1/0}function Or(n){this.site=n,this.edges=[]}function Ir(n){for(var t,e,r,u,i,o,a,c,l,s,f=n[0][0],h=n[1][0],g=n[0][1],p=n[1][1],v=Kc,d=v.length;d--;)if(i=v[d],i&&i.prepare())for(a=i.edges,c=a.length,o=0;c>o;)s=a[o].end(),r=s.x,u=s.y,l=a[++o%c].start(),t=l.x,e=l.y,(ga(r-t)>Ca||ga(u-e)>Ca)&&(a.splice(o,0,new Qr(Gr(i.site,s,ga(r-f)<Ca&&p-u>Ca?{x:f,y:ga(t-f)<Ca?e:p}:ga(u-p)<Ca&&h-r>Ca?{x:ga(e-p)<Ca?t:h,y:p}:ga(r-h)<Ca&&u-g>Ca?{x:h,y:ga(t-h)<Ca?e:g}:ga(u-g)<Ca&&r-f>Ca?{x:ga(e-g)<Ca?t:f,y:g}:null),i.site,null)),++c)}function Yr(n,t){return t.angle-n.angle}function Zr(){tu(this),this.x=this.y=this.arc=this.site=this.cy=null}function Vr(n){var t=n.P,e=n.N;if(t&&e){var r=t.site,u=n.site,i=e.site;if(r!==i){var o=u.x,a=u.y,c=r.x-o,l=r.y-a,s=i.x-o,f=i.y-a,h=2*(c*f-l*s);if(!(h>=-za)){var g=c*c+l*l,p=s*s+f*f,v=(f*g-l*p)/h,d=(c*p-s*g)/h,f=d+a,m=rl.pop()||new Zr;m.arc=n,m.site=u,m.x=v+o,m.y=f+Math.sqrt(v*v+d*d),m.cy=f,n.circle=m;for(var y=null,M=tl._;M;)if(m.y<M.y||m.y===M.y&&m.x<=M.x){if(!M.L){y=M.P;break}M=M.L}else{if(!M.R){y=M;break}M=M.R}tl.insert(y,m),y||(nl=m)}}}}function Xr(n){var t=n.circle;t&&(t.P||(nl=t.N),tl.remove(t),rl.push(t),tu(t),n.circle=null)}function $r(n){for(var t,e=Gc,r=Oe(n[0][0],n[0][1],n[1][0],n[1][1]),u=e.length;u--;)t=e[u],(!Br(t,n)||!r(t)||ga(t.a.x-t.b.x)<Ca&&ga(t.a.y-t.b.y)<Ca)&&(t.a=t.b=null,e.splice(u,1))}function Br(n,t){var e=n.b;if(e)return!0;var r,u,i=n.a,o=t[0][0],a=t[1][0],c=t[0][1],l=t[1][1],s=n.l,f=n.r,h=s.x,g=s.y,p=f.x,v=f.y,d=(h+p)/2,m=(g+v)/2;if(v===g){if(o>d||d>=a)return;if(h>p){if(i){if(i.y>=l)return}else i={x:d,y:c};e={x:d,y:l}}else{if(i){if(i.y<c)return}else i={x:d,y:l};e={x:d,y:c}}}else if(r=(h-p)/(v-g),u=m-r*d,-1>r||r>1)if(h>p){if(i){if(i.y>=l)return}else i={x:(c-u)/r,y:c};e={x:(l-u)/r,y:l}}else{if(i){if(i.y<c)return}else i={x:(l-u)/r,y:l};e={x:(c-u)/r,y:c}}else if(v>g){if(i){if(i.x>=a)return}else i={x:o,y:r*o+u};e={x:a,y:r*a+u}}else{if(i){if(i.x<o)return}else i={x:a,y:r*a+u};e={x:o,y:r*o+u}}return n.a=i,n.b=e,!0}function Wr(n,t){this.l=n,this.r=t,this.a=this.b=null}function Jr(n,t,e,r){var u=new Wr(n,t);return Gc.push(u),e&&Kr(u,n,t,e),r&&Kr(u,t,n,r),Kc[n.i].edges.push(new Qr(u,n,t)),Kc[t.i].edges.push(new Qr(u,t,n)),u}function Gr(n,t,e){var r=new Wr(n,null);return r.a=t,r.b=e,Gc.push(r),r}function Kr(n,t,e,r){n.a||n.b?n.l===e?n.b=r:n.a=r:(n.a=r,n.l=t,n.r=e)}function Qr(n,t,e){var r=n.a,u=n.b;this.edge=n,this.site=t,this.angle=e?Math.atan2(e.y-t.y,e.x-t.x):n.l===t?Math.atan2(u.x-r.x,r.y-u.y):Math.atan2(r.x-u.x,u.y-r.y)}function nu(){this._=null}function tu(n){n.U=n.C=n.L=n.R=n.P=n.N=null}function eu(n,t){var e=t,r=t.R,u=e.U;u?u.L===e?u.L=r:u.R=r:n._=r,r.U=u,e.U=r,e.R=r.L,e.R&&(e.R.U=e),r.L=e}function ru(n,t){var e=t,r=t.L,u=e.U;u?u.L===e?u.L=r:u.R=r:n._=r,r.U=u,e.U=r,e.L=r.R,e.L&&(e.L.U=e),r.R=e}function uu(n){for(;n.L;)n=n.L;return n}function iu(n,t){var e,r,u,i=n.sort(ou).pop();for(Gc=[],Kc=new Array(n.length),Qc=new nu,tl=new nu;;)if(u=nl,i&&(!u||i.y<u.y||i.y===u.y&&i.x<u.x))(i.x!==e||i.y!==r)&&(Kc[i.i]=new Or(i),jr(i),e=i.x,r=i.y),i=n.pop();else{if(!u)break;Ur(u.arc)}t&&($r(t),Ir(t));var o={cells:Kc,edges:Gc};return Qc=tl=Gc=Kc=null,o}function ou(n,t){return t.y-n.y||t.x-n.x}function au(n,t,e){return(n.x-e.x)*(t.y-n.y)-(n.x-t.x)*(e.y-n.y)}function cu(n){return n.x}function lu(n){return n.y}function su(){return{leaf:!0,nodes:[],point:null,x:null,y:null}}function fu(n,t,e,r,u,i){if(!n(t,e,r,u,i)){var o=.5*(e+u),a=.5*(r+i),c=t.nodes;c[0]&&fu(n,c[0],e,r,o,a),c[1]&&fu(n,c[1],o,r,u,a),c[2]&&fu(n,c[2],e,a,o,i),c[3]&&fu(n,c[3],o,a,u,i)}}function hu(n,t,e,r,u,i,o){var a,c=1/0;return function l(n,s,f,h,g){if(!(s>i||f>o||r>h||u>g)){if(p=n.point){var p,v=t-n.x,d=e-n.y,m=v*v+d*d;if(c>m){var y=Math.sqrt(c=m);r=t-y,u=e-y,i=t+y,o=e+y,a=p}}for(var M=n.nodes,x=.5*(s+h),b=.5*(f+g),_=t>=x,w=e>=b,S=w<<1|_,k=S+4;k>S;++S)if(n=M[3&S])switch(3&S){case 0:l(n,s,f,x,b);break;case 1:l(n,x,f,h,b);break;case 2:l(n,s,b,x,g);break;case 3:l(n,x,b,h,g)}}}(n,r,u,i,o),a}function gu(n,t){n=ta.rgb(n),t=ta.rgb(t);var e=n.r,r=n.g,u=n.b,i=t.r-e,o=t.g-r,a=t.b-u;return function(n){return"#"+xt(Math.round(e+i*n))+xt(Math.round(r+o*n))+xt(Math.round(u+a*n))}}function pu(n,t){var e,r={},u={};for(e in n)e in t?r[e]=mu(n[e],t[e]):u[e]=n[e];for(e in t)e in n||(u[e]=t[e]);return function(n){for(e in r)u[e]=r[e](n);return u}}function vu(n,t){return n=+n,t=+t,function(e){return n*(1-e)+t*e}}function du(n,t){var e,r,u,i=il.lastIndex=ol.lastIndex=0,o=-1,a=[],c=[];for(n+="",t+="";(e=il.exec(n))&&(r=ol.exec(t));)(u=r.index)>i&&(u=t.slice(i,u),a[o]?a[o]+=u:a[++o]=u),(e=e[0])===(r=r[0])?a[o]?a[o]+=r:a[++o]=r:(a[++o]=null,c.push({i:o,x:vu(e,r)})),i=ol.lastIndex;return i<t.length&&(u=t.slice(i),a[o]?a[o]+=u:a[++o]=u),a.length<2?c[0]?(t=c[0].x,function(n){return t(n)+""}):function(){return t}:(t=c.length,function(n){for(var e,r=0;t>r;++r)a[(e=c[r]).i]=e.x(n);return a.join("")})}function mu(n,t){for(var e,r=ta.interpolators.length;--r>=0&&!(e=ta.interpolators[r](n,t)););return e}function yu(n,t){var e,r=[],u=[],i=n.length,o=t.length,a=Math.min(n.length,t.length);for(e=0;a>e;++e)r.push(mu(n[e],t[e]));for(;i>e;++e)u[e]=n[e];for(;o>e;++e)u[e]=t[e];return function(n){for(e=0;a>e;++e)u[e]=r[e](n);return u}}function Mu(n){return function(t){return 0>=t?0:t>=1?1:n(t)}}function xu(n){return function(t){return 1-n(1-t)}}function bu(n){return function(t){return.5*(.5>t?n(2*t):2-n(2-2*t))}}function _u(n){return n*n}function wu(n){return n*n*n}function Su(n){if(0>=n)return 0;if(n>=1)return 1;var t=n*n,e=t*n;return 4*(.5>n?e:3*(n-t)+e-.75)}function ku(n){return function(t){return Math.pow(t,n)}}function Eu(n){return 1-Math.cos(n*Ra)}function Au(n){return Math.pow(2,10*(n-1))}function Nu(n){return 1-Math.sqrt(1-n*n)}function Cu(n,t){var e;return arguments.length<2&&(t=.45),arguments.length?e=t/La*Math.asin(1/n):(n=1,e=t/4),function(r){return 1+n*Math.pow(2,-10*r)*Math.sin((r-e)*La/t)}}function zu(n){return n||(n=1.70158),function(t){return t*t*((n+1)*t-n)}}function qu(n){return 1/2.75>n?7.5625*n*n:2/2.75>n?7.5625*(n-=1.5/2.75)*n+.75:2.5/2.75>n?7.5625*(n-=2.25/2.75)*n+.9375:7.5625*(n-=2.625/2.75)*n+.984375}function Lu(n,t){n=ta.hcl(n),t=ta.hcl(t);var e=n.h,r=n.c,u=n.l,i=t.h-e,o=t.c-r,a=t.l-u;return isNaN(o)&&(o=0,r=isNaN(r)?t.c:r),isNaN(i)?(i=0,e=isNaN(e)?t.h:e):i>180?i-=360:-180>i&&(i+=360),function(n){return st(e+i*n,r+o*n,u+a*n)+""}}function Tu(n,t){n=ta.hsl(n),t=ta.hsl(t);var e=n.h,r=n.s,u=n.l,i=t.h-e,o=t.s-r,a=t.l-u;return isNaN(o)&&(o=0,r=isNaN(r)?t.s:r),isNaN(i)?(i=0,e=isNaN(e)?t.h:e):i>180?i-=360:-180>i&&(i+=360),function(n){return ct(e+i*n,r+o*n,u+a*n)+""}}function Ru(n,t){n=ta.lab(n),t=ta.lab(t);var e=n.l,r=n.a,u=n.b,i=t.l-e,o=t.a-r,a=t.b-u;return function(n){return ht(e+i*n,r+o*n,u+a*n)+""}}function Du(n,t){return t-=n,function(e){return Math.round(n+t*e)}}function Pu(n){var t=[n.a,n.b],e=[n.c,n.d],r=ju(t),u=Uu(t,e),i=ju(Fu(e,t,-u))||0;t[0]*e[1]<e[0]*t[1]&&(t[0]*=-1,t[1]*=-1,r*=-1,u*=-1),this.rotate=(r?Math.atan2(t[1],t[0]):Math.atan2(-e[0],e[1]))*Pa,this.translate=[n.e,n.f],this.scale=[r,i],this.skew=i?Math.atan2(u,i)*Pa:0}function Uu(n,t){return n[0]*t[0]+n[1]*t[1]}function ju(n){var t=Math.sqrt(Uu(n,n));return t&&(n[0]/=t,n[1]/=t),t}function Fu(n,t,e){return n[0]+=e*t[0],n[1]+=e*t[1],n}function Hu(n,t){var e,r=[],u=[],i=ta.transform(n),o=ta.transform(t),a=i.translate,c=o.translate,l=i.rotate,s=o.rotate,f=i.skew,h=o.skew,g=i.scale,p=o.scale;return a[0]!=c[0]||a[1]!=c[1]?(r.push("translate(",null,",",null,")"),u.push({i:1,x:vu(a[0],c[0])},{i:3,x:vu(a[1],c[1])})):r.push(c[0]||c[1]?"translate("+c+")":""),l!=s?(l-s>180?s+=360:s-l>180&&(l+=360),u.push({i:r.push(r.pop()+"rotate(",null,")")-2,x:vu(l,s)})):s&&r.push(r.pop()+"rotate("+s+")"),f!=h?u.push({i:r.push(r.pop()+"skewX(",null,")")-2,x:vu(f,h)}):h&&r.push(r.pop()+"skewX("+h+")"),g[0]!=p[0]||g[1]!=p[1]?(e=r.push(r.pop()+"scale(",null,",",null,")"),u.push({i:e-4,x:vu(g[0],p[0])},{i:e-2,x:vu(g[1],p[1])})):(1!=p[0]||1!=p[1])&&r.push(r.pop()+"scale("+p+")"),e=u.length,function(n){for(var t,i=-1;++i<e;)r[(t=u[i]).i]=t.x(n);return r.join("")}}function Ou(n,t){return t=(t-=n=+n)||1/t,function(e){return(e-n)/t}}function Iu(n,t){return t=(t-=n=+n)||1/t,function(e){return Math.max(0,Math.min(1,(e-n)/t))}}function Yu(n){for(var t=n.source,e=n.target,r=Vu(t,e),u=[t];t!==r;)t=t.parent,u.push(t);for(var i=u.length;e!==r;)u.splice(i,0,e),e=e.parent;return u}function Zu(n){for(var t=[],e=n.parent;null!=e;)t.push(n),n=e,e=e.parent;return t.push(n),t}function Vu(n,t){if(n===t)return n;for(var e=Zu(n),r=Zu(t),u=e.pop(),i=r.pop(),o=null;u===i;)o=u,u=e.pop(),i=r.pop();return o}function Xu(n){n.fixed|=2}function $u(n){n.fixed&=-7}function Bu(n){n.fixed|=4,n.px=n.x,n.py=n.y}function Wu(n){n.fixed&=-5}function Ju(n,t,e){var r=0,u=0;if(n.charge=0,!n.leaf)for(var i,o=n.nodes,a=o.length,c=-1;++c<a;)i=o[c],null!=i&&(Ju(i,t,e),n.charge+=i.charge,r+=i.charge*i.cx,u+=i.charge*i.cy);if(n.point){n.leaf||(n.point.x+=Math.random()-.5,n.point.y+=Math.random()-.5);var l=t*e[n.point.index];n.charge+=n.pointCharge=l,r+=l*n.point.x,u+=l*n.point.y}n.cx=r/n.charge,n.cy=u/n.charge}function Gu(n,t){return ta.rebind(n,t,"sort","children","value"),n.nodes=n,n.links=ri,n}function Ku(n,t){for(var e=[n];null!=(n=e.pop());)if(t(n),(u=n.children)&&(r=u.length))for(var r,u;--r>=0;)e.push(u[r])}function Qu(n,t){for(var e=[n],r=[];null!=(n=e.pop());)if(r.push(n),(i=n.children)&&(u=i.length))for(var u,i,o=-1;++o<u;)e.push(i[o]);for(;null!=(n=r.pop());)t(n)}function ni(n){return n.children}function ti(n){return n.value}function ei(n,t){return t.value-n.value}function ri(n){return ta.merge(n.map(function(n){return(n.children||[]).map(function(t){return{source:n,target:t}})}))}function ui(n){return n.x}function ii(n){return n.y}function oi(n,t,e){n.y0=t,n.y=e}function ai(n){return ta.range(n.length)}function ci(n){for(var t=-1,e=n[0].length,r=[];++t<e;)r[t]=0;return r}function li(n){for(var t,e=1,r=0,u=n[0][1],i=n.length;i>e;++e)(t=n[e][1])>u&&(r=e,u=t);return r}function si(n){return n.reduce(fi,0)}function fi(n,t){return n+t[1]}function hi(n,t){return gi(n,Math.ceil(Math.log(t.length)/Math.LN2+1))}function gi(n,t){for(var e=-1,r=+n[0],u=(n[1]-r)/t,i=[];++e<=t;)i[e]=u*e+r;return i}function pi(n){return[ta.min(n),ta.max(n)]}function vi(n,t){return n.value-t.value}function di(n,t){var e=n._pack_next;n._pack_next=t,t._pack_prev=n,t._pack_next=e,e._pack_prev=t}function mi(n,t){n._pack_next=t,t._pack_prev=n}function yi(n,t){var e=t.x-n.x,r=t.y-n.y,u=n.r+t.r;return.999*u*u>e*e+r*r}function Mi(n){function t(n){s=Math.min(n.x-n.r,s),f=Math.max(n.x+n.r,f),h=Math.min(n.y-n.r,h),g=Math.max(n.y+n.r,g)}if((e=n.children)&&(l=e.length)){var e,r,u,i,o,a,c,l,s=1/0,f=-1/0,h=1/0,g=-1/0;if(e.forEach(xi),r=e[0],r.x=-r.r,r.y=0,t(r),l>1&&(u=e[1],u.x=u.r,u.y=0,t(u),l>2))for(i=e[2],wi(r,u,i),t(i),di(r,i),r._pack_prev=i,di(i,u),u=r._pack_next,o=3;l>o;o++){wi(r,u,i=e[o]);var p=0,v=1,d=1;for(a=u._pack_next;a!==u;a=a._pack_next,v++)if(yi(a,i)){p=1;break}if(1==p)for(c=r._pack_prev;c!==a._pack_prev&&!yi(c,i);c=c._pack_prev,d++);p?(d>v||v==d&&u.r<r.r?mi(r,u=a):mi(r=c,u),o--):(di(r,i),u=i,t(i))}var m=(s+f)/2,y=(h+g)/2,M=0;for(o=0;l>o;o++)i=e[o],i.x-=m,i.y-=y,M=Math.max(M,i.r+Math.sqrt(i.x*i.x+i.y*i.y));n.r=M,e.forEach(bi)}}function xi(n){n._pack_next=n._pack_prev=n}function bi(n){delete n._pack_next,delete n._pack_prev}function _i(n,t,e,r){var u=n.children;if(n.x=t+=r*n.x,n.y=e+=r*n.y,n.r*=r,u)for(var i=-1,o=u.length;++i<o;)_i(u[i],t,e,r)}function wi(n,t,e){var r=n.r+e.r,u=t.x-n.x,i=t.y-n.y;if(r&&(u||i)){var o=t.r+e.r,a=u*u+i*i;o*=o,r*=r;var c=.5+(r-o)/(2*a),l=Math.sqrt(Math.max(0,2*o*(r+a)-(r-=a)*r-o*o))/(2*a);e.x=n.x+c*u+l*i,e.y=n.y+c*i-l*u}else e.x=n.x+r,e.y=n.y}function Si(n,t){return n.parent==t.parent?1:2}function ki(n){var t=n.children;return t.length?t[0]:n.t}function Ei(n){var t,e=n.children;return(t=e.length)?e[t-1]:n.t}function Ai(n,t,e){var r=e/(t.i-n.i);t.c-=r,t.s+=e,n.c+=r,t.z+=e,t.m+=e}function Ni(n){for(var t,e=0,r=0,u=n.children,i=u.length;--i>=0;)t=u[i],t.z+=e,t.m+=e,e+=t.s+(r+=t.c)}function Ci(n,t,e){return n.a.parent===t.parent?n.a:e}function zi(n){return 1+ta.max(n,function(n){return n.y})}function qi(n){return n.reduce(function(n,t){return n+t.x},0)/n.length}function Li(n){var t=n.children;return t&&t.length?Li(t[0]):n}function Ti(n){var t,e=n.children;return e&&(t=e.length)?Ti(e[t-1]):n}function Ri(n){return{x:n.x,y:n.y,dx:n.dx,dy:n.dy}}function Di(n,t){var e=n.x+t[3],r=n.y+t[0],u=n.dx-t[1]-t[3],i=n.dy-t[0]-t[2];return 0>u&&(e+=u/2,u=0),0>i&&(r+=i/2,i=0),{x:e,y:r,dx:u,dy:i}}function Pi(n){var t=n[0],e=n[n.length-1];return e>t?[t,e]:[e,t]}function Ui(n){return n.rangeExtent?n.rangeExtent():Pi(n.range())}function ji(n,t,e,r){var u=e(n[0],n[1]),i=r(t[0],t[1]);return function(n){return i(u(n))}}function Fi(n,t){var e,r=0,u=n.length-1,i=n[r],o=n[u];return i>o&&(e=r,r=u,u=e,e=i,i=o,o=e),n[r]=t.floor(i),n[u]=t.ceil(o),n}function Hi(n){return n?{floor:function(t){return Math.floor(t/n)*n},ceil:function(t){return Math.ceil(t/n)*n}}:ml}function Oi(n,t,e,r){var u=[],i=[],o=0,a=Math.min(n.length,t.length)-1;for(n[a]<n[0]&&(n=n.slice().reverse(),t=t.slice().reverse());++o<=a;)u.push(e(n[o-1],n[o])),i.push(r(t[o-1],t[o]));return function(t){var e=ta.bisect(n,t,1,a)-1;return i[e](u[e](t))}}function Ii(n,t,e,r){function u(){var u=Math.min(n.length,t.length)>2?Oi:ji,c=r?Iu:Ou;return o=u(n,t,c,e),a=u(t,n,c,mu),i}function i(n){return o(n)}var o,a;return i.invert=function(n){return a(n)},i.domain=function(t){return arguments.length?(n=t.map(Number),u()):n},i.range=function(n){return arguments.length?(t=n,u()):t},i.rangeRound=function(n){return i.range(n).interpolate(Du)},i.clamp=function(n){return arguments.length?(r=n,u()):r},i.interpolate=function(n){return arguments.length?(e=n,u()):e},i.ticks=function(t){return Xi(n,t)},i.tickFormat=function(t,e){return $i(n,t,e)},i.nice=function(t){return Zi(n,t),u()},i.copy=function(){return Ii(n,t,e,r)},u()}function Yi(n,t){return ta.rebind(n,t,"range","rangeRound","interpolate","clamp")}function Zi(n,t){return Fi(n,Hi(Vi(n,t)[2]))}function Vi(n,t){null==t&&(t=10);var e=Pi(n),r=e[1]-e[0],u=Math.pow(10,Math.floor(Math.log(r/t)/Math.LN10)),i=t/r*u;return.15>=i?u*=10:.35>=i?u*=5:.75>=i&&(u*=2),e[0]=Math.ceil(e[0]/u)*u,e[1]=Math.floor(e[1]/u)*u+.5*u,e[2]=u,e}function Xi(n,t){return ta.range.apply(ta,Vi(n,t))}function $i(n,t,e){var r=Vi(n,t);if(e){var u=ic.exec(e);if(u.shift(),"s"===u[8]){var i=ta.formatPrefix(Math.max(ga(r[0]),ga(r[1])));return u[7]||(u[7]="."+Bi(i.scale(r[2]))),u[8]="f",e=ta.format(u.join("")),function(n){return e(i.scale(n))+i.symbol}}u[7]||(u[7]="."+Wi(u[8],r)),e=u.join("")}else e=",."+Bi(r[2])+"f";return ta.format(e)}function Bi(n){return-Math.floor(Math.log(n)/Math.LN10+.01)}function Wi(n,t){var e=Bi(t[2]);return n in yl?Math.abs(e-Bi(Math.max(ga(t[0]),ga(t[1]))))+ +("e"!==n):e-2*("%"===n)}function Ji(n,t,e,r){function u(n){return(e?Math.log(0>n?0:n):-Math.log(n>0?0:-n))/Math.log(t)}function i(n){return e?Math.pow(t,n):-Math.pow(t,-n)}function o(t){return n(u(t))}return o.invert=function(t){return i(n.invert(t))},o.domain=function(t){return arguments.length?(e=t[0]>=0,n.domain((r=t.map(Number)).map(u)),o):r},o.base=function(e){return arguments.length?(t=+e,n.domain(r.map(u)),o):t},o.nice=function(){var t=Fi(r.map(u),e?Math:xl);return n.domain(t),r=t.map(i),o},o.ticks=function(){var n=Pi(r),o=[],a=n[0],c=n[1],l=Math.floor(u(a)),s=Math.ceil(u(c)),f=t%1?2:t;if(isFinite(s-l)){if(e){for(;s>l;l++)for(var h=1;f>h;h++)o.push(i(l)*h);o.push(i(l))}else for(o.push(i(l));l++<s;)for(var h=f-1;h>0;h--)o.push(i(l)*h);for(l=0;o[l]<a;l++);for(s=o.length;o[s-1]>c;s--);o=o.slice(l,s)}return o},o.tickFormat=function(n,t){if(!arguments.length)return Ml;arguments.length<2?t=Ml:"function"!=typeof t&&(t=ta.format(t));var r,a=Math.max(.1,n/o.ticks().length),c=e?(r=1e-12,Math.ceil):(r=-1e-12,Math.floor);return function(n){return n/i(c(u(n)+r))<=a?t(n):""}},o.copy=function(){return Ji(n.copy(),t,e,r)},Yi(o,n)}function Gi(n,t,e){function r(t){return n(u(t))}var u=Ki(t),i=Ki(1/t);return r.invert=function(t){return i(n.invert(t))},r.domain=function(t){return arguments.length?(n.domain((e=t.map(Number)).map(u)),r):e},r.ticks=function(n){return Xi(e,n)},r.tickFormat=function(n,t){return $i(e,n,t)},r.nice=function(n){return r.domain(Zi(e,n))},r.exponent=function(o){return arguments.length?(u=Ki(t=o),i=Ki(1/t),n.domain(e.map(u)),r):t},r.copy=function(){return Gi(n.copy(),t,e)},Yi(r,n)}function Ki(n){return function(t){return 0>t?-Math.pow(-t,n):Math.pow(t,n)}}function Qi(n,t){function e(e){return i[((u.get(e)||("range"===t.t?u.set(e,n.push(e)):0/0))-1)%i.length]}function r(t,e){return ta.range(n.length).map(function(n){return t+e*n})}var u,i,o;return e.domain=function(r){if(!arguments.length)return n;n=[],u=new l;for(var i,o=-1,a=r.length;++o<a;)u.has(i=r[o])||u.set(i,n.push(i));return e[t.t].apply(e,t.a)},e.range=function(n){return arguments.length?(i=n,o=0,t={t:"range",a:arguments},e):i},e.rangePoints=function(u,a){arguments.length<2&&(a=0);var c=u[0],l=u[1],s=n.length<2?(c=(c+l)/2,0):(l-c)/(n.length-1+a);return i=r(c+s*a/2,s),o=0,t={t:"rangePoints",a:arguments},e},e.rangeRoundPoints=function(u,a){arguments.length<2&&(a=0);var c=u[0],l=u[1],s=n.length<2?(c=l=Math.round((c+l)/2),0):(l-c)/(n.length-1+a)|0;return i=r(c+Math.round(s*a/2+(l-c-(n.length-1+a)*s)/2),s),o=0,t={t:"rangeRoundPoints",a:arguments},e},e.rangeBands=function(u,a,c){arguments.length<2&&(a=0),arguments.length<3&&(c=a);var l=u[1]<u[0],s=u[l-0],f=u[1-l],h=(f-s)/(n.length-a+2*c);return i=r(s+h*c,h),l&&i.reverse(),o=h*(1-a),t={t:"rangeBands",a:arguments},e},e.rangeRoundBands=function(u,a,c){arguments.length<2&&(a=0),arguments.length<3&&(c=a);var l=u[1]<u[0],s=u[l-0],f=u[1-l],h=Math.floor((f-s)/(n.length-a+2*c));return i=r(s+Math.round((f-s-(n.length-a)*h)/2),h),l&&i.reverse(),o=Math.round(h*(1-a)),t={t:"rangeRoundBands",a:arguments},e},e.rangeBand=function(){return o},e.rangeExtent=function(){return Pi(t.a[0])},e.copy=function(){return Qi(n,t)},e.domain(n)}function no(n,t){function i(){var e=0,r=t.length;for(a=[];++e<r;)a[e-1]=ta.quantile(n,e/r);return o}function o(n){return isNaN(n=+n)?void 0:t[ta.bisect(a,n)]}var a;return o.domain=function(t){return arguments.length?(n=t.map(r).filter(u).sort(e),i()):n},o.range=function(n){return arguments.length?(t=n,i()):t},o.quantiles=function(){return a},o.invertExtent=function(e){return e=t.indexOf(e),0>e?[0/0,0/0]:[e>0?a[e-1]:n[0],e<a.length?a[e]:n[n.length-1]]},o.copy=function(){return no(n,t)},i()}function to(n,t,e){function r(t){return e[Math.max(0,Math.min(o,Math.floor(i*(t-n))))]}function u(){return i=e.length/(t-n),o=e.length-1,r}var i,o;return r.domain=function(e){return arguments.length?(n=+e[0],t=+e[e.length-1],u()):[n,t]},r.range=function(n){return arguments.length?(e=n,u()):e},r.invertExtent=function(t){return t=e.indexOf(t),t=0>t?0/0:t/i+n,[t,t+1/i]},r.copy=function(){return to(n,t,e)},u()}function eo(n,t){function e(e){return e>=e?t[ta.bisect(n,e)]:void 0}return e.domain=function(t){return arguments.length?(n=t,e):n},e.range=function(n){return arguments.length?(t=n,e):t},e.invertExtent=function(e){return e=t.indexOf(e),[n[e-1],n[e]]},e.copy=function(){return eo(n,t)},e}function ro(n){function t(n){return+n}return t.invert=t,t.domain=t.range=function(e){return arguments.length?(n=e.map(t),t):n},t.ticks=function(t){return Xi(n,t)},t.tickFormat=function(t,e){return $i(n,t,e)},t.copy=function(){return ro(n)},t}function uo(){return 0}function io(n){return n.innerRadius}function oo(n){return n.outerRadius}function ao(n){return n.startAngle}function co(n){return n.endAngle}function lo(n){return n&&n.padAngle}function so(n,t,e,r){return(n-e)*t-(t-r)*n>0?0:1}function fo(n,t,e,r,u){var i=n[0]-t[0],o=n[1]-t[1],a=(u?r:-r)/Math.sqrt(i*i+o*o),c=a*o,l=-a*i,s=n[0]+c,f=n[1]+l,h=t[0]+c,g=t[1]+l,p=(s+h)/2,v=(f+g)/2,d=h-s,m=g-f,y=d*d+m*m,M=e-r,x=s*g-h*f,b=(0>m?-1:1)*Math.sqrt(M*M*y-x*x),_=(x*m-d*b)/y,w=(-x*d-m*b)/y,S=(x*m+d*b)/y,k=(-x*d+m*b)/y,E=_-p,A=w-v,N=S-p,C=k-v;return E*E+A*A>N*N+C*C&&(_=S,w=k),[[_-c,w-l],[_*e/M,w*e/M]]}function ho(n){function t(t){function o(){l.push("M",i(n(s),a))}for(var c,l=[],s=[],f=-1,h=t.length,g=Et(e),p=Et(r);++f<h;)u.call(this,c=t[f],f)?s.push([+g.call(this,c,f),+p.call(this,c,f)]):s.length&&(o(),s=[]);return s.length&&o(),l.length?l.join(""):null}var e=Ar,r=Nr,u=Ne,i=go,o=i.key,a=.7;return t.x=function(n){return arguments.length?(e=n,t):e},t.y=function(n){return arguments.length?(r=n,t):r},t.defined=function(n){return arguments.length?(u=n,t):u},t.interpolate=function(n){return arguments.length?(o="function"==typeof n?i=n:(i=El.get(n)||go).key,t):o},t.tension=function(n){return arguments.length?(a=n,t):a},t}function go(n){return n.join("L")}function po(n){return go(n)+"Z"}function vo(n){for(var t=0,e=n.length,r=n[0],u=[r[0],",",r[1]];++t<e;)u.push("H",(r[0]+(r=n[t])[0])/2,"V",r[1]);return e>1&&u.push("H",r[0]),u.join("")}function mo(n){for(var t=0,e=n.length,r=n[0],u=[r[0],",",r[1]];++t<e;)u.push("V",(r=n[t])[1],"H",r[0]);return u.join("")}function yo(n){for(var t=0,e=n.length,r=n[0],u=[r[0],",",r[1]];++t<e;)u.push("H",(r=n[t])[0],"V",r[1]);return u.join("")}function Mo(n,t){return n.length<4?go(n):n[1]+_o(n.slice(1,-1),wo(n,t))}function xo(n,t){return n.length<3?go(n):n[0]+_o((n.push(n[0]),n),wo([n[n.length-2]].concat(n,[n[1]]),t))}function bo(n,t){return n.length<3?go(n):n[0]+_o(n,wo(n,t))}function _o(n,t){if(t.length<1||n.length!=t.length&&n.length!=t.length+2)return go(n);var e=n.length!=t.length,r="",u=n[0],i=n[1],o=t[0],a=o,c=1;if(e&&(r+="Q"+(i[0]-2*o[0]/3)+","+(i[1]-2*o[1]/3)+","+i[0]+","+i[1],u=n[1],c=2),t.length>1){a=t[1],i=n[c],c++,r+="C"+(u[0]+o[0])+","+(u[1]+o[1])+","+(i[0]-a[0])+","+(i[1]-a[1])+","+i[0]+","+i[1];for(var l=2;l<t.length;l++,c++)i=n[c],a=t[l],r+="S"+(i[0]-a[0])+","+(i[1]-a[1])+","+i[0]+","+i[1]}if(e){var s=n[c];r+="Q"+(i[0]+2*a[0]/3)+","+(i[1]+2*a[1]/3)+","+s[0]+","+s[1]}return r}function wo(n,t){for(var e,r=[],u=(1-t)/2,i=n[0],o=n[1],a=1,c=n.length;++a<c;)e=i,i=o,o=n[a],r.push([u*(o[0]-e[0]),u*(o[1]-e[1])]);return r}function So(n){if(n.length<3)return go(n);var t=1,e=n.length,r=n[0],u=r[0],i=r[1],o=[u,u,u,(r=n[1])[0]],a=[i,i,i,r[1]],c=[u,",",i,"L",No(Cl,o),",",No(Cl,a)];for(n.push(n[e-1]);++t<=e;)r=n[t],o.shift(),o.push(r[0]),a.shift(),a.push(r[1]),Co(c,o,a);return n.pop(),c.push("L",r),c.join("")}function ko(n){if(n.length<4)return go(n);for(var t,e=[],r=-1,u=n.length,i=[0],o=[0];++r<3;)t=n[r],i.push(t[0]),o.push(t[1]);for(e.push(No(Cl,i)+","+No(Cl,o)),--r;++r<u;)t=n[r],i.shift(),i.push(t[0]),o.shift(),o.push(t[1]),Co(e,i,o);return e.join("")}function Eo(n){for(var t,e,r=-1,u=n.length,i=u+4,o=[],a=[];++r<4;)e=n[r%u],o.push(e[0]),a.push(e[1]);for(t=[No(Cl,o),",",No(Cl,a)],--r;++r<i;)e=n[r%u],o.shift(),o.push(e[0]),a.shift(),a.push(e[1]),Co(t,o,a);return t.join("")}function Ao(n,t){var e=n.length-1;if(e)for(var r,u,i=n[0][0],o=n[0][1],a=n[e][0]-i,c=n[e][1]-o,l=-1;++l<=e;)r=n[l],u=l/e,r[0]=t*r[0]+(1-t)*(i+u*a),r[1]=t*r[1]+(1-t)*(o+u*c);return So(n)}function No(n,t){return n[0]*t[0]+n[1]*t[1]+n[2]*t[2]+n[3]*t[3]}function Co(n,t,e){n.push("C",No(Al,t),",",No(Al,e),",",No(Nl,t),",",No(Nl,e),",",No(Cl,t),",",No(Cl,e))}function zo(n,t){return(t[1]-n[1])/(t[0]-n[0])}function qo(n){for(var t=0,e=n.length-1,r=[],u=n[0],i=n[1],o=r[0]=zo(u,i);++t<e;)r[t]=(o+(o=zo(u=i,i=n[t+1])))/2;return r[t]=o,r}function Lo(n){for(var t,e,r,u,i=[],o=qo(n),a=-1,c=n.length-1;++a<c;)t=zo(n[a],n[a+1]),ga(t)<Ca?o[a]=o[a+1]=0:(e=o[a]/t,r=o[a+1]/t,u=e*e+r*r,u>9&&(u=3*t/Math.sqrt(u),o[a]=u*e,o[a+1]=u*r));for(a=-1;++a<=c;)u=(n[Math.min(c,a+1)][0]-n[Math.max(0,a-1)][0])/(6*(1+o[a]*o[a])),i.push([u||0,o[a]*u||0]);return i}function To(n){return n.length<3?go(n):n[0]+_o(n,Lo(n))}function Ro(n){for(var t,e,r,u=-1,i=n.length;++u<i;)t=n[u],e=t[0],r=t[1]-Ra,t[0]=e*Math.cos(r),t[1]=e*Math.sin(r);return n}function Do(n){function t(t){function c(){v.push("M",a(n(m),f),s,l(n(d.reverse()),f),"Z")}for(var h,g,p,v=[],d=[],m=[],y=-1,M=t.length,x=Et(e),b=Et(u),_=e===r?function(){return g}:Et(r),w=u===i?function(){return p}:Et(i);++y<M;)o.call(this,h=t[y],y)?(d.push([g=+x.call(this,h,y),p=+b.call(this,h,y)]),m.push([+_.call(this,h,y),+w.call(this,h,y)])):d.length&&(c(),d=[],m=[]);return d.length&&c(),v.length?v.join(""):null}var e=Ar,r=Ar,u=0,i=Nr,o=Ne,a=go,c=a.key,l=a,s="L",f=.7;return t.x=function(n){return arguments.length?(e=r=n,t):r},t.x0=function(n){return arguments.length?(e=n,t):e},t.x1=function(n){return arguments.length?(r=n,t):r
  },t.y=function(n){return arguments.length?(u=i=n,t):i},t.y0=function(n){return arguments.length?(u=n,t):u},t.y1=function(n){return arguments.length?(i=n,t):i},t.defined=function(n){return arguments.length?(o=n,t):o},t.interpolate=function(n){return arguments.length?(c="function"==typeof n?a=n:(a=El.get(n)||go).key,l=a.reverse||a,s=a.closed?"M":"L",t):c},t.tension=function(n){return arguments.length?(f=n,t):f},t}function Po(n){return n.radius}function Uo(n){return[n.x,n.y]}function jo(n){return function(){var t=n.apply(this,arguments),e=t[0],r=t[1]-Ra;return[e*Math.cos(r),e*Math.sin(r)]}}function Fo(){return 64}function Ho(){return"circle"}function Oo(n){var t=Math.sqrt(n/qa);return"M0,"+t+"A"+t+","+t+" 0 1,1 0,"+-t+"A"+t+","+t+" 0 1,1 0,"+t+"Z"}function Io(n){return function(){var t,e;(t=this[n])&&(e=t[t.active])&&(--t.count?delete t[t.active]:delete this[n],t.active+=.5,e.event&&e.event.interrupt.call(this,this.__data__,e.index))}}function Yo(n,t,e){return ya(n,Pl),n.namespace=t,n.id=e,n}function Zo(n,t,e,r){var u=n.id,i=n.namespace;return Y(n,"function"==typeof e?function(n,o,a){n[i][u].tween.set(t,r(e.call(n,n.__data__,o,a)))}:(e=r(e),function(n){n[i][u].tween.set(t,e)}))}function Vo(n){return null==n&&(n=""),function(){this.textContent=n}}function Xo(n){return null==n?"__transition__":"__transition_"+n+"__"}function $o(n,t,e,r,u){var i=n[e]||(n[e]={active:0,count:0}),o=i[r];if(!o){var a=u.time;o=i[r]={tween:new l,time:a,delay:u.delay,duration:u.duration,ease:u.ease,index:t},u=null,++i.count,ta.timer(function(u){function c(e){if(i.active>r)return s();var u=i[i.active];u&&(--i.count,delete i[i.active],u.event&&u.event.interrupt.call(n,n.__data__,u.index)),i.active=r,o.event&&o.event.start.call(n,n.__data__,t),o.tween.forEach(function(e,r){(r=r.call(n,n.__data__,t))&&v.push(r)}),h=o.ease,f=o.duration,ta.timer(function(){return p.c=l(e||1)?Ne:l,1},0,a)}function l(e){if(i.active!==r)return 1;for(var u=e/f,a=h(u),c=v.length;c>0;)v[--c].call(n,a);return u>=1?(o.event&&o.event.end.call(n,n.__data__,t),s()):void 0}function s(){return--i.count?delete i[r]:delete n[e],1}var f,h,g=o.delay,p=ec,v=[];return p.t=g+a,u>=g?c(u-g):void(p.c=c)},0,a)}}function Bo(n,t,e){n.attr("transform",function(n){var r=t(n);return"translate("+(isFinite(r)?r:e(n))+",0)"})}function Wo(n,t,e){n.attr("transform",function(n){var r=t(n);return"translate(0,"+(isFinite(r)?r:e(n))+")"})}function Jo(n){return n.toISOString()}function Go(n,t,e){function r(t){return n(t)}function u(n,e){var r=n[1]-n[0],u=r/e,i=ta.bisect(Vl,u);return i==Vl.length?[t.year,Vi(n.map(function(n){return n/31536e6}),e)[2]]:i?t[u/Vl[i-1]<Vl[i]/u?i-1:i]:[Bl,Vi(n,e)[2]]}return r.invert=function(t){return Ko(n.invert(t))},r.domain=function(t){return arguments.length?(n.domain(t),r):n.domain().map(Ko)},r.nice=function(n,t){function e(e){return!isNaN(e)&&!n.range(e,Ko(+e+1),t).length}var i=r.domain(),o=Pi(i),a=null==n?u(o,10):"number"==typeof n&&u(o,n);return a&&(n=a[0],t=a[1]),r.domain(Fi(i,t>1?{floor:function(t){for(;e(t=n.floor(t));)t=Ko(t-1);return t},ceil:function(t){for(;e(t=n.ceil(t));)t=Ko(+t+1);return t}}:n))},r.ticks=function(n,t){var e=Pi(r.domain()),i=null==n?u(e,10):"number"==typeof n?u(e,n):!n.range&&[{range:n},t];return i&&(n=i[0],t=i[1]),n.range(e[0],Ko(+e[1]+1),1>t?1:t)},r.tickFormat=function(){return e},r.copy=function(){return Go(n.copy(),t,e)},Yi(r,n)}function Ko(n){return new Date(n)}function Qo(n){return JSON.parse(n.responseText)}function na(n){var t=ua.createRange();return t.selectNode(ua.body),t.createContextualFragment(n.responseText)}var ta={version:"3.5.6"},ea=[].slice,ra=function(n){return ea.call(n)},ua=this.document;if(ua)try{ra(ua.documentElement.childNodes)[0].nodeType}catch(ia){ra=function(n){for(var t=n.length,e=new Array(t);t--;)e[t]=n[t];return e}}if(Date.now||(Date.now=function(){return+new Date}),ua)try{ua.createElement("DIV").style.setProperty("opacity",0,"")}catch(oa){var aa=this.Element.prototype,ca=aa.setAttribute,la=aa.setAttributeNS,sa=this.CSSStyleDeclaration.prototype,fa=sa.setProperty;aa.setAttribute=function(n,t){ca.call(this,n,t+"")},aa.setAttributeNS=function(n,t,e){la.call(this,n,t,e+"")},sa.setProperty=function(n,t,e){fa.call(this,n,t+"",e)}}ta.ascending=e,ta.descending=function(n,t){return n>t?-1:t>n?1:t>=n?0:0/0},ta.min=function(n,t){var e,r,u=-1,i=n.length;if(1===arguments.length){for(;++u<i;)if(null!=(r=n[u])&&r>=r){e=r;break}for(;++u<i;)null!=(r=n[u])&&e>r&&(e=r)}else{for(;++u<i;)if(null!=(r=t.call(n,n[u],u))&&r>=r){e=r;break}for(;++u<i;)null!=(r=t.call(n,n[u],u))&&e>r&&(e=r)}return e},ta.max=function(n,t){var e,r,u=-1,i=n.length;if(1===arguments.length){for(;++u<i;)if(null!=(r=n[u])&&r>=r){e=r;break}for(;++u<i;)null!=(r=n[u])&&r>e&&(e=r)}else{for(;++u<i;)if(null!=(r=t.call(n,n[u],u))&&r>=r){e=r;break}for(;++u<i;)null!=(r=t.call(n,n[u],u))&&r>e&&(e=r)}return e},ta.extent=function(n,t){var e,r,u,i=-1,o=n.length;if(1===arguments.length){for(;++i<o;)if(null!=(r=n[i])&&r>=r){e=u=r;break}for(;++i<o;)null!=(r=n[i])&&(e>r&&(e=r),r>u&&(u=r))}else{for(;++i<o;)if(null!=(r=t.call(n,n[i],i))&&r>=r){e=u=r;break}for(;++i<o;)null!=(r=t.call(n,n[i],i))&&(e>r&&(e=r),r>u&&(u=r))}return[e,u]},ta.sum=function(n,t){var e,r=0,i=n.length,o=-1;if(1===arguments.length)for(;++o<i;)u(e=+n[o])&&(r+=e);else for(;++o<i;)u(e=+t.call(n,n[o],o))&&(r+=e);return r},ta.mean=function(n,t){var e,i=0,o=n.length,a=-1,c=o;if(1===arguments.length)for(;++a<o;)u(e=r(n[a]))?i+=e:--c;else for(;++a<o;)u(e=r(t.call(n,n[a],a)))?i+=e:--c;return c?i/c:void 0},ta.quantile=function(n,t){var e=(n.length-1)*t+1,r=Math.floor(e),u=+n[r-1],i=e-r;return i?u+i*(n[r]-u):u},ta.median=function(n,t){var i,o=[],a=n.length,c=-1;if(1===arguments.length)for(;++c<a;)u(i=r(n[c]))&&o.push(i);else for(;++c<a;)u(i=r(t.call(n,n[c],c)))&&o.push(i);return o.length?ta.quantile(o.sort(e),.5):void 0},ta.variance=function(n,t){var e,i,o=n.length,a=0,c=0,l=-1,s=0;if(1===arguments.length)for(;++l<o;)u(e=r(n[l]))&&(i=e-a,a+=i/++s,c+=i*(e-a));else for(;++l<o;)u(e=r(t.call(n,n[l],l)))&&(i=e-a,a+=i/++s,c+=i*(e-a));return s>1?c/(s-1):void 0},ta.deviation=function(){var n=ta.variance.apply(this,arguments);return n?Math.sqrt(n):n};var ha=i(e);ta.bisectLeft=ha.left,ta.bisect=ta.bisectRight=ha.right,ta.bisector=function(n){return i(1===n.length?function(t,r){return e(n(t),r)}:n)},ta.shuffle=function(n,t,e){(i=arguments.length)<3&&(e=n.length,2>i&&(t=0));for(var r,u,i=e-t;i;)u=Math.random()*i--|0,r=n[i+t],n[i+t]=n[u+t],n[u+t]=r;return n},ta.permute=function(n,t){for(var e=t.length,r=new Array(e);e--;)r[e]=n[t[e]];return r},ta.pairs=function(n){for(var t,e=0,r=n.length-1,u=n[0],i=new Array(0>r?0:r);r>e;)i[e]=[t=u,u=n[++e]];return i},ta.zip=function(){if(!(r=arguments.length))return[];for(var n=-1,t=ta.min(arguments,o),e=new Array(t);++n<t;)for(var r,u=-1,i=e[n]=new Array(r);++u<r;)i[u]=arguments[u][n];return e},ta.transpose=function(n){return ta.zip.apply(ta,n)},ta.keys=function(n){var t=[];for(var e in n)t.push(e);return t},ta.values=function(n){var t=[];for(var e in n)t.push(n[e]);return t},ta.entries=function(n){var t=[];for(var e in n)t.push({key:e,value:n[e]});return t},ta.merge=function(n){for(var t,e,r,u=n.length,i=-1,o=0;++i<u;)o+=n[i].length;for(e=new Array(o);--u>=0;)for(r=n[u],t=r.length;--t>=0;)e[--o]=r[t];return e};var ga=Math.abs;ta.range=function(n,t,e){if(arguments.length<3&&(e=1,arguments.length<2&&(t=n,n=0)),(t-n)/e===1/0)throw new Error("infinite range");var r,u=[],i=a(ga(e)),o=-1;if(n*=i,t*=i,e*=i,0>e)for(;(r=n+e*++o)>t;)u.push(r/i);else for(;(r=n+e*++o)<t;)u.push(r/i);return u},ta.map=function(n,t){var e=new l;if(n instanceof l)n.forEach(function(n,t){e.set(n,t)});else if(Array.isArray(n)){var r,u=-1,i=n.length;if(1===arguments.length)for(;++u<i;)e.set(u,n[u]);else for(;++u<i;)e.set(t.call(n,r=n[u],u),r)}else for(var o in n)e.set(o,n[o]);return e};var pa="__proto__",va="\x00";c(l,{has:h,get:function(n){return this._[s(n)]},set:function(n,t){return this._[s(n)]=t},remove:g,keys:p,values:function(){var n=[];for(var t in this._)n.push(this._[t]);return n},entries:function(){var n=[];for(var t in this._)n.push({key:f(t),value:this._[t]});return n},size:v,empty:d,forEach:function(n){for(var t in this._)n.call(this,f(t),this._[t])}}),ta.nest=function(){function n(t,o,a){if(a>=i.length)return r?r.call(u,o):e?o.sort(e):o;for(var c,s,f,h,g=-1,p=o.length,v=i[a++],d=new l;++g<p;)(h=d.get(c=v(s=o[g])))?h.push(s):d.set(c,[s]);return t?(s=t(),f=function(e,r){s.set(e,n(t,r,a))}):(s={},f=function(e,r){s[e]=n(t,r,a)}),d.forEach(f),s}function t(n,e){if(e>=i.length)return n;var r=[],u=o[e++];return n.forEach(function(n,u){r.push({key:n,values:t(u,e)})}),u?r.sort(function(n,t){return u(n.key,t.key)}):r}var e,r,u={},i=[],o=[];return u.map=function(t,e){return n(e,t,0)},u.entries=function(e){return t(n(ta.map,e,0),0)},u.key=function(n){return i.push(n),u},u.sortKeys=function(n){return o[i.length-1]=n,u},u.sortValues=function(n){return e=n,u},u.rollup=function(n){return r=n,u},u},ta.set=function(n){var t=new m;if(n)for(var e=0,r=n.length;r>e;++e)t.add(n[e]);return t},c(m,{has:h,add:function(n){return this._[s(n+="")]=!0,n},remove:g,values:p,size:v,empty:d,forEach:function(n){for(var t in this._)n.call(this,f(t))}}),ta.behavior={},ta.rebind=function(n,t){for(var e,r=1,u=arguments.length;++r<u;)n[e=arguments[r]]=M(n,t,t[e]);return n};var da=["webkit","ms","moz","Moz","o","O"];ta.dispatch=function(){for(var n=new _,t=-1,e=arguments.length;++t<e;)n[arguments[t]]=w(n);return n},_.prototype.on=function(n,t){var e=n.indexOf("."),r="";if(e>=0&&(r=n.slice(e+1),n=n.slice(0,e)),n)return arguments.length<2?this[n].on(r):this[n].on(r,t);if(2===arguments.length){if(null==t)for(n in this)this.hasOwnProperty(n)&&this[n].on(r,null);return this}},ta.event=null,ta.requote=function(n){return n.replace(ma,"\\$&")};var ma=/[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g,ya={}.__proto__?function(n,t){n.__proto__=t}:function(n,t){for(var e in t)n[e]=t[e]},Ma=function(n,t){return t.querySelector(n)},xa=function(n,t){return t.querySelectorAll(n)},ba=function(n,t){var e=n.matches||n[x(n,"matchesSelector")];return(ba=function(n,t){return e.call(n,t)})(n,t)};"function"==typeof Sizzle&&(Ma=function(n,t){return Sizzle(n,t)[0]||null},xa=Sizzle,ba=Sizzle.matchesSelector),ta.selection=function(){return ta.select(ua.documentElement)};var _a=ta.selection.prototype=[];_a.select=function(n){var t,e,r,u,i=[];n=N(n);for(var o=-1,a=this.length;++o<a;){i.push(t=[]),t.parentNode=(r=this[o]).parentNode;for(var c=-1,l=r.length;++c<l;)(u=r[c])?(t.push(e=n.call(u,u.__data__,c,o)),e&&"__data__"in u&&(e.__data__=u.__data__)):t.push(null)}return A(i)},_a.selectAll=function(n){var t,e,r=[];n=C(n);for(var u=-1,i=this.length;++u<i;)for(var o=this[u],a=-1,c=o.length;++a<c;)(e=o[a])&&(r.push(t=ra(n.call(e,e.__data__,a,u))),t.parentNode=e);return A(r)};var wa={svg:"http://www.w3.org/2000/svg",xhtml:"http://www.w3.org/1999/xhtml",xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};ta.ns={prefix:wa,qualify:function(n){var t=n.indexOf(":"),e=n;return t>=0&&(e=n.slice(0,t),n=n.slice(t+1)),wa.hasOwnProperty(e)?{space:wa[e],local:n}:n}},_a.attr=function(n,t){if(arguments.length<2){if("string"==typeof n){var e=this.node();return n=ta.ns.qualify(n),n.local?e.getAttributeNS(n.space,n.local):e.getAttribute(n)}for(t in n)this.each(z(t,n[t]));return this}return this.each(z(n,t))},_a.classed=function(n,t){if(arguments.length<2){if("string"==typeof n){var e=this.node(),r=(n=T(n)).length,u=-1;if(t=e.classList){for(;++u<r;)if(!t.contains(n[u]))return!1}else for(t=e.getAttribute("class");++u<r;)if(!L(n[u]).test(t))return!1;return!0}for(t in n)this.each(R(t,n[t]));return this}return this.each(R(n,t))},_a.style=function(n,e,r){var u=arguments.length;if(3>u){if("string"!=typeof n){2>u&&(e="");for(r in n)this.each(P(r,n[r],e));return this}if(2>u){var i=this.node();return t(i).getComputedStyle(i,null).getPropertyValue(n)}r=""}return this.each(P(n,e,r))},_a.property=function(n,t){if(arguments.length<2){if("string"==typeof n)return this.node()[n];for(t in n)this.each(U(t,n[t]));return this}return this.each(U(n,t))},_a.text=function(n){return arguments.length?this.each("function"==typeof n?function(){var t=n.apply(this,arguments);this.textContent=null==t?"":t}:null==n?function(){this.textContent=""}:function(){this.textContent=n}):this.node().textContent},_a.html=function(n){return arguments.length?this.each("function"==typeof n?function(){var t=n.apply(this,arguments);this.innerHTML=null==t?"":t}:null==n?function(){this.innerHTML=""}:function(){this.innerHTML=n}):this.node().innerHTML},_a.append=function(n){return n=j(n),this.select(function(){return this.appendChild(n.apply(this,arguments))})},_a.insert=function(n,t){return n=j(n),t=N(t),this.select(function(){return this.insertBefore(n.apply(this,arguments),t.apply(this,arguments)||null)})},_a.remove=function(){return this.each(F)},_a.data=function(n,t){function e(n,e){var r,u,i,o=n.length,f=e.length,h=Math.min(o,f),g=new Array(f),p=new Array(f),v=new Array(o);if(t){var d,m=new l,y=new Array(o);for(r=-1;++r<o;)m.has(d=t.call(u=n[r],u.__data__,r))?v[r]=u:m.set(d,u),y[r]=d;for(r=-1;++r<f;)(u=m.get(d=t.call(e,i=e[r],r)))?u!==!0&&(g[r]=u,u.__data__=i):p[r]=H(i),m.set(d,!0);for(r=-1;++r<o;)m.get(y[r])!==!0&&(v[r]=n[r])}else{for(r=-1;++r<h;)u=n[r],i=e[r],u?(u.__data__=i,g[r]=u):p[r]=H(i);for(;f>r;++r)p[r]=H(e[r]);for(;o>r;++r)v[r]=n[r]}p.update=g,p.parentNode=g.parentNode=v.parentNode=n.parentNode,a.push(p),c.push(g),s.push(v)}var r,u,i=-1,o=this.length;if(!arguments.length){for(n=new Array(o=(r=this[0]).length);++i<o;)(u=r[i])&&(n[i]=u.__data__);return n}var a=Z([]),c=A([]),s=A([]);if("function"==typeof n)for(;++i<o;)e(r=this[i],n.call(r,r.parentNode.__data__,i));else for(;++i<o;)e(r=this[i],n);return c.enter=function(){return a},c.exit=function(){return s},c},_a.datum=function(n){return arguments.length?this.property("__data__",n):this.property("__data__")},_a.filter=function(n){var t,e,r,u=[];"function"!=typeof n&&(n=O(n));for(var i=0,o=this.length;o>i;i++){u.push(t=[]),t.parentNode=(e=this[i]).parentNode;for(var a=0,c=e.length;c>a;a++)(r=e[a])&&n.call(r,r.__data__,a,i)&&t.push(r)}return A(u)},_a.order=function(){for(var n=-1,t=this.length;++n<t;)for(var e,r=this[n],u=r.length-1,i=r[u];--u>=0;)(e=r[u])&&(i&&i!==e.nextSibling&&i.parentNode.insertBefore(e,i),i=e);return this},_a.sort=function(n){n=I.apply(this,arguments);for(var t=-1,e=this.length;++t<e;)this[t].sort(n);return this.order()},_a.each=function(n){return Y(this,function(t,e,r){n.call(t,t.__data__,e,r)})},_a.call=function(n){var t=ra(arguments);return n.apply(t[0]=this,t),this},_a.empty=function(){return!this.node()},_a.node=function(){for(var n=0,t=this.length;t>n;n++)for(var e=this[n],r=0,u=e.length;u>r;r++){var i=e[r];if(i)return i}return null},_a.size=function(){var n=0;return Y(this,function(){++n}),n};var Sa=[];ta.selection.enter=Z,ta.selection.enter.prototype=Sa,Sa.append=_a.append,Sa.empty=_a.empty,Sa.node=_a.node,Sa.call=_a.call,Sa.size=_a.size,Sa.select=function(n){for(var t,e,r,u,i,o=[],a=-1,c=this.length;++a<c;){r=(u=this[a]).update,o.push(t=[]),t.parentNode=u.parentNode;for(var l=-1,s=u.length;++l<s;)(i=u[l])?(t.push(r[l]=e=n.call(u.parentNode,i.__data__,l,a)),e.__data__=i.__data__):t.push(null)}return A(o)},Sa.insert=function(n,t){return arguments.length<2&&(t=V(this)),_a.insert.call(this,n,t)},ta.select=function(t){var e;return"string"==typeof t?(e=[Ma(t,ua)],e.parentNode=ua.documentElement):(e=[t],e.parentNode=n(t)),A([e])},ta.selectAll=function(n){var t;return"string"==typeof n?(t=ra(xa(n,ua)),t.parentNode=ua.documentElement):(t=n,t.parentNode=null),A([t])},_a.on=function(n,t,e){var r=arguments.length;if(3>r){if("string"!=typeof n){2>r&&(t=!1);for(e in n)this.each(X(e,n[e],t));return this}if(2>r)return(r=this.node()["__on"+n])&&r._;e=!1}return this.each(X(n,t,e))};var ka=ta.map({mouseenter:"mouseover",mouseleave:"mouseout"});ua&&ka.forEach(function(n){"on"+n in ua&&ka.remove(n)});var Ea,Aa=0;ta.mouse=function(n){return J(n,k())};var Na=this.navigator&&/WebKit/.test(this.navigator.userAgent)?-1:0;ta.touch=function(n,t,e){if(arguments.length<3&&(e=t,t=k().changedTouches),t)for(var r,u=0,i=t.length;i>u;++u)if((r=t[u]).identifier===e)return J(n,r)},ta.behavior.drag=function(){function n(){this.on("mousedown.drag",i).on("touchstart.drag",o)}function e(n,t,e,i,o){return function(){function a(){var n,e,r=t(h,v);r&&(n=r[0]-M[0],e=r[1]-M[1],p|=n|e,M=r,g({type:"drag",x:r[0]+l[0],y:r[1]+l[1],dx:n,dy:e}))}function c(){t(h,v)&&(m.on(i+d,null).on(o+d,null),y(p&&ta.event.target===f),g({type:"dragend"}))}var l,s=this,f=ta.event.target,h=s.parentNode,g=r.of(s,arguments),p=0,v=n(),d=".drag"+(null==v?"":"-"+v),m=ta.select(e(f)).on(i+d,a).on(o+d,c),y=W(f),M=t(h,v);u?(l=u.apply(s,arguments),l=[l.x-M[0],l.y-M[1]]):l=[0,0],g({type:"dragstart"})}}var r=E(n,"drag","dragstart","dragend"),u=null,i=e(b,ta.mouse,t,"mousemove","mouseup"),o=e(G,ta.touch,y,"touchmove","touchend");return n.origin=function(t){return arguments.length?(u=t,n):u},ta.rebind(n,r,"on")},ta.touches=function(n,t){return arguments.length<2&&(t=k().touches),t?ra(t).map(function(t){var e=J(n,t);return e.identifier=t.identifier,e}):[]};var Ca=1e-6,za=Ca*Ca,qa=Math.PI,La=2*qa,Ta=La-Ca,Ra=qa/2,Da=qa/180,Pa=180/qa,Ua=Math.SQRT2,ja=2,Fa=4;ta.interpolateZoom=function(n,t){function e(n){var t=n*y;if(m){var e=rt(v),o=i/(ja*h)*(e*ut(Ua*t+v)-et(v));return[r+o*l,u+o*s,i*e/rt(Ua*t+v)]}return[r+n*l,u+n*s,i*Math.exp(Ua*t)]}var r=n[0],u=n[1],i=n[2],o=t[0],a=t[1],c=t[2],l=o-r,s=a-u,f=l*l+s*s,h=Math.sqrt(f),g=(c*c-i*i+Fa*f)/(2*i*ja*h),p=(c*c-i*i-Fa*f)/(2*c*ja*h),v=Math.log(Math.sqrt(g*g+1)-g),d=Math.log(Math.sqrt(p*p+1)-p),m=d-v,y=(m||Math.log(c/i))/Ua;return e.duration=1e3*y,e},ta.behavior.zoom=function(){function n(n){n.on(q,f).on(Oa+".zoom",g).on("dblclick.zoom",p).on(R,h)}function e(n){return[(n[0]-k.x)/k.k,(n[1]-k.y)/k.k]}function r(n){return[n[0]*k.k+k.x,n[1]*k.k+k.y]}function u(n){k.k=Math.max(N[0],Math.min(N[1],n))}function i(n,t){t=r(t),k.x+=n[0]-t[0],k.y+=n[1]-t[1]}function o(t,e,r,o){t.__chart__={x:k.x,y:k.y,k:k.k},u(Math.pow(2,o)),i(d=e,r),t=ta.select(t),C>0&&(t=t.transition().duration(C)),t.call(n.event)}function a(){b&&b.domain(x.range().map(function(n){return(n-k.x)/k.k}).map(x.invert)),w&&w.domain(_.range().map(function(n){return(n-k.y)/k.k}).map(_.invert))}function c(n){z++||n({type:"zoomstart"})}function l(n){a(),n({type:"zoom",scale:k.k,translate:[k.x,k.y]})}function s(n){--z||(n({type:"zoomend"}),d=null)}function f(){function n(){f=1,i(ta.mouse(u),g),l(a)}function r(){h.on(L,null).on(T,null),p(f&&ta.event.target===o),s(a)}var u=this,o=ta.event.target,a=D.of(u,arguments),f=0,h=ta.select(t(u)).on(L,n).on(T,r),g=e(ta.mouse(u)),p=W(u);Dl.call(u),c(a)}function h(){function n(){var n=ta.touches(p);return g=k.k,n.forEach(function(n){n.identifier in d&&(d[n.identifier]=e(n))}),n}function t(){var t=ta.event.target;ta.select(t).on(x,r).on(b,a),_.push(t);for(var e=ta.event.changedTouches,u=0,i=e.length;i>u;++u)d[e[u].identifier]=null;var c=n(),l=Date.now();if(1===c.length){if(500>l-M){var s=c[0];o(p,s,d[s.identifier],Math.floor(Math.log(k.k)/Math.LN2)+1),S()}M=l}else if(c.length>1){var s=c[0],f=c[1],h=s[0]-f[0],g=s[1]-f[1];m=h*h+g*g}}function r(){var n,t,e,r,o=ta.touches(p);Dl.call(p);for(var a=0,c=o.length;c>a;++a,r=null)if(e=o[a],r=d[e.identifier]){if(t)break;n=e,t=r}if(r){var s=(s=e[0]-n[0])*s+(s=e[1]-n[1])*s,f=m&&Math.sqrt(s/m);n=[(n[0]+e[0])/2,(n[1]+e[1])/2],t=[(t[0]+r[0])/2,(t[1]+r[1])/2],u(f*g)}M=null,i(n,t),l(v)}function a(){if(ta.event.touches.length){for(var t=ta.event.changedTouches,e=0,r=t.length;r>e;++e)delete d[t[e].identifier];for(var u in d)return void n()}ta.selectAll(_).on(y,null),w.on(q,f).on(R,h),E(),s(v)}var g,p=this,v=D.of(p,arguments),d={},m=0,y=".zoom-"+ta.event.changedTouches[0].identifier,x="touchmove"+y,b="touchend"+y,_=[],w=ta.select(p),E=W(p);t(),c(v),w.on(q,null).on(R,t)}function g(){var n=D.of(this,arguments);y?clearTimeout(y):(Dl.call(this),v=e(d=m||ta.mouse(this)),c(n)),y=setTimeout(function(){y=null,s(n)},50),S(),u(Math.pow(2,.002*Ha())*k.k),i(d,v),l(n)}function p(){var n=ta.mouse(this),t=Math.log(k.k)/Math.LN2;o(this,n,e(n),ta.event.shiftKey?Math.ceil(t)-1:Math.floor(t)+1)}var v,d,m,y,M,x,b,_,w,k={x:0,y:0,k:1},A=[960,500],N=Ia,C=250,z=0,q="mousedown.zoom",L="mousemove.zoom",T="mouseup.zoom",R="touchstart.zoom",D=E(n,"zoomstart","zoom","zoomend");return Oa||(Oa="onwheel"in ua?(Ha=function(){return-ta.event.deltaY*(ta.event.deltaMode?120:1)},"wheel"):"onmousewheel"in ua?(Ha=function(){return ta.event.wheelDelta},"mousewheel"):(Ha=function(){return-ta.event.detail},"MozMousePixelScroll")),n.event=function(n){n.each(function(){var n=D.of(this,arguments),t=k;Tl?ta.select(this).transition().each("start.zoom",function(){k=this.__chart__||{x:0,y:0,k:1},c(n)}).tween("zoom:zoom",function(){var e=A[0],r=A[1],u=d?d[0]:e/2,i=d?d[1]:r/2,o=ta.interpolateZoom([(u-k.x)/k.k,(i-k.y)/k.k,e/k.k],[(u-t.x)/t.k,(i-t.y)/t.k,e/t.k]);return function(t){var r=o(t),a=e/r[2];this.__chart__=k={x:u-r[0]*a,y:i-r[1]*a,k:a},l(n)}}).each("interrupt.zoom",function(){s(n)}).each("end.zoom",function(){s(n)}):(this.__chart__=k,c(n),l(n),s(n))})},n.translate=function(t){return arguments.length?(k={x:+t[0],y:+t[1],k:k.k},a(),n):[k.x,k.y]},n.scale=function(t){return arguments.length?(k={x:k.x,y:k.y,k:+t},a(),n):k.k},n.scaleExtent=function(t){return arguments.length?(N=null==t?Ia:[+t[0],+t[1]],n):N},n.center=function(t){return arguments.length?(m=t&&[+t[0],+t[1]],n):m},n.size=function(t){return arguments.length?(A=t&&[+t[0],+t[1]],n):A},n.duration=function(t){return arguments.length?(C=+t,n):C},n.x=function(t){return arguments.length?(b=t,x=t.copy(),k={x:0,y:0,k:1},n):b},n.y=function(t){return arguments.length?(w=t,_=t.copy(),k={x:0,y:0,k:1},n):w},ta.rebind(n,D,"on")};var Ha,Oa,Ia=[0,1/0];ta.color=ot,ot.prototype.toString=function(){return this.rgb()+""},ta.hsl=at;var Ya=at.prototype=new ot;Ya.brighter=function(n){return n=Math.pow(.7,arguments.length?n:1),new at(this.h,this.s,this.l/n)},Ya.darker=function(n){return n=Math.pow(.7,arguments.length?n:1),new at(this.h,this.s,n*this.l)},Ya.rgb=function(){return ct(this.h,this.s,this.l)},ta.hcl=lt;var Za=lt.prototype=new ot;Za.brighter=function(n){return new lt(this.h,this.c,Math.min(100,this.l+Va*(arguments.length?n:1)))},Za.darker=function(n){return new lt(this.h,this.c,Math.max(0,this.l-Va*(arguments.length?n:1)))},Za.rgb=function(){return st(this.h,this.c,this.l).rgb()},ta.lab=ft;var Va=18,Xa=.95047,$a=1,Ba=1.08883,Wa=ft.prototype=new ot;Wa.brighter=function(n){return new ft(Math.min(100,this.l+Va*(arguments.length?n:1)),this.a,this.b)},Wa.darker=function(n){return new ft(Math.max(0,this.l-Va*(arguments.length?n:1)),this.a,this.b)},Wa.rgb=function(){return ht(this.l,this.a,this.b)},ta.rgb=mt;var Ja=mt.prototype=new ot;Ja.brighter=function(n){n=Math.pow(.7,arguments.length?n:1);var t=this.r,e=this.g,r=this.b,u=30;return t||e||r?(t&&u>t&&(t=u),e&&u>e&&(e=u),r&&u>r&&(r=u),new mt(Math.min(255,t/n),Math.min(255,e/n),Math.min(255,r/n))):new mt(u,u,u)},Ja.darker=function(n){return n=Math.pow(.7,arguments.length?n:1),new mt(n*this.r,n*this.g,n*this.b)},Ja.hsl=function(){return _t(this.r,this.g,this.b)},Ja.toString=function(){return"#"+xt(this.r)+xt(this.g)+xt(this.b)};var Ga=ta.map({aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074});Ga.forEach(function(n,t){Ga.set(n,yt(t))}),ta.functor=Et,ta.xhr=At(y),ta.dsv=function(n,t){function e(n,e,i){arguments.length<3&&(i=e,e=null);var o=Nt(n,t,null==e?r:u(e),i);return o.row=function(n){return arguments.length?o.response(null==(e=n)?r:u(n)):e},o}function r(n){return e.parse(n.responseText)}function u(n){return function(t){return e.parse(t.responseText,n)}}function i(t){return t.map(o).join(n)}function o(n){return a.test(n)?'"'+n.replace(/\"/g,'""')+'"':n}var a=new RegExp('["'+n+"\n]"),c=n.charCodeAt(0);return e.parse=function(n,t){var r;return e.parseRows(n,function(n,e){if(r)return r(n,e-1);var u=new Function("d","return {"+n.map(function(n,t){return JSON.stringify(n)+": d["+t+"]"}).join(",")+"}");r=t?function(n,e){return t(u(n),e)}:u})},e.parseRows=function(n,t){function e(){if(s>=l)return o;if(u)return u=!1,i;var t=s;if(34===n.charCodeAt(t)){for(var e=t;e++<l;)if(34===n.charCodeAt(e)){if(34!==n.charCodeAt(e+1))break;++e}s=e+2;var r=n.charCodeAt(e+1);return 13===r?(u=!0,10===n.charCodeAt(e+2)&&++s):10===r&&(u=!0),n.slice(t+1,e).replace(/""/g,'"')}for(;l>s;){var r=n.charCodeAt(s++),a=1;if(10===r)u=!0;else if(13===r)u=!0,10===n.charCodeAt(s)&&(++s,++a);else if(r!==c)continue;return n.slice(t,s-a)}return n.slice(t)}for(var r,u,i={},o={},a=[],l=n.length,s=0,f=0;(r=e())!==o;){for(var h=[];r!==i&&r!==o;)h.push(r),r=e();t&&null==(h=t(h,f++))||a.push(h)}return a},e.format=function(t){if(Array.isArray(t[0]))return e.formatRows(t);var r=new m,u=[];return t.forEach(function(n){for(var t in n)r.has(t)||u.push(r.add(t))}),[u.map(o).join(n)].concat(t.map(function(t){return u.map(function(n){return o(t[n])}).join(n)})).join("\n")},e.formatRows=function(n){return n.map(i).join("\n")},e},ta.csv=ta.dsv(",","text/csv"),ta.tsv=ta.dsv("	","text/tab-separated-values");var Ka,Qa,nc,tc,ec,rc=this[x(this,"requestAnimationFrame")]||function(n){setTimeout(n,17)};ta.timer=function(n,t,e){var r=arguments.length;2>r&&(t=0),3>r&&(e=Date.now());var u=e+t,i={c:n,t:u,f:!1,n:null};Qa?Qa.n=i:Ka=i,Qa=i,nc||(tc=clearTimeout(tc),nc=1,rc(qt))},ta.timer.flush=function(){Lt(),Tt()},ta.round=function(n,t){return t?Math.round(n*(t=Math.pow(10,t)))/t:Math.round(n)};var uc=["y","z","a","f","p","n","\xb5","m","","k","M","G","T","P","E","Z","Y"].map(Dt);ta.formatPrefix=function(n,t){var e=0;return n&&(0>n&&(n*=-1),t&&(n=ta.round(n,Rt(n,t))),e=1+Math.floor(1e-12+Math.log(n)/Math.LN10),e=Math.max(-24,Math.min(24,3*Math.floor((e-1)/3)))),uc[8+e/3]};var ic=/(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i,oc=ta.map({b:function(n){return n.toString(2)},c:function(n){return String.fromCharCode(n)},o:function(n){return n.toString(8)},x:function(n){return n.toString(16)},X:function(n){return n.toString(16).toUpperCase()},g:function(n,t){return n.toPrecision(t)},e:function(n,t){return n.toExponential(t)},f:function(n,t){return n.toFixed(t)},r:function(n,t){return(n=ta.round(n,Rt(n,t))).toFixed(Math.max(0,Math.min(20,Rt(n*(1+1e-15),t))))}}),ac=ta.time={},cc=Date;jt.prototype={getDate:function(){return this._.getUTCDate()},getDay:function(){return this._.getUTCDay()},getFullYear:function(){return this._.getUTCFullYear()},getHours:function(){return this._.getUTCHours()},getMilliseconds:function(){return this._.getUTCMilliseconds()},getMinutes:function(){return this._.getUTCMinutes()},getMonth:function(){return this._.getUTCMonth()},getSeconds:function(){return this._.getUTCSeconds()},getTime:function(){return this._.getTime()},getTimezoneOffset:function(){return 0},valueOf:function(){return this._.valueOf()},setDate:function(){lc.setUTCDate.apply(this._,arguments)},setDay:function(){lc.setUTCDay.apply(this._,arguments)},setFullYear:function(){lc.setUTCFullYear.apply(this._,arguments)},setHours:function(){lc.setUTCHours.apply(this._,arguments)},setMilliseconds:function(){lc.setUTCMilliseconds.apply(this._,arguments)},setMinutes:function(){lc.setUTCMinutes.apply(this._,arguments)},setMonth:function(){lc.setUTCMonth.apply(this._,arguments)},setSeconds:function(){lc.setUTCSeconds.apply(this._,arguments)},setTime:function(){lc.setTime.apply(this._,arguments)}};var lc=Date.prototype;ac.year=Ft(function(n){return n=ac.day(n),n.setMonth(0,1),n},function(n,t){n.setFullYear(n.getFullYear()+t)},function(n){return n.getFullYear()}),ac.years=ac.year.range,ac.years.utc=ac.year.utc.range,ac.day=Ft(function(n){var t=new cc(2e3,0);return t.setFullYear(n.getFullYear(),n.getMonth(),n.getDate()),t},function(n,t){n.setDate(n.getDate()+t)},function(n){return n.getDate()-1}),ac.days=ac.day.range,ac.days.utc=ac.day.utc.range,ac.dayOfYear=function(n){var t=ac.year(n);return Math.floor((n-t-6e4*(n.getTimezoneOffset()-t.getTimezoneOffset()))/864e5)},["sunday","monday","tuesday","wednesday","thursday","friday","saturday"].forEach(function(n,t){t=7-t;var e=ac[n]=Ft(function(n){return(n=ac.day(n)).setDate(n.getDate()-(n.getDay()+t)%7),n},function(n,t){n.setDate(n.getDate()+7*Math.floor(t))},function(n){var e=ac.year(n).getDay();return Math.floor((ac.dayOfYear(n)+(e+t)%7)/7)-(e!==t)});ac[n+"s"]=e.range,ac[n+"s"].utc=e.utc.range,ac[n+"OfYear"]=function(n){var e=ac.year(n).getDay();return Math.floor((ac.dayOfYear(n)+(e+t)%7)/7)}}),ac.week=ac.sunday,ac.weeks=ac.sunday.range,ac.weeks.utc=ac.sunday.utc.range,ac.weekOfYear=ac.sundayOfYear;var sc={"-":"",_:" ",0:"0"},fc=/^\s*\d+/,hc=/^%/;ta.locale=function(n){return{numberFormat:Pt(n),timeFormat:Ot(n)}};var gc=ta.locale({decimal:".",thousands:",",grouping:[3],currency:["$",""],dateTime:"%a %b %e %X %Y",date:"%m/%d/%Y",time:"%H:%M:%S",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]});ta.format=gc.numberFormat,ta.geo={},ce.prototype={s:0,t:0,add:function(n){le(n,this.t,pc),le(pc.s,this.s,this),this.s?this.t+=pc.t:this.s=pc.t
  },reset:function(){this.s=this.t=0},valueOf:function(){return this.s}};var pc=new ce;ta.geo.stream=function(n,t){n&&vc.hasOwnProperty(n.type)?vc[n.type](n,t):se(n,t)};var vc={Feature:function(n,t){se(n.geometry,t)},FeatureCollection:function(n,t){for(var e=n.features,r=-1,u=e.length;++r<u;)se(e[r].geometry,t)}},dc={Sphere:function(n,t){t.sphere()},Point:function(n,t){n=n.coordinates,t.point(n[0],n[1],n[2])},MultiPoint:function(n,t){for(var e=n.coordinates,r=-1,u=e.length;++r<u;)n=e[r],t.point(n[0],n[1],n[2])},LineString:function(n,t){fe(n.coordinates,t,0)},MultiLineString:function(n,t){for(var e=n.coordinates,r=-1,u=e.length;++r<u;)fe(e[r],t,0)},Polygon:function(n,t){he(n.coordinates,t)},MultiPolygon:function(n,t){for(var e=n.coordinates,r=-1,u=e.length;++r<u;)he(e[r],t)},GeometryCollection:function(n,t){for(var e=n.geometries,r=-1,u=e.length;++r<u;)se(e[r],t)}};ta.geo.area=function(n){return mc=0,ta.geo.stream(n,Mc),mc};var mc,yc=new ce,Mc={sphere:function(){mc+=4*qa},point:b,lineStart:b,lineEnd:b,polygonStart:function(){yc.reset(),Mc.lineStart=ge},polygonEnd:function(){var n=2*yc;mc+=0>n?4*qa+n:n,Mc.lineStart=Mc.lineEnd=Mc.point=b}};ta.geo.bounds=function(){function n(n,t){M.push(x=[s=n,h=n]),f>t&&(f=t),t>g&&(g=t)}function t(t,e){var r=pe([t*Da,e*Da]);if(m){var u=de(m,r),i=[u[1],-u[0],0],o=de(i,u);Me(o),o=xe(o);var c=t-p,l=c>0?1:-1,v=o[0]*Pa*l,d=ga(c)>180;if(d^(v>l*p&&l*t>v)){var y=o[1]*Pa;y>g&&(g=y)}else if(v=(v+360)%360-180,d^(v>l*p&&l*t>v)){var y=-o[1]*Pa;f>y&&(f=y)}else f>e&&(f=e),e>g&&(g=e);d?p>t?a(s,t)>a(s,h)&&(h=t):a(t,h)>a(s,h)&&(s=t):h>=s?(s>t&&(s=t),t>h&&(h=t)):t>p?a(s,t)>a(s,h)&&(h=t):a(t,h)>a(s,h)&&(s=t)}else n(t,e);m=r,p=t}function e(){b.point=t}function r(){x[0]=s,x[1]=h,b.point=n,m=null}function u(n,e){if(m){var r=n-p;y+=ga(r)>180?r+(r>0?360:-360):r}else v=n,d=e;Mc.point(n,e),t(n,e)}function i(){Mc.lineStart()}function o(){u(v,d),Mc.lineEnd(),ga(y)>Ca&&(s=-(h=180)),x[0]=s,x[1]=h,m=null}function a(n,t){return(t-=n)<0?t+360:t}function c(n,t){return n[0]-t[0]}function l(n,t){return t[0]<=t[1]?t[0]<=n&&n<=t[1]:n<t[0]||t[1]<n}var s,f,h,g,p,v,d,m,y,M,x,b={point:n,lineStart:e,lineEnd:r,polygonStart:function(){b.point=u,b.lineStart=i,b.lineEnd=o,y=0,Mc.polygonStart()},polygonEnd:function(){Mc.polygonEnd(),b.point=n,b.lineStart=e,b.lineEnd=r,0>yc?(s=-(h=180),f=-(g=90)):y>Ca?g=90:-Ca>y&&(f=-90),x[0]=s,x[1]=h}};return function(n){g=h=-(s=f=1/0),M=[],ta.geo.stream(n,b);var t=M.length;if(t){M.sort(c);for(var e,r=1,u=M[0],i=[u];t>r;++r)e=M[r],l(e[0],u)||l(e[1],u)?(a(u[0],e[1])>a(u[0],u[1])&&(u[1]=e[1]),a(e[0],u[1])>a(u[0],u[1])&&(u[0]=e[0])):i.push(u=e);for(var o,e,p=-1/0,t=i.length-1,r=0,u=i[t];t>=r;u=e,++r)e=i[r],(o=a(u[1],e[0]))>p&&(p=o,s=e[0],h=u[1])}return M=x=null,1/0===s||1/0===f?[[0/0,0/0],[0/0,0/0]]:[[s,f],[h,g]]}}(),ta.geo.centroid=function(n){xc=bc=_c=wc=Sc=kc=Ec=Ac=Nc=Cc=zc=0,ta.geo.stream(n,qc);var t=Nc,e=Cc,r=zc,u=t*t+e*e+r*r;return za>u&&(t=kc,e=Ec,r=Ac,Ca>bc&&(t=_c,e=wc,r=Sc),u=t*t+e*e+r*r,za>u)?[0/0,0/0]:[Math.atan2(e,t)*Pa,tt(r/Math.sqrt(u))*Pa]};var xc,bc,_c,wc,Sc,kc,Ec,Ac,Nc,Cc,zc,qc={sphere:b,point:_e,lineStart:Se,lineEnd:ke,polygonStart:function(){qc.lineStart=Ee},polygonEnd:function(){qc.lineStart=Se}},Lc=Le(Ne,Pe,je,[-qa,-qa/2]),Tc=1e9;ta.geo.clipExtent=function(){var n,t,e,r,u,i,o={stream:function(n){return u&&(u.valid=!1),u=i(n),u.valid=!0,u},extent:function(a){return arguments.length?(i=Ie(n=+a[0][0],t=+a[0][1],e=+a[1][0],r=+a[1][1]),u&&(u.valid=!1,u=null),o):[[n,t],[e,r]]}};return o.extent([[0,0],[960,500]])},(ta.geo.conicEqualArea=function(){return Ye(Ze)}).raw=Ze,ta.geo.albers=function(){return ta.geo.conicEqualArea().rotate([96,0]).center([-.6,38.7]).parallels([29.5,45.5]).scale(1070)},ta.geo.albersUsa=function(){function n(n){var i=n[0],o=n[1];return t=null,e(i,o),t||(r(i,o),t)||u(i,o),t}var t,e,r,u,i=ta.geo.albers(),o=ta.geo.conicEqualArea().rotate([154,0]).center([-2,58.5]).parallels([55,65]),a=ta.geo.conicEqualArea().rotate([157,0]).center([-3,19.9]).parallels([8,18]),c={point:function(n,e){t=[n,e]}};return n.invert=function(n){var t=i.scale(),e=i.translate(),r=(n[0]-e[0])/t,u=(n[1]-e[1])/t;return(u>=.12&&.234>u&&r>=-.425&&-.214>r?o:u>=.166&&.234>u&&r>=-.214&&-.115>r?a:i).invert(n)},n.stream=function(n){var t=i.stream(n),e=o.stream(n),r=a.stream(n);return{point:function(n,u){t.point(n,u),e.point(n,u),r.point(n,u)},sphere:function(){t.sphere(),e.sphere(),r.sphere()},lineStart:function(){t.lineStart(),e.lineStart(),r.lineStart()},lineEnd:function(){t.lineEnd(),e.lineEnd(),r.lineEnd()},polygonStart:function(){t.polygonStart(),e.polygonStart(),r.polygonStart()},polygonEnd:function(){t.polygonEnd(),e.polygonEnd(),r.polygonEnd()}}},n.precision=function(t){return arguments.length?(i.precision(t),o.precision(t),a.precision(t),n):i.precision()},n.scale=function(t){return arguments.length?(i.scale(t),o.scale(.35*t),a.scale(t),n.translate(i.translate())):i.scale()},n.translate=function(t){if(!arguments.length)return i.translate();var l=i.scale(),s=+t[0],f=+t[1];return e=i.translate(t).clipExtent([[s-.455*l,f-.238*l],[s+.455*l,f+.238*l]]).stream(c).point,r=o.translate([s-.307*l,f+.201*l]).clipExtent([[s-.425*l+Ca,f+.12*l+Ca],[s-.214*l-Ca,f+.234*l-Ca]]).stream(c).point,u=a.translate([s-.205*l,f+.212*l]).clipExtent([[s-.214*l+Ca,f+.166*l+Ca],[s-.115*l-Ca,f+.234*l-Ca]]).stream(c).point,n},n.scale(1070)};var Rc,Dc,Pc,Uc,jc,Fc,Hc={point:b,lineStart:b,lineEnd:b,polygonStart:function(){Dc=0,Hc.lineStart=Ve},polygonEnd:function(){Hc.lineStart=Hc.lineEnd=Hc.point=b,Rc+=ga(Dc/2)}},Oc={point:Xe,lineStart:b,lineEnd:b,polygonStart:b,polygonEnd:b},Ic={point:We,lineStart:Je,lineEnd:Ge,polygonStart:function(){Ic.lineStart=Ke},polygonEnd:function(){Ic.point=We,Ic.lineStart=Je,Ic.lineEnd=Ge}};ta.geo.path=function(){function n(n){return n&&("function"==typeof a&&i.pointRadius(+a.apply(this,arguments)),o&&o.valid||(o=u(i)),ta.geo.stream(n,o)),i.result()}function t(){return o=null,n}var e,r,u,i,o,a=4.5;return n.area=function(n){return Rc=0,ta.geo.stream(n,u(Hc)),Rc},n.centroid=function(n){return _c=wc=Sc=kc=Ec=Ac=Nc=Cc=zc=0,ta.geo.stream(n,u(Ic)),zc?[Nc/zc,Cc/zc]:Ac?[kc/Ac,Ec/Ac]:Sc?[_c/Sc,wc/Sc]:[0/0,0/0]},n.bounds=function(n){return jc=Fc=-(Pc=Uc=1/0),ta.geo.stream(n,u(Oc)),[[Pc,Uc],[jc,Fc]]},n.projection=function(n){return arguments.length?(u=(e=n)?n.stream||tr(n):y,t()):e},n.context=function(n){return arguments.length?(i=null==(r=n)?new $e:new Qe(n),"function"!=typeof a&&i.pointRadius(a),t()):r},n.pointRadius=function(t){return arguments.length?(a="function"==typeof t?t:(i.pointRadius(+t),+t),n):a},n.projection(ta.geo.albersUsa()).context(null)},ta.geo.transform=function(n){return{stream:function(t){var e=new er(t);for(var r in n)e[r]=n[r];return e}}},er.prototype={point:function(n,t){this.stream.point(n,t)},sphere:function(){this.stream.sphere()},lineStart:function(){this.stream.lineStart()},lineEnd:function(){this.stream.lineEnd()},polygonStart:function(){this.stream.polygonStart()},polygonEnd:function(){this.stream.polygonEnd()}},ta.geo.projection=ur,ta.geo.projectionMutator=ir,(ta.geo.equirectangular=function(){return ur(ar)}).raw=ar.invert=ar,ta.geo.rotation=function(n){function t(t){return t=n(t[0]*Da,t[1]*Da),t[0]*=Pa,t[1]*=Pa,t}return n=lr(n[0]%360*Da,n[1]*Da,n.length>2?n[2]*Da:0),t.invert=function(t){return t=n.invert(t[0]*Da,t[1]*Da),t[0]*=Pa,t[1]*=Pa,t},t},cr.invert=ar,ta.geo.circle=function(){function n(){var n="function"==typeof r?r.apply(this,arguments):r,t=lr(-n[0]*Da,-n[1]*Da,0).invert,u=[];return e(null,null,1,{point:function(n,e){u.push(n=t(n,e)),n[0]*=Pa,n[1]*=Pa}}),{type:"Polygon",coordinates:[u]}}var t,e,r=[0,0],u=6;return n.origin=function(t){return arguments.length?(r=t,n):r},n.angle=function(r){return arguments.length?(e=gr((t=+r)*Da,u*Da),n):t},n.precision=function(r){return arguments.length?(e=gr(t*Da,(u=+r)*Da),n):u},n.angle(90)},ta.geo.distance=function(n,t){var e,r=(t[0]-n[0])*Da,u=n[1]*Da,i=t[1]*Da,o=Math.sin(r),a=Math.cos(r),c=Math.sin(u),l=Math.cos(u),s=Math.sin(i),f=Math.cos(i);return Math.atan2(Math.sqrt((e=f*o)*e+(e=l*s-c*f*a)*e),c*s+l*f*a)},ta.geo.graticule=function(){function n(){return{type:"MultiLineString",coordinates:t()}}function t(){return ta.range(Math.ceil(i/d)*d,u,d).map(h).concat(ta.range(Math.ceil(l/m)*m,c,m).map(g)).concat(ta.range(Math.ceil(r/p)*p,e,p).filter(function(n){return ga(n%d)>Ca}).map(s)).concat(ta.range(Math.ceil(a/v)*v,o,v).filter(function(n){return ga(n%m)>Ca}).map(f))}var e,r,u,i,o,a,c,l,s,f,h,g,p=10,v=p,d=90,m=360,y=2.5;return n.lines=function(){return t().map(function(n){return{type:"LineString",coordinates:n}})},n.outline=function(){return{type:"Polygon",coordinates:[h(i).concat(g(c).slice(1),h(u).reverse().slice(1),g(l).reverse().slice(1))]}},n.extent=function(t){return arguments.length?n.majorExtent(t).minorExtent(t):n.minorExtent()},n.majorExtent=function(t){return arguments.length?(i=+t[0][0],u=+t[1][0],l=+t[0][1],c=+t[1][1],i>u&&(t=i,i=u,u=t),l>c&&(t=l,l=c,c=t),n.precision(y)):[[i,l],[u,c]]},n.minorExtent=function(t){return arguments.length?(r=+t[0][0],e=+t[1][0],a=+t[0][1],o=+t[1][1],r>e&&(t=r,r=e,e=t),a>o&&(t=a,a=o,o=t),n.precision(y)):[[r,a],[e,o]]},n.step=function(t){return arguments.length?n.majorStep(t).minorStep(t):n.minorStep()},n.majorStep=function(t){return arguments.length?(d=+t[0],m=+t[1],n):[d,m]},n.minorStep=function(t){return arguments.length?(p=+t[0],v=+t[1],n):[p,v]},n.precision=function(t){return arguments.length?(y=+t,s=vr(a,o,90),f=dr(r,e,y),h=vr(l,c,90),g=dr(i,u,y),n):y},n.majorExtent([[-180,-90+Ca],[180,90-Ca]]).minorExtent([[-180,-80-Ca],[180,80+Ca]])},ta.geo.greatArc=function(){function n(){return{type:"LineString",coordinates:[t||r.apply(this,arguments),e||u.apply(this,arguments)]}}var t,e,r=mr,u=yr;return n.distance=function(){return ta.geo.distance(t||r.apply(this,arguments),e||u.apply(this,arguments))},n.source=function(e){return arguments.length?(r=e,t="function"==typeof e?null:e,n):r},n.target=function(t){return arguments.length?(u=t,e="function"==typeof t?null:t,n):u},n.precision=function(){return arguments.length?n:0},n},ta.geo.interpolate=function(n,t){return Mr(n[0]*Da,n[1]*Da,t[0]*Da,t[1]*Da)},ta.geo.length=function(n){return Yc=0,ta.geo.stream(n,Zc),Yc};var Yc,Zc={sphere:b,point:b,lineStart:xr,lineEnd:b,polygonStart:b,polygonEnd:b},Vc=br(function(n){return Math.sqrt(2/(1+n))},function(n){return 2*Math.asin(n/2)});(ta.geo.azimuthalEqualArea=function(){return ur(Vc)}).raw=Vc;var Xc=br(function(n){var t=Math.acos(n);return t&&t/Math.sin(t)},y);(ta.geo.azimuthalEquidistant=function(){return ur(Xc)}).raw=Xc,(ta.geo.conicConformal=function(){return Ye(_r)}).raw=_r,(ta.geo.conicEquidistant=function(){return Ye(wr)}).raw=wr;var $c=br(function(n){return 1/n},Math.atan);(ta.geo.gnomonic=function(){return ur($c)}).raw=$c,Sr.invert=function(n,t){return[n,2*Math.atan(Math.exp(t))-Ra]},(ta.geo.mercator=function(){return kr(Sr)}).raw=Sr;var Bc=br(function(){return 1},Math.asin);(ta.geo.orthographic=function(){return ur(Bc)}).raw=Bc;var Wc=br(function(n){return 1/(1+n)},function(n){return 2*Math.atan(n)});(ta.geo.stereographic=function(){return ur(Wc)}).raw=Wc,Er.invert=function(n,t){return[-t,2*Math.atan(Math.exp(n))-Ra]},(ta.geo.transverseMercator=function(){var n=kr(Er),t=n.center,e=n.rotate;return n.center=function(n){return n?t([-n[1],n[0]]):(n=t(),[n[1],-n[0]])},n.rotate=function(n){return n?e([n[0],n[1],n.length>2?n[2]+90:90]):(n=e(),[n[0],n[1],n[2]-90])},e([0,0,90])}).raw=Er,ta.geom={},ta.geom.hull=function(n){function t(n){if(n.length<3)return[];var t,u=Et(e),i=Et(r),o=n.length,a=[],c=[];for(t=0;o>t;t++)a.push([+u.call(this,n[t],t),+i.call(this,n[t],t),t]);for(a.sort(zr),t=0;o>t;t++)c.push([a[t][0],-a[t][1]]);var l=Cr(a),s=Cr(c),f=s[0]===l[0],h=s[s.length-1]===l[l.length-1],g=[];for(t=l.length-1;t>=0;--t)g.push(n[a[l[t]][2]]);for(t=+f;t<s.length-h;++t)g.push(n[a[s[t]][2]]);return g}var e=Ar,r=Nr;return arguments.length?t(n):(t.x=function(n){return arguments.length?(e=n,t):e},t.y=function(n){return arguments.length?(r=n,t):r},t)},ta.geom.polygon=function(n){return ya(n,Jc),n};var Jc=ta.geom.polygon.prototype=[];Jc.area=function(){for(var n,t=-1,e=this.length,r=this[e-1],u=0;++t<e;)n=r,r=this[t],u+=n[1]*r[0]-n[0]*r[1];return.5*u},Jc.centroid=function(n){var t,e,r=-1,u=this.length,i=0,o=0,a=this[u-1];for(arguments.length||(n=-1/(6*this.area()));++r<u;)t=a,a=this[r],e=t[0]*a[1]-a[0]*t[1],i+=(t[0]+a[0])*e,o+=(t[1]+a[1])*e;return[i*n,o*n]},Jc.clip=function(n){for(var t,e,r,u,i,o,a=Tr(n),c=-1,l=this.length-Tr(this),s=this[l-1];++c<l;){for(t=n.slice(),n.length=0,u=this[c],i=t[(r=t.length-a)-1],e=-1;++e<r;)o=t[e],qr(o,s,u)?(qr(i,s,u)||n.push(Lr(i,o,s,u)),n.push(o)):qr(i,s,u)&&n.push(Lr(i,o,s,u)),i=o;a&&n.push(n[0]),s=u}return n};var Gc,Kc,Qc,nl,tl,el=[],rl=[];Or.prototype.prepare=function(){for(var n,t=this.edges,e=t.length;e--;)n=t[e].edge,n.b&&n.a||t.splice(e,1);return t.sort(Yr),t.length},Qr.prototype={start:function(){return this.edge.l===this.site?this.edge.a:this.edge.b},end:function(){return this.edge.l===this.site?this.edge.b:this.edge.a}},nu.prototype={insert:function(n,t){var e,r,u;if(n){if(t.P=n,t.N=n.N,n.N&&(n.N.P=t),n.N=t,n.R){for(n=n.R;n.L;)n=n.L;n.L=t}else n.R=t;e=n}else this._?(n=uu(this._),t.P=null,t.N=n,n.P=n.L=t,e=n):(t.P=t.N=null,this._=t,e=null);for(t.L=t.R=null,t.U=e,t.C=!0,n=t;e&&e.C;)r=e.U,e===r.L?(u=r.R,u&&u.C?(e.C=u.C=!1,r.C=!0,n=r):(n===e.R&&(eu(this,e),n=e,e=n.U),e.C=!1,r.C=!0,ru(this,r))):(u=r.L,u&&u.C?(e.C=u.C=!1,r.C=!0,n=r):(n===e.L&&(ru(this,e),n=e,e=n.U),e.C=!1,r.C=!0,eu(this,r))),e=n.U;this._.C=!1},remove:function(n){n.N&&(n.N.P=n.P),n.P&&(n.P.N=n.N),n.N=n.P=null;var t,e,r,u=n.U,i=n.L,o=n.R;if(e=i?o?uu(o):i:o,u?u.L===n?u.L=e:u.R=e:this._=e,i&&o?(r=e.C,e.C=n.C,e.L=i,i.U=e,e!==o?(u=e.U,e.U=n.U,n=e.R,u.L=n,e.R=o,o.U=e):(e.U=u,u=e,n=e.R)):(r=n.C,n=e),n&&(n.U=u),!r){if(n&&n.C)return void(n.C=!1);do{if(n===this._)break;if(n===u.L){if(t=u.R,t.C&&(t.C=!1,u.C=!0,eu(this,u),t=u.R),t.L&&t.L.C||t.R&&t.R.C){t.R&&t.R.C||(t.L.C=!1,t.C=!0,ru(this,t),t=u.R),t.C=u.C,u.C=t.R.C=!1,eu(this,u),n=this._;break}}else if(t=u.L,t.C&&(t.C=!1,u.C=!0,ru(this,u),t=u.L),t.L&&t.L.C||t.R&&t.R.C){t.L&&t.L.C||(t.R.C=!1,t.C=!0,eu(this,t),t=u.L),t.C=u.C,u.C=t.L.C=!1,ru(this,u),n=this._;break}t.C=!0,n=u,u=u.U}while(!n.C);n&&(n.C=!1)}}},ta.geom.voronoi=function(n){function t(n){var t=new Array(n.length),r=a[0][0],u=a[0][1],i=a[1][0],o=a[1][1];return iu(e(n),a).cells.forEach(function(e,a){var c=e.edges,l=e.site,s=t[a]=c.length?c.map(function(n){var t=n.start();return[t.x,t.y]}):l.x>=r&&l.x<=i&&l.y>=u&&l.y<=o?[[r,o],[i,o],[i,u],[r,u]]:[];s.point=n[a]}),t}function e(n){return n.map(function(n,t){return{x:Math.round(i(n,t)/Ca)*Ca,y:Math.round(o(n,t)/Ca)*Ca,i:t}})}var r=Ar,u=Nr,i=r,o=u,a=ul;return n?t(n):(t.links=function(n){return iu(e(n)).edges.filter(function(n){return n.l&&n.r}).map(function(t){return{source:n[t.l.i],target:n[t.r.i]}})},t.triangles=function(n){var t=[];return iu(e(n)).cells.forEach(function(e,r){for(var u,i,o=e.site,a=e.edges.sort(Yr),c=-1,l=a.length,s=a[l-1].edge,f=s.l===o?s.r:s.l;++c<l;)u=s,i=f,s=a[c].edge,f=s.l===o?s.r:s.l,r<i.i&&r<f.i&&au(o,i,f)<0&&t.push([n[r],n[i.i],n[f.i]])}),t},t.x=function(n){return arguments.length?(i=Et(r=n),t):r},t.y=function(n){return arguments.length?(o=Et(u=n),t):u},t.clipExtent=function(n){return arguments.length?(a=null==n?ul:n,t):a===ul?null:a},t.size=function(n){return arguments.length?t.clipExtent(n&&[[0,0],n]):a===ul?null:a&&a[1]},t)};var ul=[[-1e6,-1e6],[1e6,1e6]];ta.geom.delaunay=function(n){return ta.geom.voronoi().triangles(n)},ta.geom.quadtree=function(n,t,e,r,u){function i(n){function i(n,t,e,r,u,i,o,a){if(!isNaN(e)&&!isNaN(r))if(n.leaf){var c=n.x,s=n.y;if(null!=c)if(ga(c-e)+ga(s-r)<.01)l(n,t,e,r,u,i,o,a);else{var f=n.point;n.x=n.y=n.point=null,l(n,f,c,s,u,i,o,a),l(n,t,e,r,u,i,o,a)}else n.x=e,n.y=r,n.point=t}else l(n,t,e,r,u,i,o,a)}function l(n,t,e,r,u,o,a,c){var l=.5*(u+a),s=.5*(o+c),f=e>=l,h=r>=s,g=h<<1|f;n.leaf=!1,n=n.nodes[g]||(n.nodes[g]=su()),f?u=l:a=l,h?o=s:c=s,i(n,t,e,r,u,o,a,c)}var s,f,h,g,p,v,d,m,y,M=Et(a),x=Et(c);if(null!=t)v=t,d=e,m=r,y=u;else if(m=y=-(v=d=1/0),f=[],h=[],p=n.length,o)for(g=0;p>g;++g)s=n[g],s.x<v&&(v=s.x),s.y<d&&(d=s.y),s.x>m&&(m=s.x),s.y>y&&(y=s.y),f.push(s.x),h.push(s.y);else for(g=0;p>g;++g){var b=+M(s=n[g],g),_=+x(s,g);v>b&&(v=b),d>_&&(d=_),b>m&&(m=b),_>y&&(y=_),f.push(b),h.push(_)}var w=m-v,S=y-d;w>S?y=d+w:m=v+S;var k=su();if(k.add=function(n){i(k,n,+M(n,++g),+x(n,g),v,d,m,y)},k.visit=function(n){fu(n,k,v,d,m,y)},k.find=function(n){return hu(k,n[0],n[1],v,d,m,y)},g=-1,null==t){for(;++g<p;)i(k,n[g],f[g],h[g],v,d,m,y);--g}else n.forEach(k.add);return f=h=n=s=null,k}var o,a=Ar,c=Nr;return(o=arguments.length)?(a=cu,c=lu,3===o&&(u=e,r=t,e=t=0),i(n)):(i.x=function(n){return arguments.length?(a=n,i):a},i.y=function(n){return arguments.length?(c=n,i):c},i.extent=function(n){return arguments.length?(null==n?t=e=r=u=null:(t=+n[0][0],e=+n[0][1],r=+n[1][0],u=+n[1][1]),i):null==t?null:[[t,e],[r,u]]},i.size=function(n){return arguments.length?(null==n?t=e=r=u=null:(t=e=0,r=+n[0],u=+n[1]),i):null==t?null:[r-t,u-e]},i)},ta.interpolateRgb=gu,ta.interpolateObject=pu,ta.interpolateNumber=vu,ta.interpolateString=du;var il=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,ol=new RegExp(il.source,"g");ta.interpolate=mu,ta.interpolators=[function(n,t){var e=typeof t;return("string"===e?Ga.has(t.toLowerCase())||/^(#|rgb\(|hsl\()/i.test(t)?gu:du:t instanceof ot?gu:Array.isArray(t)?yu:"object"===e&&isNaN(t)?pu:vu)(n,t)}],ta.interpolateArray=yu;var al=function(){return y},cl=ta.map({linear:al,poly:ku,quad:function(){return _u},cubic:function(){return wu},sin:function(){return Eu},exp:function(){return Au},circle:function(){return Nu},elastic:Cu,back:zu,bounce:function(){return qu}}),ll=ta.map({"in":y,out:xu,"in-out":bu,"out-in":function(n){return bu(xu(n))}});ta.ease=function(n){var t=n.indexOf("-"),e=t>=0?n.slice(0,t):n,r=t>=0?n.slice(t+1):"in";return e=cl.get(e)||al,r=ll.get(r)||y,Mu(r(e.apply(null,ea.call(arguments,1))))},ta.interpolateHcl=Lu,ta.interpolateHsl=Tu,ta.interpolateLab=Ru,ta.interpolateRound=Du,ta.transform=function(n){var t=ua.createElementNS(ta.ns.prefix.svg,"g");return(ta.transform=function(n){if(null!=n){t.setAttribute("transform",n);var e=t.transform.baseVal.consolidate()}return new Pu(e?e.matrix:sl)})(n)},Pu.prototype.toString=function(){return"translate("+this.translate+")rotate("+this.rotate+")skewX("+this.skew+")scale("+this.scale+")"};var sl={a:1,b:0,c:0,d:1,e:0,f:0};ta.interpolateTransform=Hu,ta.layout={},ta.layout.bundle=function(){return function(n){for(var t=[],e=-1,r=n.length;++e<r;)t.push(Yu(n[e]));return t}},ta.layout.chord=function(){function n(){var n,l,f,h,g,p={},v=[],d=ta.range(i),m=[];for(e=[],r=[],n=0,h=-1;++h<i;){for(l=0,g=-1;++g<i;)l+=u[h][g];v.push(l),m.push(ta.range(i)),n+=l}for(o&&d.sort(function(n,t){return o(v[n],v[t])}),a&&m.forEach(function(n,t){n.sort(function(n,e){return a(u[t][n],u[t][e])})}),n=(La-s*i)/n,l=0,h=-1;++h<i;){for(f=l,g=-1;++g<i;){var y=d[h],M=m[y][g],x=u[y][M],b=l,_=l+=x*n;p[y+"-"+M]={index:y,subindex:M,startAngle:b,endAngle:_,value:x}}r[y]={index:y,startAngle:f,endAngle:l,value:(l-f)/n},l+=s}for(h=-1;++h<i;)for(g=h-1;++g<i;){var w=p[h+"-"+g],S=p[g+"-"+h];(w.value||S.value)&&e.push(w.value<S.value?{source:S,target:w}:{source:w,target:S})}c&&t()}function t(){e.sort(function(n,t){return c((n.source.value+n.target.value)/2,(t.source.value+t.target.value)/2)})}var e,r,u,i,o,a,c,l={},s=0;return l.matrix=function(n){return arguments.length?(i=(u=n)&&u.length,e=r=null,l):u},l.padding=function(n){return arguments.length?(s=n,e=r=null,l):s},l.sortGroups=function(n){return arguments.length?(o=n,e=r=null,l):o},l.sortSubgroups=function(n){return arguments.length?(a=n,e=null,l):a},l.sortChords=function(n){return arguments.length?(c=n,e&&t(),l):c},l.chords=function(){return e||n(),e},l.groups=function(){return r||n(),r},l},ta.layout.force=function(){function n(n){return function(t,e,r,u){if(t.point!==n){var i=t.cx-n.x,o=t.cy-n.y,a=u-e,c=i*i+o*o;if(c>a*a/d){if(p>c){var l=t.charge/c;n.px-=i*l,n.py-=o*l}return!0}if(t.point&&c&&p>c){var l=t.pointCharge/c;n.px-=i*l,n.py-=o*l}}return!t.charge}}function t(n){n.px=ta.event.x,n.py=ta.event.y,a.resume()}var e,r,u,i,o,a={},c=ta.dispatch("start","tick","end"),l=[1,1],s=.9,f=fl,h=hl,g=-30,p=gl,v=.1,d=.64,m=[],M=[];return a.tick=function(){if((r*=.99)<.005)return c.end({type:"end",alpha:r=0}),!0;var t,e,a,f,h,p,d,y,x,b=m.length,_=M.length;for(e=0;_>e;++e)a=M[e],f=a.source,h=a.target,y=h.x-f.x,x=h.y-f.y,(p=y*y+x*x)&&(p=r*i[e]*((p=Math.sqrt(p))-u[e])/p,y*=p,x*=p,h.x-=y*(d=f.weight/(h.weight+f.weight)),h.y-=x*d,f.x+=y*(d=1-d),f.y+=x*d);if((d=r*v)&&(y=l[0]/2,x=l[1]/2,e=-1,d))for(;++e<b;)a=m[e],a.x+=(y-a.x)*d,a.y+=(x-a.y)*d;if(g)for(Ju(t=ta.geom.quadtree(m),r,o),e=-1;++e<b;)(a=m[e]).fixed||t.visit(n(a));for(e=-1;++e<b;)a=m[e],a.fixed?(a.x=a.px,a.y=a.py):(a.x-=(a.px-(a.px=a.x))*s,a.y-=(a.py-(a.py=a.y))*s);c.tick({type:"tick",alpha:r})},a.nodes=function(n){return arguments.length?(m=n,a):m},a.links=function(n){return arguments.length?(M=n,a):M},a.size=function(n){return arguments.length?(l=n,a):l},a.linkDistance=function(n){return arguments.length?(f="function"==typeof n?n:+n,a):f},a.distance=a.linkDistance,a.linkStrength=function(n){return arguments.length?(h="function"==typeof n?n:+n,a):h},a.friction=function(n){return arguments.length?(s=+n,a):s},a.charge=function(n){return arguments.length?(g="function"==typeof n?n:+n,a):g},a.chargeDistance=function(n){return arguments.length?(p=n*n,a):Math.sqrt(p)},a.gravity=function(n){return arguments.length?(v=+n,a):v},a.theta=function(n){return arguments.length?(d=n*n,a):Math.sqrt(d)},a.alpha=function(n){return arguments.length?(n=+n,r?r=n>0?n:0:n>0&&(c.start({type:"start",alpha:r=n}),ta.timer(a.tick)),a):r},a.start=function(){function n(n,r){if(!e){for(e=new Array(c),a=0;c>a;++a)e[a]=[];for(a=0;s>a;++a){var u=M[a];e[u.source.index].push(u.target),e[u.target.index].push(u.source)}}for(var i,o=e[t],a=-1,l=o.length;++a<l;)if(!isNaN(i=o[a][n]))return i;return Math.random()*r}var t,e,r,c=m.length,s=M.length,p=l[0],v=l[1];for(t=0;c>t;++t)(r=m[t]).index=t,r.weight=0;for(t=0;s>t;++t)r=M[t],"number"==typeof r.source&&(r.source=m[r.source]),"number"==typeof r.target&&(r.target=m[r.target]),++r.source.weight,++r.target.weight;for(t=0;c>t;++t)r=m[t],isNaN(r.x)&&(r.x=n("x",p)),isNaN(r.y)&&(r.y=n("y",v)),isNaN(r.px)&&(r.px=r.x),isNaN(r.py)&&(r.py=r.y);if(u=[],"function"==typeof f)for(t=0;s>t;++t)u[t]=+f.call(this,M[t],t);else for(t=0;s>t;++t)u[t]=f;if(i=[],"function"==typeof h)for(t=0;s>t;++t)i[t]=+h.call(this,M[t],t);else for(t=0;s>t;++t)i[t]=h;if(o=[],"function"==typeof g)for(t=0;c>t;++t)o[t]=+g.call(this,m[t],t);else for(t=0;c>t;++t)o[t]=g;return a.resume()},a.resume=function(){return a.alpha(.1)},a.stop=function(){return a.alpha(0)},a.drag=function(){return e||(e=ta.behavior.drag().origin(y).on("dragstart.force",Xu).on("drag.force",t).on("dragend.force",$u)),arguments.length?void this.on("mouseover.force",Bu).on("mouseout.force",Wu).call(e):e},ta.rebind(a,c,"on")};var fl=20,hl=1,gl=1/0;ta.layout.hierarchy=function(){function n(u){var i,o=[u],a=[];for(u.depth=0;null!=(i=o.pop());)if(a.push(i),(l=e.call(n,i,i.depth))&&(c=l.length)){for(var c,l,s;--c>=0;)o.push(s=l[c]),s.parent=i,s.depth=i.depth+1;r&&(i.value=0),i.children=l}else r&&(i.value=+r.call(n,i,i.depth)||0),delete i.children;return Qu(u,function(n){var e,u;t&&(e=n.children)&&e.sort(t),r&&(u=n.parent)&&(u.value+=n.value)}),a}var t=ei,e=ni,r=ti;return n.sort=function(e){return arguments.length?(t=e,n):t},n.children=function(t){return arguments.length?(e=t,n):e},n.value=function(t){return arguments.length?(r=t,n):r},n.revalue=function(t){return r&&(Ku(t,function(n){n.children&&(n.value=0)}),Qu(t,function(t){var e;t.children||(t.value=+r.call(n,t,t.depth)||0),(e=t.parent)&&(e.value+=t.value)})),t},n},ta.layout.partition=function(){function n(t,e,r,u){var i=t.children;if(t.x=e,t.y=t.depth*u,t.dx=r,t.dy=u,i&&(o=i.length)){var o,a,c,l=-1;for(r=t.value?r/t.value:0;++l<o;)n(a=i[l],e,c=a.value*r,u),e+=c}}function t(n){var e=n.children,r=0;if(e&&(u=e.length))for(var u,i=-1;++i<u;)r=Math.max(r,t(e[i]));return 1+r}function e(e,i){var o=r.call(this,e,i);return n(o[0],0,u[0],u[1]/t(o[0])),o}var r=ta.layout.hierarchy(),u=[1,1];return e.size=function(n){return arguments.length?(u=n,e):u},Gu(e,r)},ta.layout.pie=function(){function n(o){var a,c=o.length,l=o.map(function(e,r){return+t.call(n,e,r)}),s=+("function"==typeof r?r.apply(this,arguments):r),f=("function"==typeof u?u.apply(this,arguments):u)-s,h=Math.min(Math.abs(f)/c,+("function"==typeof i?i.apply(this,arguments):i)),g=h*(0>f?-1:1),p=(f-c*g)/ta.sum(l),v=ta.range(c),d=[];return null!=e&&v.sort(e===pl?function(n,t){return l[t]-l[n]}:function(n,t){return e(o[n],o[t])}),v.forEach(function(n){d[n]={data:o[n],value:a=l[n],startAngle:s,endAngle:s+=a*p+g,padAngle:h}}),d}var t=Number,e=pl,r=0,u=La,i=0;return n.value=function(e){return arguments.length?(t=e,n):t},n.sort=function(t){return arguments.length?(e=t,n):e},n.startAngle=function(t){return arguments.length?(r=t,n):r},n.endAngle=function(t){return arguments.length?(u=t,n):u},n.padAngle=function(t){return arguments.length?(i=t,n):i},n};var pl={};ta.layout.stack=function(){function n(a,c){if(!(h=a.length))return a;var l=a.map(function(e,r){return t.call(n,e,r)}),s=l.map(function(t){return t.map(function(t,e){return[i.call(n,t,e),o.call(n,t,e)]})}),f=e.call(n,s,c);l=ta.permute(l,f),s=ta.permute(s,f);var h,g,p,v,d=r.call(n,s,c),m=l[0].length;for(p=0;m>p;++p)for(u.call(n,l[0][p],v=d[p],s[0][p][1]),g=1;h>g;++g)u.call(n,l[g][p],v+=s[g-1][p][1],s[g][p][1]);return a}var t=y,e=ai,r=ci,u=oi,i=ui,o=ii;return n.values=function(e){return arguments.length?(t=e,n):t},n.order=function(t){return arguments.length?(e="function"==typeof t?t:vl.get(t)||ai,n):e},n.offset=function(t){return arguments.length?(r="function"==typeof t?t:dl.get(t)||ci,n):r},n.x=function(t){return arguments.length?(i=t,n):i},n.y=function(t){return arguments.length?(o=t,n):o},n.out=function(t){return arguments.length?(u=t,n):u},n};var vl=ta.map({"inside-out":function(n){var t,e,r=n.length,u=n.map(li),i=n.map(si),o=ta.range(r).sort(function(n,t){return u[n]-u[t]}),a=0,c=0,l=[],s=[];for(t=0;r>t;++t)e=o[t],c>a?(a+=i[e],l.push(e)):(c+=i[e],s.push(e));return s.reverse().concat(l)},reverse:function(n){return ta.range(n.length).reverse()},"default":ai}),dl=ta.map({silhouette:function(n){var t,e,r,u=n.length,i=n[0].length,o=[],a=0,c=[];for(e=0;i>e;++e){for(t=0,r=0;u>t;t++)r+=n[t][e][1];r>a&&(a=r),o.push(r)}for(e=0;i>e;++e)c[e]=(a-o[e])/2;return c},wiggle:function(n){var t,e,r,u,i,o,a,c,l,s=n.length,f=n[0],h=f.length,g=[];for(g[0]=c=l=0,e=1;h>e;++e){for(t=0,u=0;s>t;++t)u+=n[t][e][1];for(t=0,i=0,a=f[e][0]-f[e-1][0];s>t;++t){for(r=0,o=(n[t][e][1]-n[t][e-1][1])/(2*a);t>r;++r)o+=(n[r][e][1]-n[r][e-1][1])/a;i+=o*n[t][e][1]}g[e]=c-=u?i/u*a:0,l>c&&(l=c)}for(e=0;h>e;++e)g[e]-=l;return g},expand:function(n){var t,e,r,u=n.length,i=n[0].length,o=1/u,a=[];for(e=0;i>e;++e){for(t=0,r=0;u>t;t++)r+=n[t][e][1];if(r)for(t=0;u>t;t++)n[t][e][1]/=r;else for(t=0;u>t;t++)n[t][e][1]=o}for(e=0;i>e;++e)a[e]=0;return a},zero:ci});ta.layout.histogram=function(){function n(n,i){for(var o,a,c=[],l=n.map(e,this),s=r.call(this,l,i),f=u.call(this,s,l,i),i=-1,h=l.length,g=f.length-1,p=t?1:1/h;++i<g;)o=c[i]=[],o.dx=f[i+1]-(o.x=f[i]),o.y=0;if(g>0)for(i=-1;++i<h;)a=l[i],a>=s[0]&&a<=s[1]&&(o=c[ta.bisect(f,a,1,g)-1],o.y+=p,o.push(n[i]));return c}var t=!0,e=Number,r=pi,u=hi;return n.value=function(t){return arguments.length?(e=t,n):e},n.range=function(t){return arguments.length?(r=Et(t),n):r},n.bins=function(t){return arguments.length?(u="number"==typeof t?function(n){return gi(n,t)}:Et(t),n):u},n.frequency=function(e){return arguments.length?(t=!!e,n):t},n},ta.layout.pack=function(){function n(n,i){var o=e.call(this,n,i),a=o[0],c=u[0],l=u[1],s=null==t?Math.sqrt:"function"==typeof t?t:function(){return t};if(a.x=a.y=0,Qu(a,function(n){n.r=+s(n.value)}),Qu(a,Mi),r){var f=r*(t?1:Math.max(2*a.r/c,2*a.r/l))/2;Qu(a,function(n){n.r+=f}),Qu(a,Mi),Qu(a,function(n){n.r-=f})}return _i(a,c/2,l/2,t?1:1/Math.max(2*a.r/c,2*a.r/l)),o}var t,e=ta.layout.hierarchy().sort(vi),r=0,u=[1,1];return n.size=function(t){return arguments.length?(u=t,n):u},n.radius=function(e){return arguments.length?(t=null==e||"function"==typeof e?e:+e,n):t},n.padding=function(t){return arguments.length?(r=+t,n):r},Gu(n,e)},ta.layout.tree=function(){function n(n,u){var s=o.call(this,n,u),f=s[0],h=t(f);if(Qu(h,e),h.parent.m=-h.z,Ku(h,r),l)Ku(f,i);else{var g=f,p=f,v=f;Ku(f,function(n){n.x<g.x&&(g=n),n.x>p.x&&(p=n),n.depth>v.depth&&(v=n)});var d=a(g,p)/2-g.x,m=c[0]/(p.x+a(p,g)/2+d),y=c[1]/(v.depth||1);Ku(f,function(n){n.x=(n.x+d)*m,n.y=n.depth*y})}return s}function t(n){for(var t,e={A:null,children:[n]},r=[e];null!=(t=r.pop());)for(var u,i=t.children,o=0,a=i.length;a>o;++o)r.push((i[o]=u={_:i[o],parent:t,children:(u=i[o].children)&&u.slice()||[],A:null,a:null,z:0,m:0,c:0,s:0,t:null,i:o}).a=u);return e.children[0]}function e(n){var t=n.children,e=n.parent.children,r=n.i?e[n.i-1]:null;if(t.length){Ni(n);var i=(t[0].z+t[t.length-1].z)/2;r?(n.z=r.z+a(n._,r._),n.m=n.z-i):n.z=i}else r&&(n.z=r.z+a(n._,r._));n.parent.A=u(n,r,n.parent.A||e[0])}function r(n){n._.x=n.z+n.parent.m,n.m+=n.parent.m}function u(n,t,e){if(t){for(var r,u=n,i=n,o=t,c=u.parent.children[0],l=u.m,s=i.m,f=o.m,h=c.m;o=Ei(o),u=ki(u),o&&u;)c=ki(c),i=Ei(i),i.a=n,r=o.z+f-u.z-l+a(o._,u._),r>0&&(Ai(Ci(o,n,e),n,r),l+=r,s+=r),f+=o.m,l+=u.m,h+=c.m,s+=i.m;o&&!Ei(i)&&(i.t=o,i.m+=f-s),u&&!ki(c)&&(c.t=u,c.m+=l-h,e=n)}return e}function i(n){n.x*=c[0],n.y=n.depth*c[1]}var o=ta.layout.hierarchy().sort(null).value(null),a=Si,c=[1,1],l=null;return n.separation=function(t){return arguments.length?(a=t,n):a},n.size=function(t){return arguments.length?(l=null==(c=t)?i:null,n):l?null:c},n.nodeSize=function(t){return arguments.length?(l=null==(c=t)?null:i,n):l?c:null},Gu(n,o)},ta.layout.cluster=function(){function n(n,i){var o,a=t.call(this,n,i),c=a[0],l=0;Qu(c,function(n){var t=n.children;t&&t.length?(n.x=qi(t),n.y=zi(t)):(n.x=o?l+=e(n,o):0,n.y=0,o=n)});var s=Li(c),f=Ti(c),h=s.x-e(s,f)/2,g=f.x+e(f,s)/2;return Qu(c,u?function(n){n.x=(n.x-c.x)*r[0],n.y=(c.y-n.y)*r[1]}:function(n){n.x=(n.x-h)/(g-h)*r[0],n.y=(1-(c.y?n.y/c.y:1))*r[1]}),a}var t=ta.layout.hierarchy().sort(null).value(null),e=Si,r=[1,1],u=!1;return n.separation=function(t){return arguments.length?(e=t,n):e},n.size=function(t){return arguments.length?(u=null==(r=t),n):u?null:r},n.nodeSize=function(t){return arguments.length?(u=null!=(r=t),n):u?r:null},Gu(n,t)},ta.layout.treemap=function(){function n(n,t){for(var e,r,u=-1,i=n.length;++u<i;)r=(e=n[u]).value*(0>t?0:t),e.area=isNaN(r)||0>=r?0:r}function t(e){var i=e.children;if(i&&i.length){var o,a,c,l=f(e),s=[],h=i.slice(),p=1/0,v="slice"===g?l.dx:"dice"===g?l.dy:"slice-dice"===g?1&e.depth?l.dy:l.dx:Math.min(l.dx,l.dy);for(n(h,l.dx*l.dy/e.value),s.area=0;(c=h.length)>0;)s.push(o=h[c-1]),s.area+=o.area,"squarify"!==g||(a=r(s,v))<=p?(h.pop(),p=a):(s.area-=s.pop().area,u(s,v,l,!1),v=Math.min(l.dx,l.dy),s.length=s.area=0,p=1/0);s.length&&(u(s,v,l,!0),s.length=s.area=0),i.forEach(t)}}function e(t){var r=t.children;if(r&&r.length){var i,o=f(t),a=r.slice(),c=[];for(n(a,o.dx*o.dy/t.value),c.area=0;i=a.pop();)c.push(i),c.area+=i.area,null!=i.z&&(u(c,i.z?o.dx:o.dy,o,!a.length),c.length=c.area=0);r.forEach(e)}}function r(n,t){for(var e,r=n.area,u=0,i=1/0,o=-1,a=n.length;++o<a;)(e=n[o].area)&&(i>e&&(i=e),e>u&&(u=e));return r*=r,t*=t,r?Math.max(t*u*p/r,r/(t*i*p)):1/0}function u(n,t,e,r){var u,i=-1,o=n.length,a=e.x,l=e.y,s=t?c(n.area/t):0;if(t==e.dx){for((r||s>e.dy)&&(s=e.dy);++i<o;)u=n[i],u.x=a,u.y=l,u.dy=s,a+=u.dx=Math.min(e.x+e.dx-a,s?c(u.area/s):0);u.z=!0,u.dx+=e.x+e.dx-a,e.y+=s,e.dy-=s}else{for((r||s>e.dx)&&(s=e.dx);++i<o;)u=n[i],u.x=a,u.y=l,u.dx=s,l+=u.dy=Math.min(e.y+e.dy-l,s?c(u.area/s):0);u.z=!1,u.dy+=e.y+e.dy-l,e.x+=s,e.dx-=s}}function i(r){var u=o||a(r),i=u[0];return i.x=0,i.y=0,i.dx=l[0],i.dy=l[1],o&&a.revalue(i),n([i],i.dx*i.dy/i.value),(o?e:t)(i),h&&(o=u),u}var o,a=ta.layout.hierarchy(),c=Math.round,l=[1,1],s=null,f=Ri,h=!1,g="squarify",p=.5*(1+Math.sqrt(5));
  return i.size=function(n){return arguments.length?(l=n,i):l},i.padding=function(n){function t(t){var e=n.call(i,t,t.depth);return null==e?Ri(t):Di(t,"number"==typeof e?[e,e,e,e]:e)}function e(t){return Di(t,n)}if(!arguments.length)return s;var r;return f=null==(s=n)?Ri:"function"==(r=typeof n)?t:"number"===r?(n=[n,n,n,n],e):e,i},i.round=function(n){return arguments.length?(c=n?Math.round:Number,i):c!=Number},i.sticky=function(n){return arguments.length?(h=n,o=null,i):h},i.ratio=function(n){return arguments.length?(p=n,i):p},i.mode=function(n){return arguments.length?(g=n+"",i):g},Gu(i,a)},ta.random={normal:function(n,t){var e=arguments.length;return 2>e&&(t=1),1>e&&(n=0),function(){var e,r,u;do e=2*Math.random()-1,r=2*Math.random()-1,u=e*e+r*r;while(!u||u>1);return n+t*e*Math.sqrt(-2*Math.log(u)/u)}},logNormal:function(){var n=ta.random.normal.apply(ta,arguments);return function(){return Math.exp(n())}},bates:function(n){var t=ta.random.irwinHall(n);return function(){return t()/n}},irwinHall:function(n){return function(){for(var t=0,e=0;n>e;e++)t+=Math.random();return t}}},ta.scale={};var ml={floor:y,ceil:y};ta.scale.linear=function(){return Ii([0,1],[0,1],mu,!1)};var yl={s:1,g:1,p:1,r:1,e:1};ta.scale.log=function(){return Ji(ta.scale.linear().domain([0,1]),10,!0,[1,10])};var Ml=ta.format(".0e"),xl={floor:function(n){return-Math.ceil(-n)},ceil:function(n){return-Math.floor(-n)}};ta.scale.pow=function(){return Gi(ta.scale.linear(),1,[0,1])},ta.scale.sqrt=function(){return ta.scale.pow().exponent(.5)},ta.scale.ordinal=function(){return Qi([],{t:"range",a:[[]]})},ta.scale.category10=function(){return ta.scale.ordinal().range(bl)},ta.scale.category20=function(){return ta.scale.ordinal().range(_l)},ta.scale.category20b=function(){return ta.scale.ordinal().range(wl)},ta.scale.category20c=function(){return ta.scale.ordinal().range(Sl)};var bl=[2062260,16744206,2924588,14034728,9725885,9197131,14907330,8355711,12369186,1556175].map(Mt),_l=[2062260,11454440,16744206,16759672,2924588,10018698,14034728,16750742,9725885,12955861,9197131,12885140,14907330,16234194,8355711,13092807,12369186,14408589,1556175,10410725].map(Mt),wl=[3750777,5395619,7040719,10264286,6519097,9216594,11915115,13556636,9202993,12426809,15186514,15190932,8666169,11356490,14049643,15177372,8077683,10834324,13528509,14589654].map(Mt),Sl=[3244733,7057110,10406625,13032431,15095053,16616764,16625259,16634018,3253076,7652470,10607003,13101504,7695281,10394312,12369372,14342891,6513507,9868950,12434877,14277081].map(Mt);ta.scale.quantile=function(){return no([],[])},ta.scale.quantize=function(){return to(0,1,[0,1])},ta.scale.threshold=function(){return eo([.5],[0,1])},ta.scale.identity=function(){return ro([0,1])},ta.svg={},ta.svg.arc=function(){function n(){var n=Math.max(0,+e.apply(this,arguments)),l=Math.max(0,+r.apply(this,arguments)),s=o.apply(this,arguments)-Ra,f=a.apply(this,arguments)-Ra,h=Math.abs(f-s),g=s>f?0:1;if(n>l&&(p=l,l=n,n=p),h>=Ta)return t(l,g)+(n?t(n,1-g):"")+"Z";var p,v,d,m,y,M,x,b,_,w,S,k,E=0,A=0,N=[];if((m=(+c.apply(this,arguments)||0)/2)&&(d=i===kl?Math.sqrt(n*n+l*l):+i.apply(this,arguments),g||(A*=-1),l&&(A=tt(d/l*Math.sin(m))),n&&(E=tt(d/n*Math.sin(m)))),l){y=l*Math.cos(s+A),M=l*Math.sin(s+A),x=l*Math.cos(f-A),b=l*Math.sin(f-A);var C=Math.abs(f-s-2*A)<=qa?0:1;if(A&&so(y,M,x,b)===g^C){var z=(s+f)/2;y=l*Math.cos(z),M=l*Math.sin(z),x=b=null}}else y=M=0;if(n){_=n*Math.cos(f-E),w=n*Math.sin(f-E),S=n*Math.cos(s+E),k=n*Math.sin(s+E);var q=Math.abs(s-f+2*E)<=qa?0:1;if(E&&so(_,w,S,k)===1-g^q){var L=(s+f)/2;_=n*Math.cos(L),w=n*Math.sin(L),S=k=null}}else _=w=0;if((p=Math.min(Math.abs(l-n)/2,+u.apply(this,arguments)))>.001){v=l>n^g?0:1;var T=null==S?[_,w]:null==x?[y,M]:Lr([y,M],[S,k],[x,b],[_,w]),R=y-T[0],D=M-T[1],P=x-T[0],U=b-T[1],j=1/Math.sin(Math.acos((R*P+D*U)/(Math.sqrt(R*R+D*D)*Math.sqrt(P*P+U*U)))/2),F=Math.sqrt(T[0]*T[0]+T[1]*T[1]);if(null!=x){var H=Math.min(p,(l-F)/(j+1)),O=fo(null==S?[_,w]:[S,k],[y,M],l,H,g),I=fo([x,b],[_,w],l,H,g);p===H?N.push("M",O[0],"A",H,",",H," 0 0,",v," ",O[1],"A",l,",",l," 0 ",1-g^so(O[1][0],O[1][1],I[1][0],I[1][1]),",",g," ",I[1],"A",H,",",H," 0 0,",v," ",I[0]):N.push("M",O[0],"A",H,",",H," 0 1,",v," ",I[0])}else N.push("M",y,",",M);if(null!=S){var Y=Math.min(p,(n-F)/(j-1)),Z=fo([y,M],[S,k],n,-Y,g),V=fo([_,w],null==x?[y,M]:[x,b],n,-Y,g);p===Y?N.push("L",V[0],"A",Y,",",Y," 0 0,",v," ",V[1],"A",n,",",n," 0 ",g^so(V[1][0],V[1][1],Z[1][0],Z[1][1]),",",1-g," ",Z[1],"A",Y,",",Y," 0 0,",v," ",Z[0]):N.push("L",V[0],"A",Y,",",Y," 0 0,",v," ",Z[0])}else N.push("L",_,",",w)}else N.push("M",y,",",M),null!=x&&N.push("A",l,",",l," 0 ",C,",",g," ",x,",",b),N.push("L",_,",",w),null!=S&&N.push("A",n,",",n," 0 ",q,",",1-g," ",S,",",k);return N.push("Z"),N.join("")}function t(n,t){return"M0,"+n+"A"+n+","+n+" 0 1,"+t+" 0,"+-n+"A"+n+","+n+" 0 1,"+t+" 0,"+n}var e=io,r=oo,u=uo,i=kl,o=ao,a=co,c=lo;return n.innerRadius=function(t){return arguments.length?(e=Et(t),n):e},n.outerRadius=function(t){return arguments.length?(r=Et(t),n):r},n.cornerRadius=function(t){return arguments.length?(u=Et(t),n):u},n.padRadius=function(t){return arguments.length?(i=t==kl?kl:Et(t),n):i},n.startAngle=function(t){return arguments.length?(o=Et(t),n):o},n.endAngle=function(t){return arguments.length?(a=Et(t),n):a},n.padAngle=function(t){return arguments.length?(c=Et(t),n):c},n.centroid=function(){var n=(+e.apply(this,arguments)+ +r.apply(this,arguments))/2,t=(+o.apply(this,arguments)+ +a.apply(this,arguments))/2-Ra;return[Math.cos(t)*n,Math.sin(t)*n]},n};var kl="auto";ta.svg.line=function(){return ho(y)};var El=ta.map({linear:go,"linear-closed":po,step:vo,"step-before":mo,"step-after":yo,basis:So,"basis-open":ko,"basis-closed":Eo,bundle:Ao,cardinal:bo,"cardinal-open":Mo,"cardinal-closed":xo,monotone:To});El.forEach(function(n,t){t.key=n,t.closed=/-closed$/.test(n)});var Al=[0,2/3,1/3,0],Nl=[0,1/3,2/3,0],Cl=[0,1/6,2/3,1/6];ta.svg.line.radial=function(){var n=ho(Ro);return n.radius=n.x,delete n.x,n.angle=n.y,delete n.y,n},mo.reverse=yo,yo.reverse=mo,ta.svg.area=function(){return Do(y)},ta.svg.area.radial=function(){var n=Do(Ro);return n.radius=n.x,delete n.x,n.innerRadius=n.x0,delete n.x0,n.outerRadius=n.x1,delete n.x1,n.angle=n.y,delete n.y,n.startAngle=n.y0,delete n.y0,n.endAngle=n.y1,delete n.y1,n},ta.svg.chord=function(){function n(n,a){var c=t(this,i,n,a),l=t(this,o,n,a);return"M"+c.p0+r(c.r,c.p1,c.a1-c.a0)+(e(c,l)?u(c.r,c.p1,c.r,c.p0):u(c.r,c.p1,l.r,l.p0)+r(l.r,l.p1,l.a1-l.a0)+u(l.r,l.p1,c.r,c.p0))+"Z"}function t(n,t,e,r){var u=t.call(n,e,r),i=a.call(n,u,r),o=c.call(n,u,r)-Ra,s=l.call(n,u,r)-Ra;return{r:i,a0:o,a1:s,p0:[i*Math.cos(o),i*Math.sin(o)],p1:[i*Math.cos(s),i*Math.sin(s)]}}function e(n,t){return n.a0==t.a0&&n.a1==t.a1}function r(n,t,e){return"A"+n+","+n+" 0 "+ +(e>qa)+",1 "+t}function u(n,t,e,r){return"Q 0,0 "+r}var i=mr,o=yr,a=Po,c=ao,l=co;return n.radius=function(t){return arguments.length?(a=Et(t),n):a},n.source=function(t){return arguments.length?(i=Et(t),n):i},n.target=function(t){return arguments.length?(o=Et(t),n):o},n.startAngle=function(t){return arguments.length?(c=Et(t),n):c},n.endAngle=function(t){return arguments.length?(l=Et(t),n):l},n},ta.svg.diagonal=function(){function n(n,u){var i=t.call(this,n,u),o=e.call(this,n,u),a=(i.y+o.y)/2,c=[i,{x:i.x,y:a},{x:o.x,y:a},o];return c=c.map(r),"M"+c[0]+"C"+c[1]+" "+c[2]+" "+c[3]}var t=mr,e=yr,r=Uo;return n.source=function(e){return arguments.length?(t=Et(e),n):t},n.target=function(t){return arguments.length?(e=Et(t),n):e},n.projection=function(t){return arguments.length?(r=t,n):r},n},ta.svg.diagonal.radial=function(){var n=ta.svg.diagonal(),t=Uo,e=n.projection;return n.projection=function(n){return arguments.length?e(jo(t=n)):t},n},ta.svg.symbol=function(){function n(n,r){return(zl.get(t.call(this,n,r))||Oo)(e.call(this,n,r))}var t=Ho,e=Fo;return n.type=function(e){return arguments.length?(t=Et(e),n):t},n.size=function(t){return arguments.length?(e=Et(t),n):e},n};var zl=ta.map({circle:Oo,cross:function(n){var t=Math.sqrt(n/5)/2;return"M"+-3*t+","+-t+"H"+-t+"V"+-3*t+"H"+t+"V"+-t+"H"+3*t+"V"+t+"H"+t+"V"+3*t+"H"+-t+"V"+t+"H"+-3*t+"Z"},diamond:function(n){var t=Math.sqrt(n/(2*Ll)),e=t*Ll;return"M0,"+-t+"L"+e+",0 0,"+t+" "+-e+",0Z"},square:function(n){var t=Math.sqrt(n)/2;return"M"+-t+","+-t+"L"+t+","+-t+" "+t+","+t+" "+-t+","+t+"Z"},"triangle-down":function(n){var t=Math.sqrt(n/ql),e=t*ql/2;return"M0,"+e+"L"+t+","+-e+" "+-t+","+-e+"Z"},"triangle-up":function(n){var t=Math.sqrt(n/ql),e=t*ql/2;return"M0,"+-e+"L"+t+","+e+" "+-t+","+e+"Z"}});ta.svg.symbolTypes=zl.keys();var ql=Math.sqrt(3),Ll=Math.tan(30*Da);_a.transition=function(n){for(var t,e,r=Tl||++Ul,u=Xo(n),i=[],o=Rl||{time:Date.now(),ease:Su,delay:0,duration:250},a=-1,c=this.length;++a<c;){i.push(t=[]);for(var l=this[a],s=-1,f=l.length;++s<f;)(e=l[s])&&$o(e,s,u,r,o),t.push(e)}return Yo(i,u,r)},_a.interrupt=function(n){return this.each(null==n?Dl:Io(Xo(n)))};var Tl,Rl,Dl=Io(Xo()),Pl=[],Ul=0;Pl.call=_a.call,Pl.empty=_a.empty,Pl.node=_a.node,Pl.size=_a.size,ta.transition=function(n,t){return n&&n.transition?Tl?n.transition(t):n:ta.selection().transition(n)},ta.transition.prototype=Pl,Pl.select=function(n){var t,e,r,u=this.id,i=this.namespace,o=[];n=N(n);for(var a=-1,c=this.length;++a<c;){o.push(t=[]);for(var l=this[a],s=-1,f=l.length;++s<f;)(r=l[s])&&(e=n.call(r,r.__data__,s,a))?("__data__"in r&&(e.__data__=r.__data__),$o(e,s,i,u,r[i][u]),t.push(e)):t.push(null)}return Yo(o,i,u)},Pl.selectAll=function(n){var t,e,r,u,i,o=this.id,a=this.namespace,c=[];n=C(n);for(var l=-1,s=this.length;++l<s;)for(var f=this[l],h=-1,g=f.length;++h<g;)if(r=f[h]){i=r[a][o],e=n.call(r,r.__data__,h,l),c.push(t=[]);for(var p=-1,v=e.length;++p<v;)(u=e[p])&&$o(u,p,a,o,i),t.push(u)}return Yo(c,a,o)},Pl.filter=function(n){var t,e,r,u=[];"function"!=typeof n&&(n=O(n));for(var i=0,o=this.length;o>i;i++){u.push(t=[]);for(var e=this[i],a=0,c=e.length;c>a;a++)(r=e[a])&&n.call(r,r.__data__,a,i)&&t.push(r)}return Yo(u,this.namespace,this.id)},Pl.tween=function(n,t){var e=this.id,r=this.namespace;return arguments.length<2?this.node()[r][e].tween.get(n):Y(this,null==t?function(t){t[r][e].tween.remove(n)}:function(u){u[r][e].tween.set(n,t)})},Pl.attr=function(n,t){function e(){this.removeAttribute(a)}function r(){this.removeAttributeNS(a.space,a.local)}function u(n){return null==n?e:(n+="",function(){var t,e=this.getAttribute(a);return e!==n&&(t=o(e,n),function(n){this.setAttribute(a,t(n))})})}function i(n){return null==n?r:(n+="",function(){var t,e=this.getAttributeNS(a.space,a.local);return e!==n&&(t=o(e,n),function(n){this.setAttributeNS(a.space,a.local,t(n))})})}if(arguments.length<2){for(t in n)this.attr(t,n[t]);return this}var o="transform"==n?Hu:mu,a=ta.ns.qualify(n);return Zo(this,"attr."+n,t,a.local?i:u)},Pl.attrTween=function(n,t){function e(n,e){var r=t.call(this,n,e,this.getAttribute(u));return r&&function(n){this.setAttribute(u,r(n))}}function r(n,e){var r=t.call(this,n,e,this.getAttributeNS(u.space,u.local));return r&&function(n){this.setAttributeNS(u.space,u.local,r(n))}}var u=ta.ns.qualify(n);return this.tween("attr."+n,u.local?r:e)},Pl.style=function(n,e,r){function u(){this.style.removeProperty(n)}function i(e){return null==e?u:(e+="",function(){var u,i=t(this).getComputedStyle(this,null).getPropertyValue(n);return i!==e&&(u=mu(i,e),function(t){this.style.setProperty(n,u(t),r)})})}var o=arguments.length;if(3>o){if("string"!=typeof n){2>o&&(e="");for(r in n)this.style(r,n[r],e);return this}r=""}return Zo(this,"style."+n,e,i)},Pl.styleTween=function(n,e,r){function u(u,i){var o=e.call(this,u,i,t(this).getComputedStyle(this,null).getPropertyValue(n));return o&&function(t){this.style.setProperty(n,o(t),r)}}return arguments.length<3&&(r=""),this.tween("style."+n,u)},Pl.text=function(n){return Zo(this,"text",n,Vo)},Pl.remove=function(){var n=this.namespace;return this.each("end.transition",function(){var t;this[n].count<2&&(t=this.parentNode)&&t.removeChild(this)})},Pl.ease=function(n){var t=this.id,e=this.namespace;return arguments.length<1?this.node()[e][t].ease:("function"!=typeof n&&(n=ta.ease.apply(ta,arguments)),Y(this,function(r){r[e][t].ease=n}))},Pl.delay=function(n){var t=this.id,e=this.namespace;return arguments.length<1?this.node()[e][t].delay:Y(this,"function"==typeof n?function(r,u,i){r[e][t].delay=+n.call(r,r.__data__,u,i)}:(n=+n,function(r){r[e][t].delay=n}))},Pl.duration=function(n){var t=this.id,e=this.namespace;return arguments.length<1?this.node()[e][t].duration:Y(this,"function"==typeof n?function(r,u,i){r[e][t].duration=Math.max(1,n.call(r,r.__data__,u,i))}:(n=Math.max(1,n),function(r){r[e][t].duration=n}))},Pl.each=function(n,t){var e=this.id,r=this.namespace;if(arguments.length<2){var u=Rl,i=Tl;try{Tl=e,Y(this,function(t,u,i){Rl=t[r][e],n.call(t,t.__data__,u,i)})}finally{Rl=u,Tl=i}}else Y(this,function(u){var i=u[r][e];(i.event||(i.event=ta.dispatch("start","end","interrupt"))).on(n,t)});return this},Pl.transition=function(){for(var n,t,e,r,u=this.id,i=++Ul,o=this.namespace,a=[],c=0,l=this.length;l>c;c++){a.push(n=[]);for(var t=this[c],s=0,f=t.length;f>s;s++)(e=t[s])&&(r=e[o][u],$o(e,s,o,i,{time:r.time,ease:r.ease,delay:r.delay+r.duration,duration:r.duration})),n.push(e)}return Yo(a,o,i)},ta.svg.axis=function(){function n(n){n.each(function(){var n,l=ta.select(this),s=this.__chart__||e,f=this.__chart__=e.copy(),h=null==c?f.ticks?f.ticks.apply(f,a):f.domain():c,g=null==t?f.tickFormat?f.tickFormat.apply(f,a):y:t,p=l.selectAll(".tick").data(h,f),v=p.enter().insert("g",".domain").attr("class","tick").style("opacity",Ca),d=ta.transition(p.exit()).style("opacity",Ca).remove(),m=ta.transition(p.order()).style("opacity",1),M=Math.max(u,0)+o,x=Ui(f),b=l.selectAll(".domain").data([0]),_=(b.enter().append("path").attr("class","domain"),ta.transition(b));v.append("line"),v.append("text");var w,S,k,E,A=v.select("line"),N=m.select("line"),C=p.select("text").text(g),z=v.select("text"),q=m.select("text"),L="top"===r||"left"===r?-1:1;if("bottom"===r||"top"===r?(n=Bo,w="x",k="y",S="x2",E="y2",C.attr("dy",0>L?"0em":".71em").style("text-anchor","middle"),_.attr("d","M"+x[0]+","+L*i+"V0H"+x[1]+"V"+L*i)):(n=Wo,w="y",k="x",S="y2",E="x2",C.attr("dy",".32em").style("text-anchor",0>L?"end":"start"),_.attr("d","M"+L*i+","+x[0]+"H0V"+x[1]+"H"+L*i)),A.attr(E,L*u),z.attr(k,L*M),N.attr(S,0).attr(E,L*u),q.attr(w,0).attr(k,L*M),f.rangeBand){var T=f,R=T.rangeBand()/2;s=f=function(n){return T(n)+R}}else s.rangeBand?s=f:d.call(n,f,s);v.call(n,s,f),m.call(n,f,f)})}var t,e=ta.scale.linear(),r=jl,u=6,i=6,o=3,a=[10],c=null;return n.scale=function(t){return arguments.length?(e=t,n):e},n.orient=function(t){return arguments.length?(r=t in Fl?t+"":jl,n):r},n.ticks=function(){return arguments.length?(a=arguments,n):a},n.tickValues=function(t){return arguments.length?(c=t,n):c},n.tickFormat=function(e){return arguments.length?(t=e,n):t},n.tickSize=function(t){var e=arguments.length;return e?(u=+t,i=+arguments[e-1],n):u},n.innerTickSize=function(t){return arguments.length?(u=+t,n):u},n.outerTickSize=function(t){return arguments.length?(i=+t,n):i},n.tickPadding=function(t){return arguments.length?(o=+t,n):o},n.tickSubdivide=function(){return arguments.length&&n},n};var jl="bottom",Fl={top:1,right:1,bottom:1,left:1};ta.svg.brush=function(){function n(t){t.each(function(){var t=ta.select(this).style("pointer-events","all").style("-webkit-tap-highlight-color","rgba(0,0,0,0)").on("mousedown.brush",i).on("touchstart.brush",i),o=t.selectAll(".background").data([0]);o.enter().append("rect").attr("class","background").style("visibility","hidden").style("cursor","crosshair"),t.selectAll(".extent").data([0]).enter().append("rect").attr("class","extent").style("cursor","move");var a=t.selectAll(".resize").data(v,y);a.exit().remove(),a.enter().append("g").attr("class",function(n){return"resize "+n}).style("cursor",function(n){return Hl[n]}).append("rect").attr("x",function(n){return/[ew]$/.test(n)?-3:null}).attr("y",function(n){return/^[ns]/.test(n)?-3:null}).attr("width",6).attr("height",6).style("visibility","hidden"),a.style("display",n.empty()?"none":null);var c,f=ta.transition(t),h=ta.transition(o);l&&(c=Ui(l),h.attr("x",c[0]).attr("width",c[1]-c[0]),r(f)),s&&(c=Ui(s),h.attr("y",c[0]).attr("height",c[1]-c[0]),u(f)),e(f)})}function e(n){n.selectAll(".resize").attr("transform",function(n){return"translate("+f[+/e$/.test(n)]+","+h[+/^s/.test(n)]+")"})}function r(n){n.select(".extent").attr("x",f[0]),n.selectAll(".extent,.n>rect,.s>rect").attr("width",f[1]-f[0])}function u(n){n.select(".extent").attr("y",h[0]),n.selectAll(".extent,.e>rect,.w>rect").attr("height",h[1]-h[0])}function i(){function i(){32==ta.event.keyCode&&(C||(M=null,q[0]-=f[1],q[1]-=h[1],C=2),S())}function v(){32==ta.event.keyCode&&2==C&&(q[0]+=f[1],q[1]+=h[1],C=0,S())}function d(){var n=ta.mouse(b),t=!1;x&&(n[0]+=x[0],n[1]+=x[1]),C||(ta.event.altKey?(M||(M=[(f[0]+f[1])/2,(h[0]+h[1])/2]),q[0]=f[+(n[0]<M[0])],q[1]=h[+(n[1]<M[1])]):M=null),A&&m(n,l,0)&&(r(k),t=!0),N&&m(n,s,1)&&(u(k),t=!0),t&&(e(k),w({type:"brush",mode:C?"move":"resize"}))}function m(n,t,e){var r,u,i=Ui(t),c=i[0],l=i[1],s=q[e],v=e?h:f,d=v[1]-v[0];return C&&(c-=s,l-=d+s),r=(e?p:g)?Math.max(c,Math.min(l,n[e])):n[e],C?u=(r+=s)+d:(M&&(s=Math.max(c,Math.min(l,2*M[e]-r))),r>s?(u=r,r=s):u=s),v[0]!=r||v[1]!=u?(e?a=null:o=null,v[0]=r,v[1]=u,!0):void 0}function y(){d(),k.style("pointer-events","all").selectAll(".resize").style("display",n.empty()?"none":null),ta.select("body").style("cursor",null),L.on("mousemove.brush",null).on("mouseup.brush",null).on("touchmove.brush",null).on("touchend.brush",null).on("keydown.brush",null).on("keyup.brush",null),z(),w({type:"brushend"})}var M,x,b=this,_=ta.select(ta.event.target),w=c.of(b,arguments),k=ta.select(b),E=_.datum(),A=!/^(n|s)$/.test(E)&&l,N=!/^(e|w)$/.test(E)&&s,C=_.classed("extent"),z=W(b),q=ta.mouse(b),L=ta.select(t(b)).on("keydown.brush",i).on("keyup.brush",v);if(ta.event.changedTouches?L.on("touchmove.brush",d).on("touchend.brush",y):L.on("mousemove.brush",d).on("mouseup.brush",y),k.interrupt().selectAll("*").interrupt(),C)q[0]=f[0]-q[0],q[1]=h[0]-q[1];else if(E){var T=+/w$/.test(E),R=+/^n/.test(E);x=[f[1-T]-q[0],h[1-R]-q[1]],q[0]=f[T],q[1]=h[R]}else ta.event.altKey&&(M=q.slice());k.style("pointer-events","none").selectAll(".resize").style("display",null),ta.select("body").style("cursor",_.style("cursor")),w({type:"brushstart"}),d()}var o,a,c=E(n,"brushstart","brush","brushend"),l=null,s=null,f=[0,0],h=[0,0],g=!0,p=!0,v=Ol[0];return n.event=function(n){n.each(function(){var n=c.of(this,arguments),t={x:f,y:h,i:o,j:a},e=this.__chart__||t;this.__chart__=t,Tl?ta.select(this).transition().each("start.brush",function(){o=e.i,a=e.j,f=e.x,h=e.y,n({type:"brushstart"})}).tween("brush:brush",function(){var e=yu(f,t.x),r=yu(h,t.y);return o=a=null,function(u){f=t.x=e(u),h=t.y=r(u),n({type:"brush",mode:"resize"})}}).each("end.brush",function(){o=t.i,a=t.j,n({type:"brush",mode:"resize"}),n({type:"brushend"})}):(n({type:"brushstart"}),n({type:"brush",mode:"resize"}),n({type:"brushend"}))})},n.x=function(t){return arguments.length?(l=t,v=Ol[!l<<1|!s],n):l},n.y=function(t){return arguments.length?(s=t,v=Ol[!l<<1|!s],n):s},n.clamp=function(t){return arguments.length?(l&&s?(g=!!t[0],p=!!t[1]):l?g=!!t:s&&(p=!!t),n):l&&s?[g,p]:l?g:s?p:null},n.extent=function(t){var e,r,u,i,c;return arguments.length?(l&&(e=t[0],r=t[1],s&&(e=e[0],r=r[0]),o=[e,r],l.invert&&(e=l(e),r=l(r)),e>r&&(c=e,e=r,r=c),(e!=f[0]||r!=f[1])&&(f=[e,r])),s&&(u=t[0],i=t[1],l&&(u=u[1],i=i[1]),a=[u,i],s.invert&&(u=s(u),i=s(i)),u>i&&(c=u,u=i,i=c),(u!=h[0]||i!=h[1])&&(h=[u,i])),n):(l&&(o?(e=o[0],r=o[1]):(e=f[0],r=f[1],l.invert&&(e=l.invert(e),r=l.invert(r)),e>r&&(c=e,e=r,r=c))),s&&(a?(u=a[0],i=a[1]):(u=h[0],i=h[1],s.invert&&(u=s.invert(u),i=s.invert(i)),u>i&&(c=u,u=i,i=c))),l&&s?[[e,u],[r,i]]:l?[e,r]:s&&[u,i])},n.clear=function(){return n.empty()||(f=[0,0],h=[0,0],o=a=null),n},n.empty=function(){return!!l&&f[0]==f[1]||!!s&&h[0]==h[1]},ta.rebind(n,c,"on")};var Hl={n:"ns-resize",e:"ew-resize",s:"ns-resize",w:"ew-resize",nw:"nwse-resize",ne:"nesw-resize",se:"nwse-resize",sw:"nesw-resize"},Ol=[["n","e","s","w","nw","ne","se","sw"],["e","w"],["n","s"],[]],Il=ac.format=gc.timeFormat,Yl=Il.utc,Zl=Yl("%Y-%m-%dT%H:%M:%S.%LZ");Il.iso=Date.prototype.toISOString&&+new Date("2000-01-01T00:00:00.000Z")?Jo:Zl,Jo.parse=function(n){var t=new Date(n);return isNaN(t)?null:t},Jo.toString=Zl.toString,ac.second=Ft(function(n){return new cc(1e3*Math.floor(n/1e3))},function(n,t){n.setTime(n.getTime()+1e3*Math.floor(t))},function(n){return n.getSeconds()}),ac.seconds=ac.second.range,ac.seconds.utc=ac.second.utc.range,ac.minute=Ft(function(n){return new cc(6e4*Math.floor(n/6e4))},function(n,t){n.setTime(n.getTime()+6e4*Math.floor(t))},function(n){return n.getMinutes()}),ac.minutes=ac.minute.range,ac.minutes.utc=ac.minute.utc.range,ac.hour=Ft(function(n){var t=n.getTimezoneOffset()/60;return new cc(36e5*(Math.floor(n/36e5-t)+t))},function(n,t){n.setTime(n.getTime()+36e5*Math.floor(t))},function(n){return n.getHours()}),ac.hours=ac.hour.range,ac.hours.utc=ac.hour.utc.range,ac.month=Ft(function(n){return n=ac.day(n),n.setDate(1),n},function(n,t){n.setMonth(n.getMonth()+t)},function(n){return n.getMonth()}),ac.months=ac.month.range,ac.months.utc=ac.month.utc.range;var Vl=[1e3,5e3,15e3,3e4,6e4,3e5,9e5,18e5,36e5,108e5,216e5,432e5,864e5,1728e5,6048e5,2592e6,7776e6,31536e6],Xl=[[ac.second,1],[ac.second,5],[ac.second,15],[ac.second,30],[ac.minute,1],[ac.minute,5],[ac.minute,15],[ac.minute,30],[ac.hour,1],[ac.hour,3],[ac.hour,6],[ac.hour,12],[ac.day,1],[ac.day,2],[ac.week,1],[ac.month,1],[ac.month,3],[ac.year,1]],$l=Il.multi([[".%L",function(n){return n.getMilliseconds()}],[":%S",function(n){return n.getSeconds()}],["%I:%M",function(n){return n.getMinutes()}],["%I %p",function(n){return n.getHours()}],["%a %d",function(n){return n.getDay()&&1!=n.getDate()}],["%b %d",function(n){return 1!=n.getDate()}],["%B",function(n){return n.getMonth()}],["%Y",Ne]]),Bl={range:function(n,t,e){return ta.range(Math.ceil(n/e)*e,+t,e).map(Ko)},floor:y,ceil:y};Xl.year=ac.year,ac.scale=function(){return Go(ta.scale.linear(),Xl,$l)};var Wl=Xl.map(function(n){return[n[0].utc,n[1]]}),Jl=Yl.multi([[".%L",function(n){return n.getUTCMilliseconds()}],[":%S",function(n){return n.getUTCSeconds()}],["%I:%M",function(n){return n.getUTCMinutes()}],["%I %p",function(n){return n.getUTCHours()}],["%a %d",function(n){return n.getUTCDay()&&1!=n.getUTCDate()}],["%b %d",function(n){return 1!=n.getUTCDate()}],["%B",function(n){return n.getUTCMonth()}],["%Y",Ne]]);Wl.year=ac.year.utc,ac.scale.utc=function(){return Go(ta.scale.linear(),Wl,Jl)},ta.text=At(function(n){return n.responseText}),ta.json=function(n,t){return Nt(n,"application/json",Qo,t)},ta.html=function(n,t){return Nt(n,"text/html",na,t)},ta.xml=At(function(n){return n.responseXML}),"function"==typeof define&&define.amd?define(ta):"object"==typeof module&&module.exports&&(module.exports=ta),this.d3=ta}();
  (function (window) {
      'use strict';
  
      /*global define, module, exports, require */
  
      var c3 = { version: "0.4.11-rc4" };
  
      var c3_chart_fn,
          c3_chart_internal_fn,
          c3_chart_internal_axis_fn;
  
      function API(owner) {
          this.owner = owner;
      }
  
      function inherit(base, derived) {
  
          if (Object.create) {
              derived.prototype = Object.create(base.prototype);
          } else {
              var f = function f() {};
              f.prototype = base.prototype;
              derived.prototype = new f();
          }
  
          derived.prototype.constructor = derived;
  
          return derived;
      }
  
      function Chart(config) {
          var $$ = this.internal = new ChartInternal(this);
          $$.loadConfig(config);
  
          $$.beforeInit(config);
          $$.init();
          $$.afterInit(config);
  
          // bind "this" to nested API
          (function bindThis(fn, target, argThis) {
              Object.keys(fn).forEach(function (key) {
                  target[key] = fn[key].bind(argThis);
                  if (Object.keys(fn[key]).length > 0) {
                      bindThis(fn[key], target[key], argThis);
                  }
              });
          })(c3_chart_fn, this, this);
      }
  
      function ChartInternal(api) {
          var $$ = this;
          $$.d3 = window.d3 ? window.d3 : typeof require !== 'undefined' ? require("d3") : undefined;
          $$.api = api;
          $$.config = $$.getDefaultConfig();
          $$.data = {};
          $$.cache = {};
          $$.axes = {};
      }
  
      c3.generate = function (config) {
          return new Chart(config);
      };
  
      c3.chart = {
          fn: Chart.prototype,
          internal: {
              fn: ChartInternal.prototype,
              axis: {
                  fn: Axis.prototype
              }
          }
      };
      c3_chart_fn = c3.chart.fn;
      c3_chart_internal_fn = c3.chart.internal.fn;
      c3_chart_internal_axis_fn = c3.chart.internal.axis.fn;
  
      c3_chart_internal_fn.beforeInit = function () {
          // can do something
      };
      c3_chart_internal_fn.afterInit = function () {
          // can do something
      };
      c3_chart_internal_fn.init = function () {
          var $$ = this, config = $$.config;
  
          $$.initParams();
  
          if (config.data_url) {
              $$.convertUrlToData(config.data_url, config.data_mimeType, config.data_keys, $$.initWithData);
          }
          else if (config.data_json) {
              $$.initWithData($$.convertJsonToData(config.data_json, config.data_keys));
          }
          else if (config.data_rows) {
              $$.initWithData($$.convertRowsToData(config.data_rows));
          }
          else if (config.data_columns) {
              $$.initWithData($$.convertColumnsToData(config.data_columns));
          }
          else {
              throw Error('url or json or rows or columns is required.');
          }
      };
  
      c3_chart_internal_fn.initParams = function () {
          var $$ = this, d3 = $$.d3, config = $$.config;
  
          // MEMO: clipId needs to be unique because it conflicts when multiple charts exist
          $$.clipId = "c3-" + (+new Date()) + '-clip',
          $$.clipIdForXAxis = $$.clipId + '-xaxis',
          $$.clipIdForYAxis = $$.clipId + '-yaxis',
          $$.clipIdForGrid = $$.clipId + '-grid',
          $$.clipIdForSubchart = $$.clipId + '-subchart',
          $$.clipPath = $$.getClipPath($$.clipId),
          $$.clipPathForXAxis = $$.getClipPath($$.clipIdForXAxis),
          $$.clipPathForYAxis = $$.getClipPath($$.clipIdForYAxis);
          $$.clipPathForGrid = $$.getClipPath($$.clipIdForGrid),
          $$.clipPathForSubchart = $$.getClipPath($$.clipIdForSubchart),
  
          $$.dragStart = null;
          $$.dragging = false;
          $$.flowing = false;
          $$.cancelClick = false;
          $$.mouseover = false;
          $$.transiting = false;
  
          $$.color = $$.generateColor();
          $$.levelColor = $$.generateLevelColor();
  
          $$.dataTimeFormat = config.data_xLocaltime ? d3.time.format : d3.time.format.utc;
          $$.axisTimeFormat = config.axis_x_localtime ? d3.time.format : d3.time.format.utc;
          $$.defaultAxisTimeFormat = $$.axisTimeFormat.multi([
              [".%L", function (d) { return d.getMilliseconds(); }],
              [":%S", function (d) { return d.getSeconds(); }],
              ["%I:%M", function (d) { return d.getMinutes(); }],
              ["%I %p", function (d) { return d.getHours(); }],
              ["%-m/%-d", function (d) { return d.getDay() && d.getDate() !== 1; }],
              ["%-m/%-d", function (d) { return d.getDate() !== 1; }],
              ["%-m/%-d", function (d) { return d.getMonth(); }],
              ["%Y/%-m/%-d", function () { return true; }]
          ]);
  
          $$.hiddenTargetIds = [];
          $$.hiddenLegendIds = [];
          $$.focusedTargetIds = [];
          $$.defocusedTargetIds = [];
  
          $$.xOrient = config.axis_rotated ? "left" : "bottom";
          $$.yOrient = config.axis_rotated ? (config.axis_y_inner ? "top" : "bottom") : (config.axis_y_inner ? "right" : "left");
          $$.y2Orient = config.axis_rotated ? (config.axis_y2_inner ? "bottom" : "top") : (config.axis_y2_inner ? "left" : "right");
          $$.subXOrient = config.axis_rotated ? "left" : "bottom";
  
          $$.isLegendRight = config.legend_position === 'right';
          $$.isLegendInset = config.legend_position === 'inset';
          $$.isLegendTop = config.legend_inset_anchor === 'top-left' || config.legend_inset_anchor === 'top-right';
          $$.isLegendLeft = config.legend_inset_anchor === 'top-left' || config.legend_inset_anchor === 'bottom-left';
          $$.legendStep = 0;
          $$.legendItemWidth = 0;
          $$.legendItemHeight = 0;
  
          $$.currentMaxTickWidths = {
              x: 0,
              y: 0,
              y2: 0
          };
  
          $$.rotated_padding_left = 30;
          $$.rotated_padding_right = config.axis_rotated && !config.axis_x_show ? 0 : 30;
          $$.rotated_padding_top = 5;
  
          $$.withoutFadeIn = {};
  
          $$.intervalForObserveInserted = undefined;
  
          $$.axes.subx = d3.selectAll([]); // needs when excluding subchart.js
      };
  
      c3_chart_internal_fn.initChartElements = function () {
          if (this.initBar) { this.initBar(); }
          if (this.initLine) { this.initLine(); }
          if (this.initArc) { this.initArc(); }
          if (this.initGauge) { this.initGauge(); }
          if (this.initText) { this.initText(); }
      };
  
      c3_chart_internal_fn.initWithData = function (data) {
          var $$ = this, d3 = $$.d3, config = $$.config;
          var defs, main, binding = true;
  
          $$.axis = new Axis($$);
  
          if ($$.initPie) { $$.initPie(); }
          if ($$.initBrush) { $$.initBrush(); }
          if ($$.initZoom) { $$.initZoom(); }
  
          if (!config.bindto) {
              $$.selectChart = d3.selectAll([]);
          }
          else if (typeof config.bindto.node === 'function') {
              $$.selectChart = config.bindto;
          }
          else {
              $$.selectChart = d3.select(config.bindto);
          }
          if ($$.selectChart.empty()) {
              $$.selectChart = d3.select(document.createElement('div')).style('opacity', 0);
              $$.observeInserted($$.selectChart);
              binding = false;
          }
          $$.selectChart.html("").classed("c3", true);
  
          // Init data as targets
          $$.data.xs = {};
          $$.data.targets = $$.convertDataToTargets(data);
  
          if (config.data_filter) {
              $$.data.targets = $$.data.targets.filter(config.data_filter);
          }
  
          // Set targets to hide if needed
          if (config.data_hide) {
              $$.addHiddenTargetIds(config.data_hide === true ? $$.mapToIds($$.data.targets) : config.data_hide);
          }
          if (config.legend_hide) {
              $$.addHiddenLegendIds(config.legend_hide === true ? $$.mapToIds($$.data.targets) : config.legend_hide);
          }
  
          // when gauge, hide legend // TODO: fix
          if ($$.hasType('gauge')) {
              config.legend_show = false;
          }
  
          // Init sizes and scales
          $$.updateSizes();
          $$.updateScales();
  
          // Set domains for each scale
          $$.x.domain(d3.extent($$.getXDomain($$.data.targets)));
          $$.y.domain($$.getYDomain($$.data.targets, 'y'));
          $$.y2.domain($$.getYDomain($$.data.targets, 'y2'));
          $$.subX.domain($$.x.domain());
          $$.subY.domain($$.y.domain());
          $$.subY2.domain($$.y2.domain());
  
          // Save original x domain for zoom update
          $$.orgXDomain = $$.x.domain();
  
          // Set initialized scales to brush and zoom
          if ($$.brush) { $$.brush.scale($$.subX); }
          if (config.zoom_enabled) { $$.zoom.scale($$.x); }
  
          /*-- Basic Elements --*/
  
          // Define svgs
          $$.svg = $$.selectChart.append("svg")
              .style("overflow", "hidden")
              .on('mouseenter', function () { return config.onmouseover.call($$); })
              .on('mouseleave', function () { return config.onmouseout.call($$); });
  
          // Define defs
          defs = $$.svg.append("defs");
          $$.clipChart = $$.appendClip(defs, $$.clipId);
          $$.clipXAxis = $$.appendClip(defs, $$.clipIdForXAxis);
          $$.clipYAxis = $$.appendClip(defs, $$.clipIdForYAxis);
          $$.clipGrid = $$.appendClip(defs, $$.clipIdForGrid);
          $$.clipSubchart = $$.appendClip(defs, $$.clipIdForSubchart);
          $$.updateSvgSize();
  
          // Define regions
          main = $$.main = $$.svg.append("g").attr("transform", $$.getTranslate('main'));
  
          if ($$.initSubchart) { $$.initSubchart(); }
          if ($$.initTooltip) { $$.initTooltip(); }
          if ($$.initLegend) { $$.initLegend(); }
          if ($$.initTitle) { $$.initTitle(); }
  
          /*-- Main Region --*/
  
          // text when empty
          main.append("text")
              .attr("class", CLASS.text + ' ' + CLASS.empty)
              .attr("text-anchor", "middle") // horizontal centering of text at x position in all browsers.
              .attr("dominant-baseline", "middle"); // vertical centering of text at y position in all browsers, except IE.
  
          // Regions
          $$.initRegion();
  
          // Grids
          $$.initGrid();
  
          // Define g for chart area
          main.append('g')
              .attr("clip-path", $$.clipPath)
              .attr('class', CLASS.chart);
  
          // Grid lines
          if (config.grid_lines_front) { $$.initGridLines(); }
  
          // Cover whole with rects for events
          $$.initEventRect();
  
          // Define g for chart
          $$.initChartElements();
  
          // if zoom privileged, insert rect to forefront
          // TODO: is this needed?
          main.insert('rect', config.zoom_privileged ? null : 'g.' + CLASS.regions)
              .attr('class', CLASS.zoomRect)
              .attr('width', $$.width)
              .attr('height', $$.height)
              .style('opacity', 0)
              .on("dblclick.zoom", null);
  
          // Set default extent if defined
          if (config.axis_x_extent) { $$.brush.extent($$.getDefaultExtent()); }
  
          // Add Axis
          $$.axis.init();
  
          // Set targets
          $$.updateTargets($$.data.targets);
  
          // Draw with targets
          if (binding) {
              $$.updateDimension();
              $$.config.oninit.call($$);
              $$.redraw({
                  withTransition: false,
                  withTransform: true,
                  withUpdateXDomain: true,
                  withUpdateOrgXDomain: true,
                  withTransitionForAxis: false
              });
          }
  
          // Bind resize event
          $$.bindResize();
  
          // export element of the chart
          $$.api.element = $$.selectChart.node();
      };
  
      c3_chart_internal_fn.smoothLines = function (el, type) {
          var $$ = this;
          if (type === 'grid') {
              el.each(function () {
                  var g = $$.d3.select(this),
                      x1 = g.attr('x1'),
                      x2 = g.attr('x2'),
                      y1 = g.attr('y1'),
                      y2 = g.attr('y2');
                  g.attr({
                      'x1': Math.ceil(x1),
                      'x2': Math.ceil(x2),
                      'y1': Math.ceil(y1),
                      'y2': Math.ceil(y2)
                  });
              });
          }
      };
  
  
      c3_chart_internal_fn.updateSizes = function () {
          var $$ = this, config = $$.config;
          var legendHeight = $$.legend ? $$.getLegendHeight() : 0,
              legendWidth = $$.legend ? $$.getLegendWidth() : 0,
              legendHeightForBottom = $$.isLegendRight || $$.isLegendInset ? 0 : legendHeight,
              hasArc = $$.hasArcType(),
              xAxisHeight = config.axis_rotated || hasArc ? 0 : $$.getHorizontalAxisHeight('x'),
              subchartHeight = config.subchart_show && !hasArc ? (config.subchart_size_height + xAxisHeight) : 0;
  
          $$.currentWidth = $$.getCurrentWidth();
          $$.currentHeight = $$.getCurrentHeight();
  
          // for main
          $$.margin = config.axis_rotated ? {
              top: $$.getHorizontalAxisHeight('y2') + $$.getCurrentPaddingTop(),
              right: hasArc ? 0 : $$.getCurrentPaddingRight(),
              bottom: $$.getHorizontalAxisHeight('y') + legendHeightForBottom + $$.getCurrentPaddingBottom(),
              left: subchartHeight + (hasArc ? 0 : $$.getCurrentPaddingLeft())
          } : {
              top: 4 + $$.getCurrentPaddingTop(), // for top tick text
              right: hasArc ? 0 : $$.getCurrentPaddingRight(),
              bottom: xAxisHeight + subchartHeight + legendHeightForBottom + $$.getCurrentPaddingBottom(),
              left: hasArc ? 0 : $$.getCurrentPaddingLeft()
          };
  
          // for subchart
          $$.margin2 = config.axis_rotated ? {
              top: $$.margin.top,
              right: NaN,
              bottom: 20 + legendHeightForBottom,
              left: $$.rotated_padding_left
          } : {
              top: $$.currentHeight - subchartHeight - legendHeightForBottom,
              right: NaN,
              bottom: xAxisHeight + legendHeightForBottom,
              left: $$.margin.left
          };
  
          // for legend
          $$.margin3 = {
              top: 0,
              right: NaN,
              bottom: 0,
              left: 0
          };
          if ($$.updateSizeForLegend) { $$.updateSizeForLegend(legendHeight, legendWidth); }
  
          $$.width = $$.currentWidth - $$.margin.left - $$.margin.right;
          $$.height = $$.currentHeight - $$.margin.top - $$.margin.bottom;
          if ($$.width < 0) { $$.width = 0; }
          if ($$.height < 0) { $$.height = 0; }
  
          $$.width2 = config.axis_rotated ? $$.margin.left - $$.rotated_padding_left - $$.rotated_padding_right : $$.width;
          $$.height2 = config.axis_rotated ? $$.height : $$.currentHeight - $$.margin2.top - $$.margin2.bottom;
          if ($$.width2 < 0) { $$.width2 = 0; }
          if ($$.height2 < 0) { $$.height2 = 0; }
  
          // for arc
          $$.arcWidth = $$.width - ($$.isLegendRight ? legendWidth + 10 : 0);
          $$.arcHeight = $$.height - ($$.isLegendRight ? 0 : 10);
          if ($$.hasType('gauge')) {
              $$.arcHeight += $$.height - $$.getGaugeLabelHeight();
          }
          if ($$.updateRadius) { $$.updateRadius(); }
  
          if ($$.isLegendRight && hasArc) {
              $$.margin3.left = $$.arcWidth / 2 + $$.radiusExpanded * 1.1;
          }
      };
  
      c3_chart_internal_fn.updateTargets = function (targets) {
          var $$ = this;
  
          /*-- Main --*/
  
          //-- Text --//
          $$.updateTargetsForText(targets);
  
          //-- Bar --//
          $$.updateTargetsForBar(targets);
  
          //-- Line --//
          $$.updateTargetsForLine(targets);
  
          //-- Arc --//
          if ($$.hasArcType() && $$.updateTargetsForArc) { $$.updateTargetsForArc(targets); }
  
          /*-- Sub --*/
  
          if ($$.updateTargetsForSubchart) { $$.updateTargetsForSubchart(targets); }
  
          // Fade-in each chart
          $$.showTargets();
      };
      c3_chart_internal_fn.showTargets = function () {
          var $$ = this;
          $$.svg.selectAll('.' + CLASS.target).filter(function (d) { return $$.isTargetToShow(d.id); })
            .transition().duration($$.config.transition_duration)
              .style("opacity", 1);
      };
  
      c3_chart_internal_fn.redraw = function (options, transitions) {
          var $$ = this, main = $$.main, d3 = $$.d3, config = $$.config;
          var areaIndices = $$.getShapeIndices($$.isAreaType), barIndices = $$.getShapeIndices($$.isBarType), lineIndices = $$.getShapeIndices($$.isLineType);
          var withY, withSubchart, withTransition, withTransitionForExit, withTransitionForAxis,
              withTransform, withUpdateXDomain, withUpdateOrgXDomain, withTrimXDomain, withLegend,
              withEventRect, withDimension, withUpdateXAxis;
          var hideAxis = $$.hasArcType();
          var drawArea, drawBar, drawLine, xForText, yForText;
          var duration, durationForExit, durationForAxis;
          var waitForDraw, flow;
          var targetsToShow = $$.filterTargetsToShow($$.data.targets), tickValues, i, intervalForCulling, xDomainForZoom;
          var xv = $$.xv.bind($$), cx, cy;
  
          options = options || {};
          withY = getOption(options, "withY", true);
          withSubchart = getOption(options, "withSubchart", true);
          withTransition = getOption(options, "withTransition", true);
          withTransform = getOption(options, "withTransform", false);
          withUpdateXDomain = getOption(options, "withUpdateXDomain", false);
          withUpdateOrgXDomain = getOption(options, "withUpdateOrgXDomain", false);
          withTrimXDomain = getOption(options, "withTrimXDomain", true);
          withUpdateXAxis = getOption(options, "withUpdateXAxis", withUpdateXDomain);
          withLegend = getOption(options, "withLegend", false);
          withEventRect = getOption(options, "withEventRect", true);
          withDimension = getOption(options, "withDimension", true);
          withTransitionForExit = getOption(options, "withTransitionForExit", withTransition);
          withTransitionForAxis = getOption(options, "withTransitionForAxis", withTransition);
  
          duration = withTransition ? config.transition_duration : 0;
          durationForExit = withTransitionForExit ? duration : 0;
          durationForAxis = withTransitionForAxis ? duration : 0;
  
          transitions = transitions || $$.axis.generateTransitions(durationForAxis);
  
          // update legend and transform each g
          if (withLegend && config.legend_show) {
              $$.updateLegend($$.mapToIds($$.data.targets), options, transitions);
          } else if (withDimension) {
              // need to update dimension (e.g. axis.y.tick.values) because y tick values should change
              // no need to update axis in it because they will be updated in redraw()
              $$.updateDimension(true);
          }
  
          // MEMO: needed for grids calculation
          if ($$.isCategorized() && targetsToShow.length === 0) {
              $$.x.domain([0, $$.axes.x.selectAll('.tick').size()]);
          }
  
          if (targetsToShow.length) {
              $$.updateXDomain(targetsToShow, withUpdateXDomain, withUpdateOrgXDomain, withTrimXDomain);
              if (!config.axis_x_tick_values) {
                  tickValues = $$.axis.updateXAxisTickValues(targetsToShow);
              }
          } else {
              $$.xAxis.tickValues([]);
              $$.subXAxis.tickValues([]);
          }
  
          if (config.zoom_rescale && !options.flow) {
              xDomainForZoom = $$.x.orgDomain();
          }
  
          $$.y.domain($$.getYDomain(targetsToShow, 'y', xDomainForZoom));
          $$.y2.domain($$.getYDomain(targetsToShow, 'y2', xDomainForZoom));
  
          if (!config.axis_y_tick_values && config.axis_y_tick_count) {
              $$.yAxis.tickValues($$.axis.generateTickValues($$.y.domain(), config.axis_y_tick_count));
          }
          if (!config.axis_y2_tick_values && config.axis_y2_tick_count) {
              $$.y2Axis.tickValues($$.axis.generateTickValues($$.y2.domain(), config.axis_y2_tick_count));
          }
  
          // axes
          $$.axis.redraw(transitions, hideAxis);
  
          // Update axis label
          $$.axis.updateLabels(withTransition);
  
          // show/hide if manual culling needed
          if ((withUpdateXDomain || withUpdateXAxis) && targetsToShow.length) {
              if (config.axis_x_tick_culling && tickValues) {
                  for (i = 1; i < tickValues.length; i++) {
                      if (tickValues.length / i < config.axis_x_tick_culling_max) {
                          intervalForCulling = i;
                          break;
                      }
                  }
                  $$.svg.selectAll('.' + CLASS.axisX + ' .tick text').each(function (e) {
                      var index = tickValues.indexOf(e);
                      if (index >= 0) {
                          d3.select(this).style('display', index % intervalForCulling ? 'none' : 'block');
                      }
                  });
              } else {
                  $$.svg.selectAll('.' + CLASS.axisX + ' .tick text').style('display', 'block');
              }
          }
  
          // setup drawer - MEMO: these must be called after axis updated
          drawArea = $$.generateDrawArea ? $$.generateDrawArea(areaIndices, false) : undefined;
          drawBar = $$.generateDrawBar ? $$.generateDrawBar(barIndices) : undefined;
          drawLine = $$.generateDrawLine ? $$.generateDrawLine(lineIndices, false) : undefined;
          xForText = $$.generateXYForText(areaIndices, barIndices, lineIndices, true);
          yForText = $$.generateXYForText(areaIndices, barIndices, lineIndices, false);
  
          // Update sub domain
          if (withY) {
              $$.subY.domain($$.getYDomain(targetsToShow, 'y'));
              $$.subY2.domain($$.getYDomain(targetsToShow, 'y2'));
          }
  
          // xgrid focus
          $$.updateXgridFocus();
  
          // Data empty label positioning and text.
          main.select("text." + CLASS.text + '.' + CLASS.empty)
              .attr("x", $$.width / 2)
              .attr("y", $$.height / 2)
              .text(config.data_empty_label_text)
            .transition()
              .style('opacity', targetsToShow.length ? 0 : 1);
  
          // grid
          $$.updateGrid(duration);
  
          // rect for regions
          $$.updateRegion(duration);
  
          // bars
          $$.updateBar(durationForExit);
  
          // lines, areas and cricles
          $$.updateLine(durationForExit);
          $$.updateArea(durationForExit);
          $$.updateCircle();
  
          // text
          if ($$.hasDataLabel()) {
              $$.updateText(durationForExit);
          }
  
          // title
          if ($$.redrawTitle) { $$.redrawTitle(); }
  
          // arc
          if ($$.redrawArc) { $$.redrawArc(duration, durationForExit, withTransform); }
  
          // subchart
          if ($$.redrawSubchart) {
              $$.redrawSubchart(withSubchart, transitions, duration, durationForExit, areaIndices, barIndices, lineIndices);
          }
  
          // circles for select
          main.selectAll('.' + CLASS.selectedCircles)
              .filter($$.isBarType.bind($$))
              .selectAll('circle')
              .remove();
  
          // event rects will redrawn when flow called
          if (config.interaction_enabled && !options.flow && withEventRect) {
              $$.redrawEventRect();
              if ($$.updateZoom) { $$.updateZoom(); }
          }
  
          // update circleY based on updated parameters
          $$.updateCircleY();
  
          // generate circle x/y functions depending on updated params
          cx = ($$.config.axis_rotated ? $$.circleY : $$.circleX).bind($$);
          cy = ($$.config.axis_rotated ? $$.circleX : $$.circleY).bind($$);
  
          if (options.flow) {
              flow = $$.generateFlow({
                  targets: targetsToShow,
                  flow: options.flow,
                  duration: options.flow.duration,
                  drawBar: drawBar,
                  drawLine: drawLine,
                  drawArea: drawArea,
                  cx: cx,
                  cy: cy,
                  xv: xv,
                  xForText: xForText,
                  yForText: yForText
              });
          }
  
          if ((duration || flow) && $$.isTabVisible()) { // Only use transition if tab visible. See #938.
              // transition should be derived from one transition
              d3.transition().duration(duration).each(function () {
                  var transitionsToWait = [];
  
                  // redraw and gather transitions
                  [
                      $$.redrawBar(drawBar, true),
                      $$.redrawLine(drawLine, true),
                      $$.redrawArea(drawArea, true),
                      $$.redrawCircle(cx, cy, true),
                      $$.redrawText(xForText, yForText, options.flow, true),
                      $$.redrawRegion(true),
                      $$.redrawGrid(true),
                  ].forEach(function (transitions) {
                      transitions.forEach(function (transition) {
                          transitionsToWait.push(transition);
                      });
                  });
  
                  // Wait for end of transitions to call flow and onrendered callback
                  waitForDraw = $$.generateWait();
                  transitionsToWait.forEach(function (t) {
                      waitForDraw.add(t);
                  });
              })
              .call(waitForDraw, function () {
                  if (flow) {
                      flow();
                  }
                  if (config.onrendered) {
                      config.onrendered.call($$);
                  }
              });
          }
          else {
              $$.redrawBar(drawBar);
              $$.redrawLine(drawLine);
              $$.redrawArea(drawArea);
              $$.redrawCircle(cx, cy);
              $$.redrawText(xForText, yForText, options.flow);
              $$.redrawRegion();
              $$.redrawGrid();
              if (config.onrendered) {
                  config.onrendered.call($$);
              }
          }
  
          // update fadein condition
          $$.mapToIds($$.data.targets).forEach(function (id) {
              $$.withoutFadeIn[id] = true;
          });
      };
  
      c3_chart_internal_fn.updateAndRedraw = function (options) {
          var $$ = this, config = $$.config, transitions;
          options = options || {};
          // same with redraw
          options.withTransition = getOption(options, "withTransition", true);
          options.withTransform = getOption(options, "withTransform", false);
          options.withLegend = getOption(options, "withLegend", false);
          // NOT same with redraw
          options.withUpdateXDomain = true;
          options.withUpdateOrgXDomain = true;
          options.withTransitionForExit = false;
          options.withTransitionForTransform = getOption(options, "withTransitionForTransform", options.withTransition);
          // MEMO: this needs to be called before updateLegend and it means this ALWAYS needs to be called)
          $$.updateSizes();
          // MEMO: called in updateLegend in redraw if withLegend
          if (!(options.withLegend && config.legend_show)) {
              transitions = $$.axis.generateTransitions(options.withTransitionForAxis ? config.transition_duration : 0);
              // Update scales
              $$.updateScales();
              $$.updateSvgSize();
              // Update g positions
              $$.transformAll(options.withTransitionForTransform, transitions);
          }
          // Draw with new sizes & scales
          $$.redraw(options, transitions);
      };
      c3_chart_internal_fn.redrawWithoutRescale = function () {
          this.redraw({
              withY: false,
              withSubchart: false,
              withEventRect: false,
              withTransitionForAxis: false
          });
      };
  
      c3_chart_internal_fn.isTimeSeries = function () {
          return this.config.axis_x_type === 'timeseries';
      };
      c3_chart_internal_fn.isCategorized = function () {
          return this.config.axis_x_type.indexOf('categor') >= 0;
      };
      c3_chart_internal_fn.isCustomX = function () {
          var $$ = this, config = $$.config;
          return !$$.isTimeSeries() && (config.data_x || notEmpty(config.data_xs));
      };
  
      c3_chart_internal_fn.isTimeSeriesY = function () {
          return this.config.axis_y_type === 'timeseries';
      };
  
      c3_chart_internal_fn.getTranslate = function (target) {
          var $$ = this, config = $$.config, x, y;
          if (target === 'main') {
              x = asHalfPixel($$.margin.left);
              y = asHalfPixel($$.margin.top);
          } else if (target === 'context') {
              x = asHalfPixel($$.margin2.left);
              y = asHalfPixel($$.margin2.top);
          } else if (target === 'legend') {
              x = $$.margin3.left;
              y = $$.margin3.top;
          } else if (target === 'x') {
              x = 0;
              y = config.axis_rotated ? 0 : $$.height;
          } else if (target === 'y') {
              x = 0;
              y = config.axis_rotated ? $$.height : 0;
          } else if (target === 'y2') {
              x = config.axis_rotated ? 0 : $$.width;
              y = config.axis_rotated ? 1 : 0;
          } else if (target === 'subx') {
              x = 0;
              y = config.axis_rotated ? 0 : $$.height2;
          } else if (target === 'arc') {
              x = $$.arcWidth / 2;
              y = $$.arcHeight / 2;
          }
          return "translate(" + x + "," + y + ")";
      };
      c3_chart_internal_fn.initialOpacity = function (d) {
          return d.value !== null && this.withoutFadeIn[d.id] ? 1 : 0;
      };
      c3_chart_internal_fn.initialOpacityForCircle = function (d) {
          return d.value !== null && this.withoutFadeIn[d.id] ? this.opacityForCircle(d) : 0;
      };
      c3_chart_internal_fn.opacityForCircle = function (d) {
          var opacity = this.config.point_show ? 1 : 0;
          return isValue(d.value) ? (this.isScatterType(d) ? 0.5 : opacity) : 0;
      };
      c3_chart_internal_fn.opacityForText = function () {
          return this.hasDataLabel() ? 1 : 0;
      };
      c3_chart_internal_fn.xx = function (d) {
          return d ? this.x(d.x) : null;
      };
      c3_chart_internal_fn.xv = function (d) {
          var $$ = this, value = d.value;
          if ($$.isTimeSeries()) {
              value = $$.parseDate(d.value);
          }
          else if ($$.isCategorized() && typeof d.value === 'string') {
              value = $$.config.axis_x_categories.indexOf(d.value);
          }
          return Math.ceil($$.x(value));
      };
      c3_chart_internal_fn.yv = function (d) {
          var $$ = this,
              yScale = d.axis && d.axis === 'y2' ? $$.y2 : $$.y;
          return Math.ceil(yScale(d.value));
      };
      c3_chart_internal_fn.subxx = function (d) {
          return d ? this.subX(d.x) : null;
      };
  
      c3_chart_internal_fn.transformMain = function (withTransition, transitions) {
          var $$ = this,
              xAxis, yAxis, y2Axis;
          if (transitions && transitions.axisX) {
              xAxis = transitions.axisX;
          } else {
              xAxis  = $$.main.select('.' + CLASS.axisX);
              if (withTransition) { xAxis = xAxis.transition(); }
          }
          if (transitions && transitions.axisY) {
              yAxis = transitions.axisY;
          } else {
              yAxis = $$.main.select('.' + CLASS.axisY);
              if (withTransition) { yAxis = yAxis.transition(); }
          }
          if (transitions && transitions.axisY2) {
              y2Axis = transitions.axisY2;
          } else {
              y2Axis = $$.main.select('.' + CLASS.axisY2);
              if (withTransition) { y2Axis = y2Axis.transition(); }
          }
          (withTransition ? $$.main.transition() : $$.main).attr("transform", $$.getTranslate('main'));
          xAxis.attr("transform", $$.getTranslate('x'));
          yAxis.attr("transform", $$.getTranslate('y'));
          y2Axis.attr("transform", $$.getTranslate('y2'));
          $$.main.select('.' + CLASS.chartArcs).attr("transform", $$.getTranslate('arc'));
      };
      c3_chart_internal_fn.transformAll = function (withTransition, transitions) {
          var $$ = this;
          $$.transformMain(withTransition, transitions);
          if ($$.config.subchart_show) { $$.transformContext(withTransition, transitions); }
          if ($$.legend) { $$.transformLegend(withTransition); }
      };
  
      c3_chart_internal_fn.updateSvgSize = function () {
          var $$ = this,
              brush = $$.svg.select(".c3-brush .background");
          $$.svg.attr('width', $$.currentWidth).attr('height', $$.currentHeight);
          $$.svg.selectAll(['#' + $$.clipId, '#' + $$.clipIdForGrid]).select('rect')
              .attr('width', $$.width)
              .attr('height', $$.height);
          $$.svg.select('#' + $$.clipIdForXAxis).select('rect')
              .attr('x', $$.getXAxisClipX.bind($$))
              .attr('y', $$.getXAxisClipY.bind($$))
              .attr('width', $$.getXAxisClipWidth.bind($$))
              .attr('height', $$.getXAxisClipHeight.bind($$));
          $$.svg.select('#' + $$.clipIdForYAxis).select('rect')
              .attr('x', $$.getYAxisClipX.bind($$))
              .attr('y', $$.getYAxisClipY.bind($$))
              .attr('width', $$.getYAxisClipWidth.bind($$))
              .attr('height', $$.getYAxisClipHeight.bind($$));
          $$.svg.select('#' + $$.clipIdForSubchart).select('rect')
              .attr('width', $$.width)
              .attr('height', brush.size() ? brush.attr('height') : 0);
          $$.svg.select('.' + CLASS.zoomRect)
              .attr('width', $$.width)
              .attr('height', $$.height);
          // MEMO: parent div's height will be bigger than svg when <!DOCTYPE html>
          $$.selectChart.style('max-height', $$.currentHeight + "px");
      };
  
  
      c3_chart_internal_fn.updateDimension = function (withoutAxis) {
          var $$ = this;
          if (!withoutAxis) {
              if ($$.config.axis_rotated) {
                  $$.axes.x.call($$.xAxis);
                  $$.axes.subx.call($$.subXAxis);
              } else {
                  $$.axes.y.call($$.yAxis);
                  $$.axes.y2.call($$.y2Axis);
              }
          }
          $$.updateSizes();
          $$.updateScales();
          $$.updateSvgSize();
          $$.transformAll(false);
      };
  
      c3_chart_internal_fn.observeInserted = function (selection) {
          var $$ = this, observer;
          if (typeof MutationObserver === 'undefined') {
              window.console.error("MutationObserver not defined.");
              return;
          }
          observer= new MutationObserver(function (mutations) {
              mutations.forEach(function (mutation) {
                  if (mutation.type === 'childList' && mutation.previousSibling) {
                      observer.disconnect();
                      // need to wait for completion of load because size calculation requires the actual sizes determined after that completion
                      $$.intervalForObserveInserted = window.setInterval(function () {
                          // parentNode will NOT be null when completed
                          if (selection.node().parentNode) {
                              window.clearInterval($$.intervalForObserveInserted);
                              $$.updateDimension();
                              if ($$.brush) { $$.brush.update(); }
                              $$.config.oninit.call($$);
                              $$.redraw({
                                  withTransform: true,
                                  withUpdateXDomain: true,
                                  withUpdateOrgXDomain: true,
                                  withTransition: false,
                                  withTransitionForTransform: false,
                                  withLegend: true
                              });
                              selection.transition().style('opacity', 1);
                          }
                      }, 10);
                  }
              });
          });
          observer.observe(selection.node(), {attributes: true, childList: true, characterData: true});
      };
  
      c3_chart_internal_fn.bindResize = function () {
          var $$ = this, config = $$.config;
  
          $$.resizeFunction = $$.generateResize();
  
          $$.resizeFunction.add(function () {
              config.onresize.call($$);
          });
          if (config.resize_auto) {
              $$.resizeFunction.add(function () {
                  if ($$.resizeTimeout !== undefined) {
                      window.clearTimeout($$.resizeTimeout);
                  }
                  $$.resizeTimeout = window.setTimeout(function () {
                      delete $$.resizeTimeout;
                      $$.api.flush();
                  }, 100);
              });
          }
          $$.resizeFunction.add(function () {
              config.onresized.call($$);
          });
  
          if (window.attachEvent) {
              window.attachEvent('onresize', $$.resizeFunction);
          } else if (window.addEventListener) {
              window.addEventListener('resize', $$.resizeFunction, false);
          } else {
              // fallback to this, if this is a very old browser
              var wrapper = window.onresize;
              if (!wrapper) {
                  // create a wrapper that will call all charts
                  wrapper = $$.generateResize();
              } else if (!wrapper.add || !wrapper.remove) {
                  // there is already a handler registered, make sure we call it too
                  wrapper = $$.generateResize();
                  wrapper.add(window.onresize);
              }
              // add this graph to the wrapper, we will be removed if the user calls destroy
              wrapper.add($$.resizeFunction);
              window.onresize = wrapper;
          }
      };
  
      c3_chart_internal_fn.generateResize = function () {
          var resizeFunctions = [];
          function callResizeFunctions() {
              resizeFunctions.forEach(function (f) {
                  f();
              });
          }
          callResizeFunctions.add = function (f) {
              resizeFunctions.push(f);
          };
          callResizeFunctions.remove = function (f) {
              for (var i = 0; i < resizeFunctions.length; i++) {
                  if (resizeFunctions[i] === f) {
                      resizeFunctions.splice(i, 1);
                      break;
                  }
              }
          };
          return callResizeFunctions;
      };
  
      c3_chart_internal_fn.endall = function (transition, callback) {
          var n = 0;
          transition
              .each(function () { ++n; })
              .each("end", function () {
                  if (!--n) { callback.apply(this, arguments); }
              });
      };
      c3_chart_internal_fn.generateWait = function () {
          var transitionsToWait = [],
              f = function (transition, callback) {
                  var timer = setInterval(function () {
                      var done = 0;
                      transitionsToWait.forEach(function (t) {
                          if (t.empty()) {
                              done += 1;
                              return;
                          }
                          try {
                              t.transition();
                          } catch (e) {
                              done += 1;
                          }
                      });
                      if (done === transitionsToWait.length) {
                          clearInterval(timer);
                          if (callback) { callback(); }
                      }
                  }, 10);
              };
          f.add = function (transition) {
              transitionsToWait.push(transition);
          };
          return f;
      };
  
      c3_chart_internal_fn.parseDate = function (date) {
          var $$ = this, parsedDate;
          if (date instanceof Date) {
              parsedDate = date;
          } else if (typeof date === 'string') {
              parsedDate = $$.dataTimeFormat($$.config.data_xFormat).parse(date);
          } else if (typeof date === 'number' && !isNaN(date)) {
              parsedDate = new Date(+date);
          }
          if (!parsedDate || isNaN(+parsedDate)) {
              window.console.error("Failed to parse x '" + date + "' to Date object");
          }
          return parsedDate;
      };
  
      c3_chart_internal_fn.isTabVisible = function () {
          var hidden;
          if (typeof document.hidden !== "undefined") { // Opera 12.10 and Firefox 18 and later support
              hidden = "hidden";
          } else if (typeof document.mozHidden !== "undefined") {
              hidden = "mozHidden";
          } else if (typeof document.msHidden !== "undefined") {
              hidden = "msHidden";
          } else if (typeof document.webkitHidden !== "undefined") {
              hidden = "webkitHidden";
          }
  
          return document[hidden] ? false : true;
      };
  
      c3_chart_internal_fn.getDefaultConfig = function () {
          var config = {
              bindto: '#chart',
              size_width: undefined,
              size_height: undefined,
              padding_left: undefined,
              padding_right: undefined,
              padding_top: undefined,
              padding_bottom: undefined,
              resize_auto: true,
              zoom_enabled: false,
              zoom_extent: undefined,
              zoom_privileged: false,
              zoom_rescale: false,
              zoom_onzoom: function () {},
              zoom_onzoomstart: function () {},
              zoom_onzoomend: function () {},
              zoom_x_min: undefined,
              zoom_x_max: undefined,
              interaction_enabled: true,
              onmouseover: function () {},
              onmouseout: function () {},
              onresize: function () {},
              onresized: function () {},
              oninit: function () {},
              onrendered: function () {},
              transition_duration: 350,
              data_x: undefined,
              data_xs: {},
              data_xFormat: '%Y-%m-%d',
              data_xLocaltime: true,
              data_xSort: true,
              data_idConverter: function (id) { return id; },
              data_names: {},
              data_classes: {},
              data_groups: [],
              data_axes: {},
              data_type: undefined,
              data_types: {},
              data_labels: {},
              data_order: 'desc',
              data_regions: {},
              data_color: undefined,
              data_colors: {},
              data_hide: false,
              data_filter: undefined,
              data_selection_enabled: false,
              data_selection_grouped: false,
              data_selection_isselectable: function () { return true; },
              data_selection_multiple: true,
              data_selection_draggable: false,
              data_onclick: function () {},
              data_onmouseover: function () {},
              data_onmouseout: function () {},
              data_onselected: function () {},
              data_onunselected: function () {},
              data_url: undefined,
              data_json: undefined,
              data_rows: undefined,
              data_columns: undefined,
              data_mimeType: undefined,
              data_keys: undefined,
              // configuration for no plot-able data supplied.
              data_empty_label_text: "",
              // subchart
              subchart_show: false,
              subchart_size_height: 60,
              subchart_axis_x_show: true,
              subchart_onbrush: function () {},
              // color
              color_pattern: [],
              color_threshold: {},
              // legend
              legend_show: true,
              legend_hide: false,
              legend_position: 'bottom',
              legend_inset_anchor: 'top-left',
              legend_inset_x: 10,
              legend_inset_y: 0,
              legend_inset_step: undefined,
              legend_item_onclick: undefined,
              legend_item_onmouseover: undefined,
              legend_item_onmouseout: undefined,
              legend_equally: false,
              legend_padding: 0,
              legend_item_tile_width: 10,
              legend_item_tile_height: 10,
              // axis
              axis_rotated: false,
              axis_x_show: true,
              axis_x_type: 'indexed',
              axis_x_localtime: true,
              axis_x_categories: [],
              axis_x_tick_centered: false,
              axis_x_tick_format: undefined,
              axis_x_tick_culling: {},
              axis_x_tick_culling_max: 10,
              axis_x_tick_count: undefined,
              axis_x_tick_fit: true,
              axis_x_tick_values: null,
              axis_x_tick_rotate: 0,
              axis_x_tick_outer: true,
              axis_x_tick_multiline: true,
              axis_x_tick_width: null,
              axis_x_max: undefined,
              axis_x_min: undefined,
              axis_x_padding: {},
              axis_x_height: undefined,
              axis_x_extent: undefined,
              axis_x_label: {},
              axis_y_show: true,
              axis_y_type: undefined,
              axis_y_max: undefined,
              axis_y_min: undefined,
              axis_y_inverted: false,
              axis_y_center: undefined,
              axis_y_inner: undefined,
              axis_y_label: {},
              axis_y_tick_format: undefined,
              axis_y_tick_outer: true,
              axis_y_tick_values: null,
              axis_y_tick_count: undefined,
              axis_y_tick_time_value: undefined,
              axis_y_tick_time_interval: undefined,
              axis_y_padding: {},
              axis_y_default: undefined,
              axis_y2_show: false,
              axis_y2_max: undefined,
              axis_y2_min: undefined,
              axis_y2_inverted: false,
              axis_y2_center: undefined,
              axis_y2_inner: undefined,
              axis_y2_label: {},
              axis_y2_tick_format: undefined,
              axis_y2_tick_outer: true,
              axis_y2_tick_values: null,
              axis_y2_tick_count: undefined,
              axis_y2_padding: {},
              axis_y2_default: undefined,
              // grid
              grid_x_show: false,
              grid_x_type: 'tick',
              grid_x_lines: [],
              grid_y_show: false,
              // not used
              // grid_y_type: 'tick',
              grid_y_lines: [],
              grid_y_ticks: 10,
              grid_focus_show: true,
              grid_lines_front: true,
              // point - point of each data
              point_show: true,
              point_r: 2.5,
              point_sensitivity: 10,
              point_focus_expand_enabled: true,
              point_focus_expand_r: undefined,
              point_select_r: undefined,
              // line
              line_connectNull: false,
              line_step_type: 'step',
              // bar
              bar_width: undefined,
              bar_width_ratio: 0.6,
              bar_width_max: undefined,
              bar_zerobased: true,
              // area
              area_zerobased: true,
              // pie
              pie_label_show: true,
              pie_label_format: undefined,
              pie_label_threshold: 0.05,
              pie_expand: {},
              pie_expand_duration: 50,
              // gauge
              gauge_label_show: true,
              gauge_label_format: undefined,
              gauge_min: 0,
              gauge_max: 100,
              gauge_units: undefined,
              gauge_width: undefined,
              gauge_expand: {},
              gauge_expand_duration: 50,
              // donut
              donut_label_show: true,
              donut_label_format: undefined,
              donut_label_threshold: 0.05,
              donut_width: undefined,
              donut_title: "",
              donut_expand: {},
              donut_expand_duration: 50,
              // spline
              spline_interpolation_type: 'cardinal',
              // region - region to change style
              regions: [],
              // tooltip - show when mouseover on each data
              tooltip_show: true,
              tooltip_grouped: true,
              tooltip_format_title: undefined,
              tooltip_format_name: undefined,
              tooltip_format_value: undefined,
              tooltip_position: undefined,
              tooltip_contents: function (d, defaultTitleFormat, defaultValueFormat, color) {
                  return this.getTooltipContent ? this.getTooltipContent(d, defaultTitleFormat, defaultValueFormat, color) : '';
              },
              tooltip_init_show: false,
              tooltip_init_x: 0,
              tooltip_init_position: {top: '0px', left: '50px'},
              tooltip_onshow: function () {},
              tooltip_onhide: function () {},
              // title
              title_text: undefined,
              title_padding: {
                  top: 0,
                  right: 0,
                  bottom: 0,
                  left: 0
              },
              title_position: 'top-center',
          };
  
          Object.keys(this.additionalConfig).forEach(function (key) {
              config[key] = this.additionalConfig[key];
          }, this);
  
          return config;
      };
      c3_chart_internal_fn.additionalConfig = {};
  
      c3_chart_internal_fn.loadConfig = function (config) {
          var this_config = this.config, target, keys, read;
          function find() {
              var key = keys.shift();
      //        console.log("key =>", key, ", target =>", target);
              if (key && target && typeof target === 'object' && key in target) {
                  target = target[key];
                  return find();
              }
              else if (!key) {
                  return target;
              }
              else {
                  return undefined;
              }
          }
          Object.keys(this_config).forEach(function (key) {
              target = config;
              keys = key.split('_');
              read = find();
      //        console.log("CONFIG : ", key, read);
              if (isDefined(read)) {
                  this_config[key] = read;
              }
          });
      };
  
      c3_chart_internal_fn.getScale = function (min, max, forTimeseries) {
          return (forTimeseries ? this.d3.time.scale() : this.d3.scale.linear()).range([min, max]);
      };
      c3_chart_internal_fn.getX = function (min, max, domain, offset) {
          var $$ = this,
              scale = $$.getScale(min, max, $$.isTimeSeries()),
              _scale = domain ? scale.domain(domain) : scale, key;
          // Define customized scale if categorized axis
          if ($$.isCategorized()) {
              offset = offset || function () { return 0; };
              scale = function (d, raw) {
                  var v = _scale(d) + offset(d);
                  return raw ? v : Math.ceil(v);
              };
          } else {
              scale = function (d, raw) {
                  var v = _scale(d);
                  return raw ? v : Math.ceil(v);
              };
          }
          // define functions
          for (key in _scale) {
              scale[key] = _scale[key];
          }
          scale.orgDomain = function () {
              return _scale.domain();
          };
          // define custom domain() for categorized axis
          if ($$.isCategorized()) {
              scale.domain = function (domain) {
                  if (!arguments.length) {
                      domain = this.orgDomain();
                      return [domain[0], domain[1] + 1];
                  }
                  _scale.domain(domain);
                  return scale;
              };
          }
          return scale;
      };
      c3_chart_internal_fn.getY = function (min, max, domain) {
          var scale = this.getScale(min, max, this.isTimeSeriesY());
          if (domain) { scale.domain(domain); }
          return scale;
      };
      c3_chart_internal_fn.getYScale = function (id) {
          return this.axis.getId(id) === 'y2' ? this.y2 : this.y;
      };
      c3_chart_internal_fn.getSubYScale = function (id) {
          return this.axis.getId(id) === 'y2' ? this.subY2 : this.subY;
      };
      c3_chart_internal_fn.updateScales = function () {
          var $$ = this, config = $$.config,
              forInit = !$$.x;
          // update edges
          $$.xMin = config.axis_rotated ? 1 : 0;
          $$.xMax = config.axis_rotated ? $$.height : $$.width;
          $$.yMin = config.axis_rotated ? 0 : $$.height;
          $$.yMax = config.axis_rotated ? $$.width : 1;
          $$.subXMin = $$.xMin;
          $$.subXMax = $$.xMax;
          $$.subYMin = config.axis_rotated ? 0 : $$.height2;
          $$.subYMax = config.axis_rotated ? $$.width2 : 1;
          // update scales
          $$.x = $$.getX($$.xMin, $$.xMax, forInit ? undefined : $$.x.orgDomain(), function () { return $$.xAxis.tickOffset(); });
          $$.y = $$.getY($$.yMin, $$.yMax, forInit ? config.axis_y_default : $$.y.domain());
          $$.y2 = $$.getY($$.yMin, $$.yMax, forInit ? config.axis_y2_default : $$.y2.domain());
          $$.subX = $$.getX($$.xMin, $$.xMax, $$.orgXDomain, function (d) { return d % 1 ? 0 : $$.subXAxis.tickOffset(); });
          $$.subY = $$.getY($$.subYMin, $$.subYMax, forInit ? config.axis_y_default : $$.subY.domain());
          $$.subY2 = $$.getY($$.subYMin, $$.subYMax, forInit ? config.axis_y2_default : $$.subY2.domain());
          // update axes
          $$.xAxisTickFormat = $$.axis.getXAxisTickFormat();
          $$.xAxisTickValues = $$.axis.getXAxisTickValues();
          $$.yAxisTickValues = $$.axis.getYAxisTickValues();
          $$.y2AxisTickValues = $$.axis.getY2AxisTickValues();
  
          $$.xAxis = $$.axis.getXAxis($$.x, $$.xOrient, $$.xAxisTickFormat, $$.xAxisTickValues, config.axis_x_tick_outer);
          $$.subXAxis = $$.axis.getXAxis($$.subX, $$.subXOrient, $$.xAxisTickFormat, $$.xAxisTickValues, config.axis_x_tick_outer);
          $$.yAxis = $$.axis.getYAxis($$.y, $$.yOrient, config.axis_y_tick_format, $$.yAxisTickValues, config.axis_y_tick_outer);
          $$.y2Axis = $$.axis.getYAxis($$.y2, $$.y2Orient, config.axis_y2_tick_format, $$.y2AxisTickValues, config.axis_y2_tick_outer);
  
          // Set initialized scales to brush and zoom
          if (!forInit) {
              if ($$.brush) { $$.brush.scale($$.subX); }
              if (config.zoom_enabled) { $$.zoom.scale($$.x); }
          }
          // update for arc
          if ($$.updateArc) { $$.updateArc(); }
      };
  
      c3_chart_internal_fn.getYDomainMin = function (targets) {
          var $$ = this, config = $$.config,
              ids = $$.mapToIds(targets), ys = $$.getValuesAsIdKeyed(targets),
              j, k, baseId, idsInGroup, id, hasNegativeValue;
          if (config.data_groups.length > 0) {
              hasNegativeValue = $$.hasNegativeValueInTargets(targets);
              for (j = 0; j < config.data_groups.length; j++) {
                  // Determine baseId
                  idsInGroup = config.data_groups[j].filter(function (id) { return ids.indexOf(id) >= 0; });
                  if (idsInGroup.length === 0) { continue; }
                  baseId = idsInGroup[0];
                  // Consider negative values
                  if (hasNegativeValue && ys[baseId]) {
                      ys[baseId].forEach(function (v, i) {
                          ys[baseId][i] = v < 0 ? v : 0;
                      });
                  }
                  // Compute min
                  for (k = 1; k < idsInGroup.length; k++) {
                      id = idsInGroup[k];
                      if (! ys[id]) { continue; }
                      ys[id].forEach(function (v, i) {
                          if ($$.axis.getId(id) === $$.axis.getId(baseId) && ys[baseId] && !(hasNegativeValue && +v > 0)) {
                              ys[baseId][i] += +v;
                          }
                      });
                  }
              }
          }
          return $$.d3.min(Object.keys(ys).map(function (key) { return $$.d3.min(ys[key]); }));
      };
      c3_chart_internal_fn.getYDomainMax = function (targets) {
          var $$ = this, config = $$.config,
              ids = $$.mapToIds(targets), ys = $$.getValuesAsIdKeyed(targets),
              j, k, baseId, idsInGroup, id, hasPositiveValue;
          if (config.data_groups.length > 0) {
              hasPositiveValue = $$.hasPositiveValueInTargets(targets);
              for (j = 0; j < config.data_groups.length; j++) {
                  // Determine baseId
                  idsInGroup = config.data_groups[j].filter(function (id) { return ids.indexOf(id) >= 0; });
                  if (idsInGroup.length === 0) { continue; }
                  baseId = idsInGroup[0];
                  // Consider positive values
                  if (hasPositiveValue && ys[baseId]) {
                      ys[baseId].forEach(function (v, i) {
                          ys[baseId][i] = v > 0 ? v : 0;
                      });
                  }
                  // Compute max
                  for (k = 1; k < idsInGroup.length; k++) {
                      id = idsInGroup[k];
                      if (! ys[id]) { continue; }
                      ys[id].forEach(function (v, i) {
                          if ($$.axis.getId(id) === $$.axis.getId(baseId) && ys[baseId] && !(hasPositiveValue && +v < 0)) {
                              ys[baseId][i] += +v;
                          }
                      });
                  }
              }
          }
          return $$.d3.max(Object.keys(ys).map(function (key) { return $$.d3.max(ys[key]); }));
      };
      c3_chart_internal_fn.getYDomain = function (targets, axisId, xDomain) {
          var $$ = this, config = $$.config,
              targetsByAxisId = targets.filter(function (t) { return $$.axis.getId(t.id) === axisId; }),
              yTargets = xDomain ? $$.filterByXDomain(targetsByAxisId, xDomain) : targetsByAxisId,
              yMin = axisId === 'y2' ? config.axis_y2_min : config.axis_y_min,
              yMax = axisId === 'y2' ? config.axis_y2_max : config.axis_y_max,
              yDomainMin = $$.getYDomainMin(yTargets),
              yDomainMax = $$.getYDomainMax(yTargets),
              domain, domainLength, padding, padding_top, padding_bottom,
              center = axisId === 'y2' ? config.axis_y2_center : config.axis_y_center,
              yDomainAbs, lengths, diff, ratio, isAllPositive, isAllNegative,
              isZeroBased = ($$.hasType('bar', yTargets) && config.bar_zerobased) || ($$.hasType('area', yTargets) && config.area_zerobased),
              isInverted = axisId === 'y2' ? config.axis_y2_inverted : config.axis_y_inverted,
              showHorizontalDataLabel = $$.hasDataLabel() && config.axis_rotated,
              showVerticalDataLabel = $$.hasDataLabel() && !config.axis_rotated;
  
          // MEMO: avoid inverting domain unexpectedly
          yDomainMin = isValue(yMin) ? yMin : isValue(yMax) ? (yDomainMin < yMax ? yDomainMin : yMax - 10) : yDomainMin;
          yDomainMax = isValue(yMax) ? yMax : isValue(yMin) ? (yMin < yDomainMax ? yDomainMax : yMin + 10) : yDomainMax;
  
          if (yTargets.length === 0) { // use current domain if target of axisId is none
              return axisId === 'y2' ? $$.y2.domain() : $$.y.domain();
          }
          if (isNaN(yDomainMin)) { // set minimum to zero when not number
              yDomainMin = 0;
          }
          if (isNaN(yDomainMax)) { // set maximum to have same value as yDomainMin
              yDomainMax = yDomainMin;
          }
          if (yDomainMin === yDomainMax) {
              yDomainMin < 0 ? yDomainMax = 0 : yDomainMin = 0;
          }
          isAllPositive = yDomainMin >= 0 && yDomainMax >= 0;
          isAllNegative = yDomainMin <= 0 && yDomainMax <= 0;
  
          // Cancel zerobased if axis_*_min / axis_*_max specified
          if ((isValue(yMin) && isAllPositive) || (isValue(yMax) && isAllNegative)) {
              isZeroBased = false;
          }
  
          // Bar/Area chart should be 0-based if all positive|negative
          if (isZeroBased) {
              if (isAllPositive) { yDomainMin = 0; }
              if (isAllNegative) { yDomainMax = 0; }
          }
  
          domainLength = Math.abs(yDomainMax - yDomainMin);
          padding = padding_top = padding_bottom = domainLength * 0.1;
  
          if (typeof center !== 'undefined') {
              yDomainAbs = Math.max(Math.abs(yDomainMin), Math.abs(yDomainMax));
              yDomainMax = center + yDomainAbs;
              yDomainMin = center - yDomainAbs;
          }
          // add padding for data label
          if (showHorizontalDataLabel) {
              lengths = $$.getDataLabelLength(yDomainMin, yDomainMax, 'width');
              diff = diffDomain($$.y.range());
              ratio = [lengths[0] / diff, lengths[1] / diff];
              padding_top += domainLength * (ratio[1] / (1 - ratio[0] - ratio[1]));
              padding_bottom += domainLength * (ratio[0] / (1 - ratio[0] - ratio[1]));
          } else if (showVerticalDataLabel) {
              lengths = $$.getDataLabelLength(yDomainMin, yDomainMax, 'height');
              padding_top += $$.axis.convertPixelsToAxisPadding(lengths[1], domainLength);
              padding_bottom += $$.axis.convertPixelsToAxisPadding(lengths[0], domainLength);
          }
          if (axisId === 'y' && notEmpty(config.axis_y_padding)) {
              padding_top = $$.axis.getPadding(config.axis_y_padding, 'top', padding_top, domainLength);
              padding_bottom = $$.axis.getPadding(config.axis_y_padding, 'bottom', padding_bottom, domainLength);
          }
          if (axisId === 'y2' && notEmpty(config.axis_y2_padding)) {
              padding_top = $$.axis.getPadding(config.axis_y2_padding, 'top', padding_top, domainLength);
              padding_bottom = $$.axis.getPadding(config.axis_y2_padding, 'bottom', padding_bottom, domainLength);
          }
          // Bar/Area chart should be 0-based if all positive|negative
          if (isZeroBased) {
              if (isAllPositive) { padding_bottom = yDomainMin; }
              if (isAllNegative) { padding_top = -yDomainMax; }
          }
          domain = [yDomainMin - padding_bottom, yDomainMax + padding_top];
          return isInverted ? domain.reverse() : domain;
      };
      c3_chart_internal_fn.getXDomainMin = function (targets) {
          var $$ = this, config = $$.config;
          return isDefined(config.axis_x_min) ?
              ($$.isTimeSeries() ? this.parseDate(config.axis_x_min) : config.axis_x_min) :
          $$.d3.min(targets, function (t) { return $$.d3.min(t.values, function (v) { return v.x; }); });
      };
      c3_chart_internal_fn.getXDomainMax = function (targets) {
          var $$ = this, config = $$.config;
          return isDefined(config.axis_x_max) ?
              ($$.isTimeSeries() ? this.parseDate(config.axis_x_max) : config.axis_x_max) :
          $$.d3.max(targets, function (t) { return $$.d3.max(t.values, function (v) { return v.x; }); });
      };
      c3_chart_internal_fn.getXDomainPadding = function (domain) {
          var $$ = this, config = $$.config,
              diff = domain[1] - domain[0],
              maxDataCount, padding, paddingLeft, paddingRight;
          if ($$.isCategorized()) {
              padding = 0;
          } else if ($$.hasType('bar')) {
              maxDataCount = $$.getMaxDataCount();
              padding = maxDataCount > 1 ? (diff / (maxDataCount - 1)) / 2 : 0.5;
          } else {
              padding = diff * 0.01;
          }
          if (typeof config.axis_x_padding === 'object' && notEmpty(config.axis_x_padding)) {
              paddingLeft = isValue(config.axis_x_padding.left) ? config.axis_x_padding.left : padding;
              paddingRight = isValue(config.axis_x_padding.right) ? config.axis_x_padding.right : padding;
          } else if (typeof config.axis_x_padding === 'number') {
              paddingLeft = paddingRight = config.axis_x_padding;
          } else {
              paddingLeft = paddingRight = padding;
          }
          return {left: paddingLeft, right: paddingRight};
      };
      c3_chart_internal_fn.getXDomain = function (targets) {
          var $$ = this,
              xDomain = [$$.getXDomainMin(targets), $$.getXDomainMax(targets)],
              firstX = xDomain[0], lastX = xDomain[1],
              padding = $$.getXDomainPadding(xDomain),
              min = 0, max = 0;
          // show center of x domain if min and max are the same
          if ((firstX - lastX) === 0 && !$$.isCategorized()) {
              if ($$.isTimeSeries()) {
                  firstX = new Date(firstX.getTime() * 0.5);
                  lastX = new Date(lastX.getTime() * 1.5);
              } else {
                  firstX = firstX === 0 ? 1 : (firstX * 0.5);
                  lastX = lastX === 0 ? -1 : (lastX * 1.5);
              }
          }
          if (firstX || firstX === 0) {
              min = $$.isTimeSeries() ? new Date(firstX.getTime() - padding.left) : firstX - padding.left;
          }
          if (lastX || lastX === 0) {
              max = $$.isTimeSeries() ? new Date(lastX.getTime() + padding.right) : lastX + padding.right;
          }
          return [min, max];
      };
      c3_chart_internal_fn.updateXDomain = function (targets, withUpdateXDomain, withUpdateOrgXDomain, withTrim, domain) {
          var $$ = this, config = $$.config;
  
          if (withUpdateOrgXDomain) {
              $$.x.domain(domain ? domain : $$.d3.extent($$.getXDomain(targets)));
              $$.orgXDomain = $$.x.domain();
              if (config.zoom_enabled) { $$.zoom.scale($$.x).updateScaleExtent(); }
              $$.subX.domain($$.x.domain());
              if ($$.brush) { $$.brush.scale($$.subX); }
          }
          if (withUpdateXDomain) {
              $$.x.domain(domain ? domain : (!$$.brush || $$.brush.empty()) ? $$.orgXDomain : $$.brush.extent());
              if (config.zoom_enabled) { $$.zoom.scale($$.x).updateScaleExtent(); }
          }
  
          // Trim domain when too big by zoom mousemove event
          if (withTrim) { $$.x.domain($$.trimXDomain($$.x.orgDomain())); }
  
          return $$.x.domain();
      };
      c3_chart_internal_fn.trimXDomain = function (domain) {
          var zoomDomain = this.getZoomDomain(),
              min = zoomDomain[0], max = zoomDomain[1];
          if (domain[0] <= min) {
              domain[1] = +domain[1] + (min - domain[0]);
              domain[0] = min;
          }
          if (max <= domain[1]) {
              domain[0] = +domain[0] - (domain[1] - max);
              domain[1] = max;
          }
          return domain;
      };
  
      c3_chart_internal_fn.isX = function (key) {
          var $$ = this, config = $$.config;
          return (config.data_x && key === config.data_x) || (notEmpty(config.data_xs) && hasValue(config.data_xs, key));
      };
      c3_chart_internal_fn.isNotX = function (key) {
          return !this.isX(key);
      };
      c3_chart_internal_fn.getXKey = function (id) {
          var $$ = this, config = $$.config;
          return config.data_x ? config.data_x : notEmpty(config.data_xs) ? config.data_xs[id] : null;
      };
      c3_chart_internal_fn.getXValuesOfXKey = function (key, targets) {
          var $$ = this,
              xValues, ids = targets && notEmpty(targets) ? $$.mapToIds(targets) : [];
          ids.forEach(function (id) {
              if ($$.getXKey(id) === key) {
                  xValues = $$.data.xs[id];
              }
          });
          return xValues;
      };
      c3_chart_internal_fn.getIndexByX = function (x) {
          var $$ = this,
              data = $$.filterByX($$.data.targets, x);
          return data.length ? data[0].index : null;
      };
      c3_chart_internal_fn.getXValue = function (id, i) {
          var $$ = this;
          return id in $$.data.xs && $$.data.xs[id] && isValue($$.data.xs[id][i]) ? $$.data.xs[id][i] : i;
      };
      c3_chart_internal_fn.getOtherTargetXs = function () {
          var $$ = this,
              idsForX = Object.keys($$.data.xs);
          return idsForX.length ? $$.data.xs[idsForX[0]] : null;
      };
      c3_chart_internal_fn.getOtherTargetX = function (index) {
          var xs = this.getOtherTargetXs();
          return xs && index < xs.length ? xs[index] : null;
      };
      c3_chart_internal_fn.addXs = function (xs) {
          var $$ = this;
          Object.keys(xs).forEach(function (id) {
              $$.config.data_xs[id] = xs[id];
          });
      };
      c3_chart_internal_fn.hasMultipleX = function (xs) {
          return this.d3.set(Object.keys(xs).map(function (id) { return xs[id]; })).size() > 1;
      };
      c3_chart_internal_fn.isMultipleX = function () {
          return notEmpty(this.config.data_xs) || !this.config.data_xSort || this.hasType('scatter');
      };
      c3_chart_internal_fn.addName = function (data) {
          var $$ = this, name;
          if (data) {
              name = $$.config.data_names[data.id];
              data.name = name !== undefined ? name : data.id;
          }
          return data;
      };
      c3_chart_internal_fn.getValueOnIndex = function (values, index) {
          var valueOnIndex = values.filter(function (v) { return v.index === index; });
          return valueOnIndex.length ? valueOnIndex[0] : null;
      };
      c3_chart_internal_fn.updateTargetX = function (targets, x) {
          var $$ = this;
          targets.forEach(function (t) {
              t.values.forEach(function (v, i) {
                  v.x = $$.generateTargetX(x[i], t.id, i);
              });
              $$.data.xs[t.id] = x;
          });
      };
      c3_chart_internal_fn.updateTargetXs = function (targets, xs) {
          var $$ = this;
          targets.forEach(function (t) {
              if (xs[t.id]) {
                  $$.updateTargetX([t], xs[t.id]);
              }
          });
      };
      c3_chart_internal_fn.generateTargetX = function (rawX, id, index) {
          var $$ = this, x;
          if ($$.isTimeSeries()) {
              x = rawX ? $$.parseDate(rawX) : $$.parseDate($$.getXValue(id, index));
          }
          else if ($$.isCustomX() && !$$.isCategorized()) {
              x = isValue(rawX) ? +rawX : $$.getXValue(id, index);
          }
          else {
              x = index;
          }
          return x;
      };
      c3_chart_internal_fn.cloneTarget = function (target) {
          return {
              id : target.id,
              id_org : target.id_org,
              values : target.values.map(function (d) {
                  return {x: d.x, value: d.value, id: d.id};
              })
          };
      };
      c3_chart_internal_fn.updateXs = function () {
          var $$ = this;
          if ($$.data.targets.length) {
              $$.xs = [];
              $$.data.targets[0].values.forEach(function (v) {
                  $$.xs[v.index] = v.x;
              });
          }
      };
      c3_chart_internal_fn.getPrevX = function (i) {
          var x = this.xs[i - 1];
          return typeof x !== 'undefined' ? x : null;
      };
      c3_chart_internal_fn.getNextX = function (i) {
          var x = this.xs[i + 1];
          return typeof x !== 'undefined' ? x : null;
      };
      c3_chart_internal_fn.getMaxDataCount = function () {
          var $$ = this;
          return $$.d3.max($$.data.targets, function (t) { return t.values.length; });
      };
      c3_chart_internal_fn.getMaxDataCountTarget = function (targets) {
          var length = targets.length, max = 0, maxTarget;
          if (length > 1) {
              targets.forEach(function (t) {
                  if (t.values.length > max) {
                      maxTarget = t;
                      max = t.values.length;
                  }
              });
          } else {
              maxTarget = length ? targets[0] : null;
          }
          return maxTarget;
      };
      c3_chart_internal_fn.getEdgeX = function (targets) {
          var $$ = this;
          return !targets.length ? [0, 0] : [
              $$.d3.min(targets, function (t) { return t.values[0].x; }),
              $$.d3.max(targets, function (t) { return t.values[t.values.length - 1].x; })
          ];
      };
      c3_chart_internal_fn.mapToIds = function (targets) {
          return targets.map(function (d) { return d.id; });
      };
      c3_chart_internal_fn.mapToTargetIds = function (ids) {
          var $$ = this;
          return ids ? [].concat(ids) : $$.mapToIds($$.data.targets);
      };
      c3_chart_internal_fn.hasTarget = function (targets, id) {
          var ids = this.mapToIds(targets), i;
          for (i = 0; i < ids.length; i++) {
              if (ids[i] === id) {
                  return true;
              }
          }
          return false;
      };
      c3_chart_internal_fn.isTargetToShow = function (targetId) {
          return this.hiddenTargetIds.indexOf(targetId) < 0;
      };
      c3_chart_internal_fn.isLegendToShow = function (targetId) {
          return this.hiddenLegendIds.indexOf(targetId) < 0;
      };
      c3_chart_internal_fn.filterTargetsToShow = function (targets) {
          var $$ = this;
          return targets.filter(function (t) { return $$.isTargetToShow(t.id); });
      };
      c3_chart_internal_fn.mapTargetsToUniqueXs = function (targets) {
          var $$ = this;
          var xs = $$.d3.set($$.d3.merge(targets.map(function (t) { return t.values.map(function (v) { return +v.x; }); }))).values();
          xs = $$.isTimeSeries() ? xs.map(function (x) { return new Date(+x); }) : xs.map(function (x) { return +x; });
          return xs.sort(function (a, b) { return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN; });
      };
      c3_chart_internal_fn.addHiddenTargetIds = function (targetIds) {
          this.hiddenTargetIds = this.hiddenTargetIds.concat(targetIds);
      };
      c3_chart_internal_fn.removeHiddenTargetIds = function (targetIds) {
          this.hiddenTargetIds = this.hiddenTargetIds.filter(function (id) { return targetIds.indexOf(id) < 0; });
      };
      c3_chart_internal_fn.addHiddenLegendIds = function (targetIds) {
          this.hiddenLegendIds = this.hiddenLegendIds.concat(targetIds);
      };
      c3_chart_internal_fn.removeHiddenLegendIds = function (targetIds) {
          this.hiddenLegendIds = this.hiddenLegendIds.filter(function (id) { return targetIds.indexOf(id) < 0; });
      };
      c3_chart_internal_fn.getValuesAsIdKeyed = function (targets) {
          var ys = {};
          targets.forEach(function (t) {
              ys[t.id] = [];
              t.values.forEach(function (v) {
                  ys[t.id].push(v.value);
              });
          });
          return ys;
      };
      c3_chart_internal_fn.checkValueInTargets = function (targets, checker) {
          var ids = Object.keys(targets), i, j, values;
          for (i = 0; i < ids.length; i++) {
              values = targets[ids[i]].values;
              for (j = 0; j < values.length; j++) {
                  if (checker(values[j].value)) {
                      return true;
                  }
              }
          }
          return false;
      };
      c3_chart_internal_fn.hasNegativeValueInTargets = function (targets) {
          return this.checkValueInTargets(targets, function (v) { return v < 0; });
      };
      c3_chart_internal_fn.hasPositiveValueInTargets = function (targets) {
          return this.checkValueInTargets(targets, function (v) { return v > 0; });
      };
      c3_chart_internal_fn.isOrderDesc = function () {
          var config = this.config;
          return typeof(config.data_order) === 'string' && config.data_order.toLowerCase() === 'desc';
      };
      c3_chart_internal_fn.isOrderAsc = function () {
          var config = this.config;
          return typeof(config.data_order) === 'string' && config.data_order.toLowerCase() === 'asc';
      };
      c3_chart_internal_fn.orderTargets = function (targets) {
          var $$ = this, config = $$.config, orderAsc = $$.isOrderAsc(), orderDesc = $$.isOrderDesc();
          if (orderAsc || orderDesc) {
              targets.sort(function (t1, t2) {
                  var reducer = function (p, c) { return p + Math.abs(c.value); };
                  var t1Sum = t1.values.reduce(reducer, 0),
                      t2Sum = t2.values.reduce(reducer, 0);
                  return orderAsc ? t2Sum - t1Sum : t1Sum - t2Sum;
              });
          } else if (isFunction(config.data_order)) {
              targets.sort(config.data_order);
          } // TODO: accept name array for order
          return targets;
      };
      c3_chart_internal_fn.filterByX = function (targets, x) {
          return this.d3.merge(targets.map(function (t) { return t.values; })).filter(function (v) { return v.x - x === 0; });
      };
      c3_chart_internal_fn.filterRemoveNull = function (data) {
          return data.filter(function (d) { return isValue(d.value); });
      };
      c3_chart_internal_fn.filterByXDomain = function (targets, xDomain) {
          return targets.map(function (t) {
              return {
                  id: t.id,
                  id_org: t.id_org,
                  values: t.values.filter(function (v) {
                      return xDomain[0] <= v.x && v.x <= xDomain[1];
                  })
              };
          });
      };
      c3_chart_internal_fn.hasDataLabel = function () {
          var config = this.config;
          if (typeof config.data_labels === 'boolean' && config.data_labels) {
              return true;
          } else if (typeof config.data_labels === 'object' && notEmpty(config.data_labels)) {
              return true;
          }
          return false;
      };
      c3_chart_internal_fn.getDataLabelLength = function (min, max, key) {
          var $$ = this,
              lengths = [0, 0], paddingCoef = 1.3;
          $$.selectChart.select('svg').selectAll('.dummy')
              .data([min, max])
              .enter().append('text')
              .text(function (d) { return $$.dataLabelFormat(d.id)(d); })
              .each(function (d, i) {
                  lengths[i] = this.getBoundingClientRect()[key] * paddingCoef;
              })
              .remove();
          return lengths;
      };
      c3_chart_internal_fn.isNoneArc = function (d) {
          return this.hasTarget(this.data.targets, d.id);
      },
      c3_chart_internal_fn.isArc = function (d) {
          return 'data' in d && this.hasTarget(this.data.targets, d.data.id);
      };
      c3_chart_internal_fn.findSameXOfValues = function (values, index) {
          var i, targetX = values[index].x, sames = [];
          for (i = index - 1; i >= 0; i--) {
              if (targetX !== values[i].x) { break; }
              sames.push(values[i]);
          }
          for (i = index; i < values.length; i++) {
              if (targetX !== values[i].x) { break; }
              sames.push(values[i]);
          }
          return sames;
      };
  
      c3_chart_internal_fn.findClosestFromTargets = function (targets, pos) {
          var $$ = this, candidates;
  
          // map to array of closest points of each target
          candidates = targets.map(function (target) {
              return $$.findClosest(target.values, pos);
          });
  
          // decide closest point and return
          return $$.findClosest(candidates, pos);
      };
      c3_chart_internal_fn.findClosest = function (values, pos) {
          var $$ = this, minDist = $$.config.point_sensitivity, closest;
  
          // find mouseovering bar
          values.filter(function (v) { return v && $$.isBarType(v.id); }).forEach(function (v) {
              var shape = $$.main.select('.' + CLASS.bars + $$.getTargetSelectorSuffix(v.id) + ' .' + CLASS.bar + '-' + v.index).node();
              if (!closest && $$.isWithinBar(shape)) {
                  closest = v;
              }
          });
  
          // find closest point from non-bar
          values.filter(function (v) { return v && !$$.isBarType(v.id); }).forEach(function (v) {
              var d = $$.dist(v, pos);
              if (d < minDist) {
                  minDist = d;
                  closest = v;
              }
          });
  
          return closest;
      };
      c3_chart_internal_fn.dist = function (data, pos) {
          var $$ = this, config = $$.config,
              xIndex = config.axis_rotated ? 1 : 0,
              yIndex = config.axis_rotated ? 0 : 1,
              y = $$.circleY(data, data.index),
              x = $$.x(data.x);
          return Math.sqrt(Math.pow(x - pos[xIndex], 2) + Math.pow(y - pos[yIndex], 2));
      };
      c3_chart_internal_fn.convertValuesToStep = function (values) {
          var converted = [].concat(values), i;
  
          if (!this.isCategorized()) {
              return values;
          }
  
          for (i = values.length + 1; 0 < i; i--) {
              converted[i] = converted[i - 1];
          }
  
          converted[0] = {
              x: converted[0].x - 1,
              value: converted[0].value,
              id: converted[0].id
          };
          converted[values.length + 1] = {
              x: converted[values.length].x + 1,
              value: converted[values.length].value,
              id: converted[values.length].id
          };
  
          return converted;
      };
      c3_chart_internal_fn.updateDataAttributes = function (name, attrs) {
          var $$ = this, config = $$.config, current = config['data_' + name];
          if (typeof attrs === 'undefined') { return current; }
          Object.keys(attrs).forEach(function (id) {
              current[id] = attrs[id];
          });
          $$.redraw({withLegend: true});
          return current;
      };
  
      c3_chart_internal_fn.convertUrlToData = function (url, mimeType, keys, done) {
          var $$ = this, type = mimeType ? mimeType : 'csv';
          $$.d3.xhr(url, function (error, data) {
              var d;
              if (!data) {
                  throw new Error(error.responseURL + ' ' + error.status + ' (' + error.statusText + ')');
              }
              if (type === 'json') {
                  d = $$.convertJsonToData(JSON.parse(data.response), keys);
              } else if (type === 'tsv') {
                  d = $$.convertTsvToData(data.response);
              } else {
                  d = $$.convertCsvToData(data.response);
              }
              done.call($$, d);
          });
      };
      c3_chart_internal_fn.convertXsvToData = function (xsv, parser) {
          var rows = parser.parseRows(xsv), d;
          if (rows.length === 1) {
              d = [{}];
              rows[0].forEach(function (id) {
                  d[0][id] = null;
              });
          } else {
              d = parser.parse(xsv);
          }
          return d;
      };
      c3_chart_internal_fn.convertCsvToData = function (csv) {
          return this.convertXsvToData(csv, this.d3.csv);
      };
      c3_chart_internal_fn.convertTsvToData = function (tsv) {
          return this.convertXsvToData(tsv, this.d3.tsv);
      };
      c3_chart_internal_fn.convertJsonToData = function (json, keys) {
          var $$ = this,
              new_rows = [], targetKeys, data;
          if (keys) { // when keys specified, json would be an array that includes objects
              if (keys.x) {
                  targetKeys = keys.value.concat(keys.x);
                  $$.config.data_x = keys.x;
              } else {
                  targetKeys = keys.value;
              }
              new_rows.push(targetKeys);
              json.forEach(function (o) {
                  var new_row = [];
                  targetKeys.forEach(function (key) {
                      // convert undefined to null because undefined data will be removed in convertDataToTargets()
                      var v = isUndefined(o[key]) ? null : o[key];
                      new_row.push(v);
                  });
                  new_rows.push(new_row);
              });
              data = $$.convertRowsToData(new_rows);
          } else {
              Object.keys(json).forEach(function (key) {
                  new_rows.push([key].concat(json[key]));
              });
              data = $$.convertColumnsToData(new_rows);
          }
          return data;
      };
      c3_chart_internal_fn.convertRowsToData = function (rows) {
          var keys = rows[0], new_row = {}, new_rows = [], i, j;
          for (i = 1; i < rows.length; i++) {
              new_row = {};
              for (j = 0; j < rows[i].length; j++) {
                  if (isUndefined(rows[i][j])) {
                      throw new Error("Source data is missing a component at (" + i + "," + j + ")!");
                  }
                  new_row[keys[j]] = rows[i][j];
              }
              new_rows.push(new_row);
          }
          return new_rows;
      };
      c3_chart_internal_fn.convertColumnsToData = function (columns) {
          var new_rows = [], i, j, key;
          for (i = 0; i < columns.length; i++) {
              key = columns[i][0];
              for (j = 1; j < columns[i].length; j++) {
                  if (isUndefined(new_rows[j - 1])) {
                      new_rows[j - 1] = {};
                  }
                  if (isUndefined(columns[i][j])) {
                      throw new Error("Source data is missing a component at (" + i + "," + j + ")!");
                  }
                  new_rows[j - 1][key] = columns[i][j];
              }
          }
          return new_rows;
      };
      c3_chart_internal_fn.convertDataToTargets = function (data, appendXs) {
          var $$ = this, config = $$.config,
              ids = $$.d3.keys(data[0]).filter($$.isNotX, $$),
              xs = $$.d3.keys(data[0]).filter($$.isX, $$),
              targets;
  
          // save x for update data by load when custom x and c3.x API
          ids.forEach(function (id) {
              var xKey = $$.getXKey(id);
  
              if ($$.isCustomX() || $$.isTimeSeries()) {
                  // if included in input data
                  if (xs.indexOf(xKey) >= 0) {
                      $$.data.xs[id] = (appendXs && $$.data.xs[id] ? $$.data.xs[id] : []).concat(
                          data.map(function (d) { return d[xKey]; })
                              .filter(isValue)
                              .map(function (rawX, i) { return $$.generateTargetX(rawX, id, i); })
                      );
                  }
                  // if not included in input data, find from preloaded data of other id's x
                  else if (config.data_x) {
                      $$.data.xs[id] = $$.getOtherTargetXs();
                  }
                  // if not included in input data, find from preloaded data
                  else if (notEmpty(config.data_xs)) {
                      $$.data.xs[id] = $$.getXValuesOfXKey(xKey, $$.data.targets);
                  }
                  // MEMO: if no x included, use same x of current will be used
              } else {
                  $$.data.xs[id] = data.map(function (d, i) { return i; });
              }
          });
  
  
          // check x is defined
          ids.forEach(function (id) {
              if (!$$.data.xs[id]) {
                  throw new Error('x is not defined for id = "' + id + '".');
              }
          });
  
          // convert to target
          targets = ids.map(function (id, index) {
              var convertedId = config.data_idConverter(id);
              return {
                  id: convertedId,
                  id_org: id,
                  values: data.map(function (d, i) {
                      var xKey = $$.getXKey(id), rawX = d[xKey], x = $$.generateTargetX(rawX, id, i),
                          value = d[id] !== null && !isNaN(d[id]) ? +d[id] : null;
                      // use x as categories if custom x and categorized
                      if ($$.isCustomX() && $$.isCategorized() && index === 0 && rawX) {
                          if (i === 0) { config.axis_x_categories = []; }
                          config.axis_x_categories.push(rawX);
                      }
                      // mark as x = undefined if value is undefined and filter to remove after mapped
                      if (isUndefined(d[id]) || $$.data.xs[id].length <= i) {
                          x = undefined;
                      }
                      return {x: x, value: value, id: convertedId};
                  }).filter(function (v) { return isDefined(v.x); })
              };
          });
  
          // finish targets
          targets.forEach(function (t) {
              var i;
              // sort values by its x
              if (config.data_xSort) {
                  t.values = t.values.sort(function (v1, v2) {
                      var x1 = v1.x || v1.x === 0 ? v1.x : Infinity,
                          x2 = v2.x || v2.x === 0 ? v2.x : Infinity;
                      return x1 - x2;
                  });
              }
              // indexing each value
              i = 0;
              t.values.forEach(function (v) {
                  v.index = i++;
              });
              // this needs to be sorted because its index and value.index is identical
              $$.data.xs[t.id].sort(function (v1, v2) {
                  return v1 - v2;
              });
          });
  
          // cache information about values
          $$.hasNegativeValue = $$.hasNegativeValueInTargets(targets);
          $$.hasPositiveValue = $$.hasPositiveValueInTargets(targets);
  
          // set target types
          if (config.data_type) {
              $$.setTargetType($$.mapToIds(targets).filter(function (id) { return ! (id in config.data_types); }), config.data_type);
          }
  
          // cache as original id keyed
          targets.forEach(function (d) {
              $$.addCache(d.id_org, d);
          });
  
          return targets;
      };
  
      c3_chart_internal_fn.load = function (targets, args) {
          var $$ = this;
          if (targets) {
              // filter loading targets if needed
              if (args.filter) {
                  targets = targets.filter(args.filter);
              }
              // set type if args.types || args.type specified
              if (args.type || args.types) {
                  targets.forEach(function (t) {
                      var type = args.types && args.types[t.id] ? args.types[t.id] : args.type;
                      $$.setTargetType(t.id, type);
                  });
              }
              // Update/Add data
              $$.data.targets.forEach(function (d) {
                  for (var i = 0; i < targets.length; i++) {
                      if (d.id === targets[i].id) {
                          d.values = targets[i].values;
                          targets.splice(i, 1);
                          break;
                      }
                  }
              });
              $$.data.targets = $$.data.targets.concat(targets); // add remained
          }
  
          // Set targets
          $$.updateTargets($$.data.targets);
  
          // Redraw with new targets
          $$.redraw({withUpdateOrgXDomain: true, withUpdateXDomain: true, withLegend: true});
  
          if (args.done) { args.done(); }
      };
      c3_chart_internal_fn.loadFromArgs = function (args) {
          var $$ = this;
          if (args.data) {
              $$.load($$.convertDataToTargets(args.data), args);
          }
          else if (args.url) {
              $$.convertUrlToData(args.url, args.mimeType, args.keys, function (data) {
                  $$.load($$.convertDataToTargets(data), args);
              });
          }
          else if (args.json) {
              $$.load($$.convertDataToTargets($$.convertJsonToData(args.json, args.keys)), args);
          }
          else if (args.rows) {
              $$.load($$.convertDataToTargets($$.convertRowsToData(args.rows)), args);
          }
          else if (args.columns) {
              $$.load($$.convertDataToTargets($$.convertColumnsToData(args.columns)), args);
          }
          else {
              $$.load(null, args);
          }
      };
      c3_chart_internal_fn.unload = function (targetIds, done) {
          var $$ = this;
          if (!done) {
              done = function () {};
          }
          // filter existing target
          targetIds = targetIds.filter(function (id) { return $$.hasTarget($$.data.targets, id); });
          // If no target, call done and return
          if (!targetIds || targetIds.length === 0) {
              done();
              return;
          }
          $$.svg.selectAll(targetIds.map(function (id) { return $$.selectorTarget(id); }))
              .transition()
              .style('opacity', 0)
              .remove()
              .call($$.endall, done);
          targetIds.forEach(function (id) {
              // Reset fadein for future load
              $$.withoutFadeIn[id] = false;
              // Remove target's elements
              if ($$.legend) {
                  $$.legend.selectAll('.' + CLASS.legendItem + $$.getTargetSelectorSuffix(id)).remove();
              }
              // Remove target
              $$.data.targets = $$.data.targets.filter(function (t) {
                  return t.id !== id;
              });
          });
      };
  
      c3_chart_internal_fn.categoryName = function (i) {
          var config = this.config;
          return i < config.axis_x_categories.length ? config.axis_x_categories[i] : i;
      };
  
      c3_chart_internal_fn.initEventRect = function () {
          var $$ = this;
          $$.main.select('.' + CLASS.chart).append("g")
              .attr("class", CLASS.eventRects)
              .style('fill-opacity', 0);
      };
      c3_chart_internal_fn.redrawEventRect = function () {
          var $$ = this, config = $$.config,
              eventRectUpdate, maxDataCountTarget,
              isMultipleX = $$.isMultipleX();
  
          // rects for mouseover
          var eventRects = $$.main.select('.' + CLASS.eventRects)
                  .style('cursor', config.zoom_enabled ? config.axis_rotated ? 'ns-resize' : 'ew-resize' : null)
                  .classed(CLASS.eventRectsMultiple, isMultipleX)
                  .classed(CLASS.eventRectsSingle, !isMultipleX);
  
          // clear old rects
          eventRects.selectAll('.' + CLASS.eventRect).remove();
  
          // open as public variable
          $$.eventRect = eventRects.selectAll('.' + CLASS.eventRect);
  
          if (isMultipleX) {
              eventRectUpdate = $$.eventRect.data([0]);
              // enter : only one rect will be added
              $$.generateEventRectsForMultipleXs(eventRectUpdate.enter());
              // update
              $$.updateEventRect(eventRectUpdate);
              // exit : not needed because always only one rect exists
          }
          else {
              // Set data and update $$.eventRect
              maxDataCountTarget = $$.getMaxDataCountTarget($$.data.targets);
              eventRects.datum(maxDataCountTarget ? maxDataCountTarget.values : []);
              $$.eventRect = eventRects.selectAll('.' + CLASS.eventRect);
              eventRectUpdate = $$.eventRect.data(function (d) { return d; });
              // enter
              $$.generateEventRectsForSingleX(eventRectUpdate.enter());
              // update
              $$.updateEventRect(eventRectUpdate);
              // exit
              eventRectUpdate.exit().remove();
          }
      };
      c3_chart_internal_fn.updateEventRect = function (eventRectUpdate) {
          var $$ = this, config = $$.config,
              x, y, w, h, rectW, rectX;
  
          // set update selection if null
          eventRectUpdate = eventRectUpdate || $$.eventRect.data(function (d) { return d; });
  
          if ($$.isMultipleX()) {
              // TODO: rotated not supported yet
              x = 0;
              y = 0;
              w = $$.width;
              h = $$.height;
          }
          else {
              if (($$.isCustomX() || $$.isTimeSeries()) && !$$.isCategorized()) {
  
                  // update index for x that is used by prevX and nextX
                  $$.updateXs();
  
                  rectW = function (d) {
                      var prevX = $$.getPrevX(d.index), nextX = $$.getNextX(d.index);
  
                      // if there this is a single data point make the eventRect full width (or height)
                      if (prevX === null && nextX === null) {
                          return config.axis_rotated ? $$.height : $$.width;
                      }
  
                      if (prevX === null) { prevX = $$.x.domain()[0]; }
                      if (nextX === null) { nextX = $$.x.domain()[1]; }
  
                      return Math.max(0, ($$.x(nextX) - $$.x(prevX)) / 2);
                  };
                  rectX = function (d) {
                      var prevX = $$.getPrevX(d.index), nextX = $$.getNextX(d.index),
                          thisX = $$.data.xs[d.id][d.index];
  
                      // if there this is a single data point position the eventRect at 0
                      if (prevX === null && nextX === null) {
                          return 0;
                      }
  
                      if (prevX === null) { prevX = $$.x.domain()[0]; }
  
                      return ($$.x(thisX) + $$.x(prevX)) / 2;
                  };
              } else {
                  rectW = $$.getEventRectWidth();
                  rectX = function (d) {
                      return $$.x(d.x) - (rectW / 2);
                  };
              }
              x = config.axis_rotated ? 0 : rectX;
              y = config.axis_rotated ? rectX : 0;
              w = config.axis_rotated ? $$.width : rectW;
              h = config.axis_rotated ? rectW : $$.height;
          }
  
          eventRectUpdate
              .attr('class', $$.classEvent.bind($$))
              .attr("x", x)
              .attr("y", y)
              .attr("width", w)
              .attr("height", h);
      };
      c3_chart_internal_fn.generateEventRectsForSingleX = function (eventRectEnter) {
          var $$ = this, d3 = $$.d3, config = $$.config;
          eventRectEnter.append("rect")
              .attr("class", $$.classEvent.bind($$))
              .style("cursor", config.data_selection_enabled && config.data_selection_grouped ? "pointer" : null)
              .on('mouseover', function (d) {
                  var index = d.index;
  
                  if ($$.dragging || $$.flowing) { return; } // do nothing while dragging/flowing
                  if ($$.hasArcType()) { return; }
  
                  // Expand shapes for selection
                  if (config.point_focus_expand_enabled) { $$.expandCircles(index, null, true); }
                  $$.expandBars(index, null, true);
  
                  // Call event handler
                  $$.main.selectAll('.' + CLASS.shape + '-' + index).each(function (d) {
                      config.data_onmouseover.call($$.api, d);
                  });
              })
              .on('mouseout', function (d) {
                  var index = d.index;
                  if (!$$.config) { return; } // chart is destroyed
                  if ($$.hasArcType()) { return; }
                  $$.hideXGridFocus();
                  $$.hideTooltip();
                  // Undo expanded shapes
                  $$.unexpandCircles();
                  $$.unexpandBars();
                  // Call event handler
                  $$.main.selectAll('.' + CLASS.shape + '-' + index).each(function (d) {
                      config.data_onmouseout.call($$.api, d);
                  });
              })
              .on('mousemove', function (d) {
                  var selectedData, index = d.index,
                      eventRect = $$.svg.select('.' + CLASS.eventRect + '-' + index);
  
                  if ($$.dragging || $$.flowing) { return; } // do nothing while dragging/flowing
                  if ($$.hasArcType()) { return; }
  
                  if ($$.isStepType(d) && $$.config.line_step_type === 'step-after' && d3.mouse(this)[0] < $$.x($$.getXValue(d.id, index))) {
                      index -= 1;
                  }
  
                  // Show tooltip
                  selectedData = $$.filterTargetsToShow($$.data.targets).map(function (t) {
                      return $$.addName($$.getValueOnIndex(t.values, index));
                  });
  
                  if (config.tooltip_grouped) {
                      $$.showTooltip(selectedData, this);
                      $$.showXGridFocus(selectedData);
                  }
  
                  if (config.tooltip_grouped && (!config.data_selection_enabled || config.data_selection_grouped)) {
                      return;
                  }
  
                  $$.main.selectAll('.' + CLASS.shape + '-' + index)
                      .each(function () {
                          d3.select(this).classed(CLASS.EXPANDED, true);
                          if (config.data_selection_enabled) {
                              eventRect.style('cursor', config.data_selection_grouped ? 'pointer' : null);
                          }
                          if (!config.tooltip_grouped) {
                              $$.hideXGridFocus();
                              $$.hideTooltip();
                              if (!config.data_selection_grouped) {
                                  $$.unexpandCircles(index);
                                  $$.unexpandBars(index);
                              }
                          }
                      })
                      .filter(function (d) {
                          return $$.isWithinShape(this, d);
                      })
                      .each(function (d) {
                          if (config.data_selection_enabled && (config.data_selection_grouped || config.data_selection_isselectable(d))) {
                              eventRect.style('cursor', 'pointer');
                          }
                          if (!config.tooltip_grouped) {
                              $$.showTooltip([d], this);
                              $$.showXGridFocus([d]);
                              if (config.point_focus_expand_enabled) { $$.expandCircles(index, d.id, true); }
                              $$.expandBars(index, d.id, true);
                          }
                      });
              })
              .on('click', function (d) {
                  var index = d.index;
                  if ($$.hasArcType() || !$$.toggleShape) { return; }
                  if ($$.cancelClick) {
                      $$.cancelClick = false;
                      return;
                  }
                  if ($$.isStepType(d) && config.line_step_type === 'step-after' && d3.mouse(this)[0] < $$.x($$.getXValue(d.id, index))) {
                      index -= 1;
                  }
                  $$.main.selectAll('.' + CLASS.shape + '-' + index).each(function (d) {
                      if (config.data_selection_grouped || $$.isWithinShape(this, d)) {
                          $$.toggleShape(this, d, index);
                          $$.config.data_onclick.call($$.api, d, this);
                      }
                  });
              })
              .call(
                  config.data_selection_draggable && $$.drag ? (
                      d3.behavior.drag().origin(Object)
                          .on('drag', function () { $$.drag(d3.mouse(this)); })
                          .on('dragstart', function () { $$.dragstart(d3.mouse(this)); })
                          .on('dragend', function () { $$.dragend(); })
                  ) : function () {}
              );
      };
  
      c3_chart_internal_fn.generateEventRectsForMultipleXs = function (eventRectEnter) {
          var $$ = this, d3 = $$.d3, config = $$.config;
  
          function mouseout() {
              $$.svg.select('.' + CLASS.eventRect).style('cursor', null);
              $$.hideXGridFocus();
              $$.hideTooltip();
              $$.unexpandCircles();
              $$.unexpandBars();
          }
  
          eventRectEnter.append('rect')
              .attr('x', 0)
              .attr('y', 0)
              .attr('width', $$.width)
              .attr('height', $$.height)
              .attr('class', CLASS.eventRect)
              .on('mouseout', function () {
                  if (!$$.config) { return; } // chart is destroyed
                  if ($$.hasArcType()) { return; }
                  mouseout();
              })
              .on('mousemove', function () {
                  var targetsToShow = $$.filterTargetsToShow($$.data.targets);
                  var mouse, closest, sameXData, selectedData;
  
                  if ($$.dragging) { return; } // do nothing when dragging
                  if ($$.hasArcType(targetsToShow)) { return; }
  
                  mouse = d3.mouse(this);
                  closest = $$.findClosestFromTargets(targetsToShow, mouse);
  
                  if ($$.mouseover && (!closest || closest.id !== $$.mouseover.id)) {
                      config.data_onmouseout.call($$.api, $$.mouseover);
                      $$.mouseover = undefined;
                  }
  
                  if (! closest) {
                      mouseout();
                      return;
                  }
  
                  if ($$.isScatterType(closest) || !config.tooltip_grouped) {
                      sameXData = [closest];
                  } else {
                      sameXData = $$.filterByX(targetsToShow, closest.x);
                  }
  
                  // show tooltip when cursor is close to some point
                  selectedData = sameXData.map(function (d) {
                      return $$.addName(d);
                  });
                  $$.showTooltip(selectedData, this);
  
                  // expand points
                  if (config.point_focus_expand_enabled) {
                      $$.expandCircles(closest.index, closest.id, true);
                  }
                  $$.expandBars(closest.index, closest.id, true);
  
                  // Show xgrid focus line
                  $$.showXGridFocus(selectedData);
  
                  // Show cursor as pointer if point is close to mouse position
                  if ($$.isBarType(closest.id) || $$.dist(closest, mouse) < config.point_sensitivity) {
                      $$.svg.select('.' + CLASS.eventRect).style('cursor', 'pointer');
                      if (!$$.mouseover) {
                          config.data_onmouseover.call($$.api, closest);
                          $$.mouseover = closest;
                      }
                  }
              })
              .on('click', function () {
                  var targetsToShow = $$.filterTargetsToShow($$.data.targets);
                  var mouse, closest;
                  if ($$.hasArcType(targetsToShow)) { return; }
  
                  mouse = d3.mouse(this);
                  closest = $$.findClosestFromTargets(targetsToShow, mouse);
                  if (! closest) { return; }
                  // select if selection enabled
                  if ($$.isBarType(closest.id) || $$.dist(closest, mouse) < config.point_sensitivity) {
                      $$.main.selectAll('.' + CLASS.shapes + $$.getTargetSelectorSuffix(closest.id)).selectAll('.' + CLASS.shape + '-' + closest.index).each(function () {
                          if (config.data_selection_grouped || $$.isWithinShape(this, closest)) {
                              $$.toggleShape(this, closest, closest.index);
                              $$.config.data_onclick.call($$.api, closest, this);
                          }
                      });
                  }
              })
              .call(
                  config.data_selection_draggable && $$.drag ? (
                      d3.behavior.drag().origin(Object)
                          .on('drag', function () { $$.drag(d3.mouse(this)); })
                          .on('dragstart', function () { $$.dragstart(d3.mouse(this)); })
                          .on('dragend', function () { $$.dragend(); })
                  ) : function () {}
              );
      };
      c3_chart_internal_fn.dispatchEvent = function (type, index, mouse) {
          var $$ = this,
              selector = '.' + CLASS.eventRect + (!$$.isMultipleX() ? '-' + index : ''),
              eventRect = $$.main.select(selector).node(),
              box = eventRect.getBoundingClientRect(),
              x = box.left + (mouse ? mouse[0] : 0),
              y = box.top + (mouse ? mouse[1] : 0),
              event = document.createEvent("MouseEvents");
  
          event.initMouseEvent(type, true, true, window, 0, x, y, x, y,
                               false, false, false, false, 0, null);
          eventRect.dispatchEvent(event);
      };
  
      c3_chart_internal_fn.getCurrentWidth = function () {
          var $$ = this, config = $$.config;
          return config.size_width ? config.size_width : $$.getParentWidth();
      };
      c3_chart_internal_fn.getCurrentHeight = function () {
          var $$ = this, config = $$.config,
              h = config.size_height ? config.size_height : $$.getParentHeight();
          return h > 0 ? h : 320 / ($$.hasType('gauge') ? 2 : 1);
      };
      c3_chart_internal_fn.getCurrentPaddingTop = function () {
          var $$ = this,
              config = $$.config,
              padding = isValue(config.padding_top) ? config.padding_top : 0;
          if ($$.title && $$.title.node()) {
              padding += $$.getTitlePadding();
          }
          return padding;
      };
      c3_chart_internal_fn.getCurrentPaddingBottom = function () {
          var config = this.config;
          return isValue(config.padding_bottom) ? config.padding_bottom : 0;
      };
      c3_chart_internal_fn.getCurrentPaddingLeft = function (withoutRecompute) {
          var $$ = this, config = $$.config;
          if (isValue(config.padding_left)) {
              return config.padding_left;
          } else if (config.axis_rotated) {
              return !config.axis_x_show ? 1 : Math.max(ceil10($$.getAxisWidthByAxisId('x', withoutRecompute)), 40);
          } else if (!config.axis_y_show || config.axis_y_inner) { // && !config.axis_rotated
              return $$.axis.getYAxisLabelPosition().isOuter ? 30 : 1;
          } else {
              return ceil10($$.getAxisWidthByAxisId('y', withoutRecompute));
          }
      };
      c3_chart_internal_fn.getCurrentPaddingRight = function () {
          var $$ = this, config = $$.config,
              defaultPadding = 10, legendWidthOnRight = $$.isLegendRight ? $$.getLegendWidth() + 20 : 0;
          if (isValue(config.padding_right)) {
              return config.padding_right + 1; // 1 is needed not to hide tick line
          } else if (config.axis_rotated) {
              return defaultPadding + legendWidthOnRight;
          } else if (!config.axis_y2_show || config.axis_y2_inner) { // && !config.axis_rotated
              return 2 + legendWidthOnRight + ($$.axis.getY2AxisLabelPosition().isOuter ? 20 : 0);
          } else {
              return ceil10($$.getAxisWidthByAxisId('y2')) + legendWidthOnRight;
          }
      };
  
      c3_chart_internal_fn.getParentRectValue = function (key) {
          var parent = this.selectChart.node(), v;
          while (parent && parent.tagName !== 'BODY') {
              try {
                  v = parent.getBoundingClientRect()[key];
              } catch(e) {
                  if (key === 'width') {
                      // In IE in certain cases getBoundingClientRect
                      // will cause an "unspecified error"
                      v = parent.offsetWidth;
                  }
              }
              if (v) {
                  break;
              }
              parent = parent.parentNode;
          }
          return v;
      };
      c3_chart_internal_fn.getParentWidth = function () {
          return this.getParentRectValue('width');
      };
      c3_chart_internal_fn.getParentHeight = function () {
          var h = this.selectChart.style('height');
          return h.indexOf('px') > 0 ? +h.replace('px', '') : 0;
      };
  
  
      c3_chart_internal_fn.getSvgLeft = function (withoutRecompute) {
          var $$ = this, config = $$.config,
              hasLeftAxisRect = config.axis_rotated || (!config.axis_rotated && !config.axis_y_inner),
              leftAxisClass = config.axis_rotated ? CLASS.axisX : CLASS.axisY,
              leftAxis = $$.main.select('.' + leftAxisClass).node(),
              svgRect = leftAxis && hasLeftAxisRect ? leftAxis.getBoundingClientRect() : {right: 0},
              chartRect = $$.selectChart.node().getBoundingClientRect(),
              hasArc = $$.hasArcType(),
              svgLeft = svgRect.right - chartRect.left - (hasArc ? 0 : $$.getCurrentPaddingLeft(withoutRecompute));
          return svgLeft > 0 ? svgLeft : 0;
      };
  
  
      c3_chart_internal_fn.getAxisWidthByAxisId = function (id, withoutRecompute) {
          var $$ = this, position = $$.axis.getLabelPositionById(id);
          return $$.axis.getMaxTickWidth(id, withoutRecompute) + (position.isInner ? 20 : 40);
      };
      c3_chart_internal_fn.getHorizontalAxisHeight = function (axisId) {
          var $$ = this, config = $$.config, h = 30;
          if (axisId === 'x' && !config.axis_x_show) { return 8; }
          if (axisId === 'x' && config.axis_x_height) { return config.axis_x_height; }
          if (axisId === 'y' && !config.axis_y_show) { return config.legend_show && !$$.isLegendRight && !$$.isLegendInset ? 10 : 1; }
          if (axisId === 'y2' && !config.axis_y2_show) { return $$.rotated_padding_top; }
          // Calculate x axis height when tick rotated
          if (axisId === 'x' && !config.axis_rotated && config.axis_x_tick_rotate) {
              h = 30 + $$.axis.getMaxTickWidth(axisId) * Math.cos(Math.PI * (90 - config.axis_x_tick_rotate) / 180);
          }
          return h + ($$.axis.getLabelPositionById(axisId).isInner ? 0 : 10) + (axisId === 'y2' ? -10 : 0);
      };
  
      c3_chart_internal_fn.getEventRectWidth = function () {
          return Math.max(0, this.xAxis.tickInterval());
      };
  
      c3_chart_internal_fn.getShapeIndices = function (typeFilter) {
          var $$ = this, config = $$.config,
              indices = {}, i = 0, j, k;
          $$.filterTargetsToShow($$.data.targets.filter(typeFilter, $$)).forEach(function (d) {
              for (j = 0; j < config.data_groups.length; j++) {
                  if (config.data_groups[j].indexOf(d.id) < 0) { continue; }
                  for (k = 0; k < config.data_groups[j].length; k++) {
                      if (config.data_groups[j][k] in indices) {
                          indices[d.id] = indices[config.data_groups[j][k]];
                          break;
                      }
                  }
              }
              if (isUndefined(indices[d.id])) { indices[d.id] = i++; }
          });
          indices.__max__ = i - 1;
          return indices;
      };
      c3_chart_internal_fn.getShapeX = function (offset, targetsNum, indices, isSub) {
          var $$ = this, scale = isSub ? $$.subX : $$.x;
          return function (d) {
              var index = d.id in indices ? indices[d.id] : 0;
              return d.x || d.x === 0 ? scale(d.x) - offset * (targetsNum / 2 - index) : 0;
          };
      };
      c3_chart_internal_fn.getShapeY = function (isSub) {
          var $$ = this;
          return function (d) {
              var scale = isSub ? $$.getSubYScale(d.id) : $$.getYScale(d.id);
              return scale(d.value);
          };
      };
      c3_chart_internal_fn.getShapeOffset = function (typeFilter, indices, isSub) {
          var $$ = this,
              targets = $$.orderTargets($$.filterTargetsToShow($$.data.targets.filter(typeFilter, $$))),
              targetIds = targets.map(function (t) { return t.id; });
          return function (d, i) {
              var scale = isSub ? $$.getSubYScale(d.id) : $$.getYScale(d.id),
                  y0 = scale(0), offset = y0;
              targets.forEach(function (t) {
                  var values = $$.isStepType(d) ? $$.convertValuesToStep(t.values) : t.values;
                  if (t.id === d.id || indices[t.id] !== indices[d.id]) { return; }
                  if (targetIds.indexOf(t.id) < targetIds.indexOf(d.id)) {
                      // check if the x values line up
                      if (typeof values[i] === 'undefined' || +values[i].x !== +d.x) {  // "+" for timeseries
                          // if not, try to find the value that does line up
                          i = -1;
                          values.forEach(function (v, j) {
                              if (v.x === d.x) {
                                  i = j;
                              }
                          });
                      }
                      if (i in values && values[i].value * d.value >= 0) {
                          offset += scale(values[i].value) - y0;
                      }
                  }
              });
              return offset;
          };
      };
      c3_chart_internal_fn.isWithinShape = function (that, d) {
          var $$ = this,
              shape = $$.d3.select(that), isWithin;
          if (!$$.isTargetToShow(d.id)) {
              isWithin = false;
          }
          else if (that.nodeName === 'circle') {
              isWithin = $$.isStepType(d) ? $$.isWithinStep(that, $$.getYScale(d.id)(d.value)) : $$.isWithinCircle(that, $$.pointSelectR(d) * 1.5);
          }
          else if (that.nodeName === 'path') {
              isWithin = shape.classed(CLASS.bar) ? $$.isWithinBar(that) : true;
          }
          return isWithin;
      };
  
  
      c3_chart_internal_fn.getInterpolate = function (d) {
          var $$ = this,
              interpolation = $$.isInterpolationType($$.config.spline_interpolation_type) ? $$.config.spline_interpolation_type : 'cardinal';
          return $$.isSplineType(d) ? interpolation : $$.isStepType(d) ? $$.config.line_step_type : "linear";
      };
  
      c3_chart_internal_fn.initLine = function () {
          var $$ = this;
          $$.main.select('.' + CLASS.chart).append("g")
              .attr("class", CLASS.chartLines);
      };
      c3_chart_internal_fn.updateTargetsForLine = function (targets) {
          var $$ = this, config = $$.config,
              mainLineUpdate, mainLineEnter,
              classChartLine = $$.classChartLine.bind($$),
              classLines = $$.classLines.bind($$),
              classAreas = $$.classAreas.bind($$),
              classCircles = $$.classCircles.bind($$),
              classFocus = $$.classFocus.bind($$);
          mainLineUpdate = $$.main.select('.' + CLASS.chartLines).selectAll('.' + CLASS.chartLine)
              .data(targets)
              .attr('class', function (d) { return classChartLine(d) + classFocus(d); });
          mainLineEnter = mainLineUpdate.enter().append('g')
              .attr('class', classChartLine)
              .style('opacity', 0)
              .style("pointer-events", "none");
          // Lines for each data
          mainLineEnter.append('g')
              .attr("class", classLines);
          // Areas
          mainLineEnter.append('g')
              .attr('class', classAreas);
          // Circles for each data point on lines
          mainLineEnter.append('g')
              .attr("class", function (d) { return $$.generateClass(CLASS.selectedCircles, d.id); });
          mainLineEnter.append('g')
              .attr("class", classCircles)
              .style("cursor", function (d) { return config.data_selection_isselectable(d) ? "pointer" : null; });
          // Update date for selected circles
          targets.forEach(function (t) {
              $$.main.selectAll('.' + CLASS.selectedCircles + $$.getTargetSelectorSuffix(t.id)).selectAll('.' + CLASS.selectedCircle).each(function (d) {
                  d.value = t.values[d.index].value;
              });
          });
          // MEMO: can not keep same color...
          //mainLineUpdate.exit().remove();
      };
      c3_chart_internal_fn.updateLine = function (durationForExit) {
          var $$ = this;
          $$.mainLine = $$.main.selectAll('.' + CLASS.lines).selectAll('.' + CLASS.line)
              .data($$.lineData.bind($$));
          $$.mainLine.enter().append('path')
              .attr('class', $$.classLine.bind($$))
              .style("stroke", $$.color);
          $$.mainLine
              .style("opacity", $$.initialOpacity.bind($$))
              .style('shape-rendering', function (d) { return $$.isStepType(d) ? 'crispEdges' : ''; })
              .attr('transform', null);
          $$.mainLine.exit().transition().duration(durationForExit)
              .style('opacity', 0)
              .remove();
      };
      c3_chart_internal_fn.redrawLine = function (drawLine, withTransition) {
          return [
              (withTransition ? this.mainLine.transition() : this.mainLine)
                  .attr("d", drawLine)
                  .style("stroke", this.color)
                  .style("opacity", 1)
          ];
      };
      c3_chart_internal_fn.generateDrawLine = function (lineIndices, isSub) {
          var $$ = this, config = $$.config,
              line = $$.d3.svg.line(),
              getPoints = $$.generateGetLinePoints(lineIndices, isSub),
              yScaleGetter = isSub ? $$.getSubYScale : $$.getYScale,
              xValue = function (d) { return (isSub ? $$.subxx : $$.xx).call($$, d); },
              yValue = function (d, i) {
                  return config.data_groups.length > 0 ? getPoints(d, i)[0][1] : yScaleGetter.call($$, d.id)(d.value);
              };
  
          line = config.axis_rotated ? line.x(yValue).y(xValue) : line.x(xValue).y(yValue);
          if (!config.line_connectNull) { line = line.defined(function (d) { return d.value != null; }); }
          return function (d) {
              var values = config.line_connectNull ? $$.filterRemoveNull(d.values) : d.values,
                  x = isSub ? $$.x : $$.subX, y = yScaleGetter.call($$, d.id), x0 = 0, y0 = 0, path;
              if ($$.isLineType(d)) {
                  if (config.data_regions[d.id]) {
                      path = $$.lineWithRegions(values, x, y, config.data_regions[d.id]);
                  } else {
                      if ($$.isStepType(d)) { values = $$.convertValuesToStep(values); }
                      path = line.interpolate($$.getInterpolate(d))(values);
                  }
              } else {
                  if (values[0]) {
                      x0 = x(values[0].x);
                      y0 = y(values[0].value);
                  }
                  path = config.axis_rotated ? "M " + y0 + " " + x0 : "M " + x0 + " " + y0;
              }
              return path ? path : "M 0 0";
          };
      };
      c3_chart_internal_fn.generateGetLinePoints = function (lineIndices, isSub) { // partial duplication of generateGetBarPoints
          var $$ = this, config = $$.config,
              lineTargetsNum = lineIndices.__max__ + 1,
              x = $$.getShapeX(0, lineTargetsNum, lineIndices, !!isSub),
              y = $$.getShapeY(!!isSub),
              lineOffset = $$.getShapeOffset($$.isLineType, lineIndices, !!isSub),
              yScale = isSub ? $$.getSubYScale : $$.getYScale;
          return function (d, i) {
              var y0 = yScale.call($$, d.id)(0),
                  offset = lineOffset(d, i) || y0, // offset is for stacked area chart
                  posX = x(d), posY = y(d);
              // fix posY not to overflow opposite quadrant
              if (config.axis_rotated) {
                  if ((0 < d.value && posY < y0) || (d.value < 0 && y0 < posY)) { posY = y0; }
              }
              // 1 point that marks the line position
              return [
                  [posX, posY - (y0 - offset)],
                  [posX, posY - (y0 - offset)], // needed for compatibility
                  [posX, posY - (y0 - offset)], // needed for compatibility
                  [posX, posY - (y0 - offset)]  // needed for compatibility
              ];
          };
      };
  
  
      c3_chart_internal_fn.lineWithRegions = function (d, x, y, _regions) {
          var $$ = this, config = $$.config,
              prev = -1, i, j,
              s = "M", sWithRegion,
              xp, yp, dx, dy, dd, diff, diffx2,
              xOffset = $$.isCategorized() ? 0.5 : 0,
              xValue, yValue,
              regions = [];
  
          function isWithinRegions(x, regions) {
              var i;
              for (i = 0; i < regions.length; i++) {
                  if (regions[i].start < x && x <= regions[i].end) { return true; }
              }
              return false;
          }
  
          // Check start/end of regions
          if (isDefined(_regions)) {
              for (i = 0; i < _regions.length; i++) {
                  regions[i] = {};
                  if (isUndefined(_regions[i].start)) {
                      regions[i].start = d[0].x;
                  } else {
                      regions[i].start = $$.isTimeSeries() ? $$.parseDate(_regions[i].start) : _regions[i].start;
                  }
                  if (isUndefined(_regions[i].end)) {
                      regions[i].end = d[d.length - 1].x;
                  } else {
                      regions[i].end = $$.isTimeSeries() ? $$.parseDate(_regions[i].end) : _regions[i].end;
                  }
              }
          }
  
          // Set scales
          xValue = config.axis_rotated ? function (d) { return y(d.value); } : function (d) { return x(d.x); };
          yValue = config.axis_rotated ? function (d) { return x(d.x); } : function (d) { return y(d.value); };
  
          // Define svg generator function for region
          function generateM(points) {
              return 'M' + points[0][0] + ' ' + points[0][1] + ' ' + points[1][0] + ' ' + points[1][1];
          }
          if ($$.isTimeSeries()) {
              sWithRegion = function (d0, d1, j, diff) {
                  var x0 = d0.x.getTime(), x_diff = d1.x - d0.x,
                      xv0 = new Date(x0 + x_diff * j),
                      xv1 = new Date(x0 + x_diff * (j + diff)),
                      points;
                  if (config.axis_rotated) {
                      points = [[y(yp(j)), x(xv0)], [y(yp(j + diff)), x(xv1)]];
                  } else {
                      points = [[x(xv0), y(yp(j))], [x(xv1), y(yp(j + diff))]];
                  }
                  return generateM(points);
              };
          } else {
              sWithRegion = function (d0, d1, j, diff) {
                  var points;
                  if (config.axis_rotated) {
                      points = [[y(yp(j), true), x(xp(j))], [y(yp(j + diff), true), x(xp(j + diff))]];
                  } else {
                      points = [[x(xp(j), true), y(yp(j))], [x(xp(j + diff), true), y(yp(j + diff))]];
                  }
                  return generateM(points);
              };
          }
  
          // Generate
          for (i = 0; i < d.length; i++) {
  
              // Draw as normal
              if (isUndefined(regions) || ! isWithinRegions(d[i].x, regions)) {
                  s += " " + xValue(d[i]) + " " + yValue(d[i]);
              }
              // Draw with region // TODO: Fix for horizotal charts
              else {
                  xp = $$.getScale(d[i - 1].x + xOffset, d[i].x + xOffset, $$.isTimeSeries());
                  yp = $$.getScale(d[i - 1].value, d[i].value);
  
                  dx = x(d[i].x) - x(d[i - 1].x);
                  dy = y(d[i].value) - y(d[i - 1].value);
                  dd = Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
                  diff = 2 / dd;
                  diffx2 = diff * 2;
  
                  for (j = diff; j <= 1; j += diffx2) {
                      s += sWithRegion(d[i - 1], d[i], j, diff);
                  }
              }
              prev = d[i].x;
          }
  
          return s;
      };
  
  
      c3_chart_internal_fn.updateArea = function (durationForExit) {
          var $$ = this, d3 = $$.d3;
          $$.mainArea = $$.main.selectAll('.' + CLASS.areas).selectAll('.' + CLASS.area)
              .data($$.lineData.bind($$));
          $$.mainArea.enter().append('path')
              .attr("class", $$.classArea.bind($$))
              .style("fill", $$.color)
              .style("opacity", function () { $$.orgAreaOpacity = +d3.select(this).style('opacity'); return 0; });
          $$.mainArea
              .style("opacity", $$.orgAreaOpacity);
          $$.mainArea.exit().transition().duration(durationForExit)
              .style('opacity', 0)
              .remove();
      };
      c3_chart_internal_fn.redrawArea = function (drawArea, withTransition) {
          return [
              (withTransition ? this.mainArea.transition() : this.mainArea)
                  .attr("d", drawArea)
                  .style("fill", this.color)
                  .style("opacity", this.orgAreaOpacity)
          ];
      };
      c3_chart_internal_fn.generateDrawArea = function (areaIndices, isSub) {
          var $$ = this, config = $$.config, area = $$.d3.svg.area(),
              getPoints = $$.generateGetAreaPoints(areaIndices, isSub),
              yScaleGetter = isSub ? $$.getSubYScale : $$.getYScale,
              xValue = function (d) { return (isSub ? $$.subxx : $$.xx).call($$, d); },
              value0 = function (d, i) {
                  return config.data_groups.length > 0 ? getPoints(d, i)[0][1] : yScaleGetter.call($$, d.id)($$.getAreaBaseValue(d.id));
              },
              value1 = function (d, i) {
                  return config.data_groups.length > 0 ? getPoints(d, i)[1][1] : yScaleGetter.call($$, d.id)(d.value);
              };
  
          area = config.axis_rotated ? area.x0(value0).x1(value1).y(xValue) : area.x(xValue).y0(value0).y1(value1);
          if (!config.line_connectNull) {
              area = area.defined(function (d) { return d.value !== null; });
          }
  
          return function (d) {
              var values = config.line_connectNull ? $$.filterRemoveNull(d.values) : d.values,
                  x0 = 0, y0 = 0, path;
              if ($$.isAreaType(d)) {
                  if ($$.isStepType(d)) { values = $$.convertValuesToStep(values); }
                  path = area.interpolate($$.getInterpolate(d))(values);
              } else {
                  if (values[0]) {
                      x0 = $$.x(values[0].x);
                      y0 = $$.getYScale(d.id)(values[0].value);
                  }
                  path = config.axis_rotated ? "M " + y0 + " " + x0 : "M " + x0 + " " + y0;
              }
              return path ? path : "M 0 0";
          };
      };
      c3_chart_internal_fn.getAreaBaseValue = function () {
          return 0;
      };
      c3_chart_internal_fn.generateGetAreaPoints = function (areaIndices, isSub) { // partial duplication of generateGetBarPoints
          var $$ = this, config = $$.config,
              areaTargetsNum = areaIndices.__max__ + 1,
              x = $$.getShapeX(0, areaTargetsNum, areaIndices, !!isSub),
              y = $$.getShapeY(!!isSub),
              areaOffset = $$.getShapeOffset($$.isAreaType, areaIndices, !!isSub),
              yScale = isSub ? $$.getSubYScale : $$.getYScale;
          return function (d, i) {
              var y0 = yScale.call($$, d.id)(0),
                  offset = areaOffset(d, i) || y0, // offset is for stacked area chart
                  posX = x(d), posY = y(d);
              // fix posY not to overflow opposite quadrant
              if (config.axis_rotated) {
                  if ((0 < d.value && posY < y0) || (d.value < 0 && y0 < posY)) { posY = y0; }
              }
              // 1 point that marks the area position
              return [
                  [posX, offset],
                  [posX, posY - (y0 - offset)],
                  [posX, posY - (y0 - offset)], // needed for compatibility
                  [posX, offset] // needed for compatibility
              ];
          };
      };
  
  
      c3_chart_internal_fn.updateCircle = function () {
          var $$ = this;
          $$.mainCircle = $$.main.selectAll('.' + CLASS.circles).selectAll('.' + CLASS.circle)
              .data($$.lineOrScatterData.bind($$));
          $$.mainCircle.enter().append("circle")
              .attr("class", $$.classCircle.bind($$))
              .attr("r", $$.pointR.bind($$))
              .style("fill", $$.color);
          $$.mainCircle
              .style("opacity", $$.initialOpacityForCircle.bind($$));
          $$.mainCircle.exit().remove();
      };
      c3_chart_internal_fn.redrawCircle = function (cx, cy, withTransition) {
          var selectedCircles = this.main.selectAll('.' + CLASS.selectedCircle);
          return [
              (withTransition ? this.mainCircle.transition() : this.mainCircle)
                  .style('opacity', this.opacityForCircle.bind(this))
                  .style("fill", this.color)
                  .attr("cx", cx)
                  .attr("cy", cy),
              (withTransition ? selectedCircles.transition() : selectedCircles)
                  .attr("cx", cx)
                  .attr("cy", cy)
          ];
      };
      c3_chart_internal_fn.circleX = function (d) {
          return d.x || d.x === 0 ? this.x(d.x) : null;
      };
      c3_chart_internal_fn.updateCircleY = function () {
          var $$ = this, lineIndices, getPoints;
          if ($$.config.data_groups.length > 0) {
              lineIndices = $$.getShapeIndices($$.isLineType),
              getPoints = $$.generateGetLinePoints(lineIndices);
              $$.circleY = function (d, i) {
                  return getPoints(d, i)[0][1];
              };
          } else {
              $$.circleY = function (d) {
                  return $$.getYScale(d.id)(d.value);
              };
          }
      };
      c3_chart_internal_fn.getCircles = function (i, id) {
          var $$ = this;
          return (id ? $$.main.selectAll('.' + CLASS.circles + $$.getTargetSelectorSuffix(id)) : $$.main).selectAll('.' + CLASS.circle + (isValue(i) ? '-' + i : ''));
      };
      c3_chart_internal_fn.expandCircles = function (i, id, reset) {
          var $$ = this,
              r = $$.pointExpandedR.bind($$);
          if (reset) { $$.unexpandCircles(); }
          $$.getCircles(i, id)
              .classed(CLASS.EXPANDED, true)
              .attr('r', r);
      };
      c3_chart_internal_fn.unexpandCircles = function (i) {
          var $$ = this,
              r = $$.pointR.bind($$);
          $$.getCircles(i)
              .filter(function () { return $$.d3.select(this).classed(CLASS.EXPANDED); })
              .classed(CLASS.EXPANDED, false)
              .attr('r', r);
      };
      c3_chart_internal_fn.pointR = function (d) {
          var $$ = this, config = $$.config;
          return $$.isStepType(d) ? 0 : (isFunction(config.point_r) ? config.point_r(d) : config.point_r);
      };
      c3_chart_internal_fn.pointExpandedR = function (d) {
          var $$ = this, config = $$.config;
          return config.point_focus_expand_enabled ? (config.point_focus_expand_r ? config.point_focus_expand_r : $$.pointR(d) * 1.75) : $$.pointR(d);
      };
      c3_chart_internal_fn.pointSelectR = function (d) {
          var $$ = this, config = $$.config;
          return config.point_select_r ? config.point_select_r : $$.pointR(d) * 4;
      };
      c3_chart_internal_fn.isWithinCircle = function (that, r) {
          var d3 = this.d3,
              mouse = d3.mouse(that), d3_this = d3.select(that),
              cx = +d3_this.attr("cx"), cy = +d3_this.attr("cy");
          return Math.sqrt(Math.pow(cx - mouse[0], 2) + Math.pow(cy - mouse[1], 2)) < r;
      };
      c3_chart_internal_fn.isWithinStep = function (that, y) {
          return Math.abs(y - this.d3.mouse(that)[1]) < 30;
      };
  
      c3_chart_internal_fn.initBar = function () {
          var $$ = this;
          $$.main.select('.' + CLASS.chart).append("g")
              .attr("class", CLASS.chartBars);
      };
      c3_chart_internal_fn.updateTargetsForBar = function (targets) {
          var $$ = this, config = $$.config,
              mainBarUpdate, mainBarEnter,
              classChartBar = $$.classChartBar.bind($$),
              classBars = $$.classBars.bind($$),
              classFocus = $$.classFocus.bind($$);
          mainBarUpdate = $$.main.select('.' + CLASS.chartBars).selectAll('.' + CLASS.chartBar)
              .data(targets)
              .attr('class', function (d) { return classChartBar(d) + classFocus(d); });
          mainBarEnter = mainBarUpdate.enter().append('g')
              .attr('class', classChartBar)
              .style('opacity', 0)
              .style("pointer-events", "none");
          // Bars for each data
          mainBarEnter.append('g')
              .attr("class", classBars)
              .style("cursor", function (d) { return config.data_selection_isselectable(d) ? "pointer" : null; });
  
      };
      c3_chart_internal_fn.updateBar = function (durationForExit) {
          var $$ = this,
              barData = $$.barData.bind($$),
              classBar = $$.classBar.bind($$),
              initialOpacity = $$.initialOpacity.bind($$),
              color = function (d) { return $$.color(d.id); };
          $$.mainBar = $$.main.selectAll('.' + CLASS.bars).selectAll('.' + CLASS.bar)
              .data(barData);
          $$.mainBar.enter().append('path')
              .attr("class", classBar)
              .style("stroke", color)
              .style("fill", color);
          $$.mainBar
              .style("opacity", initialOpacity);
          $$.mainBar.exit().transition().duration(durationForExit)
              .style('opacity', 0)
              .remove();
      };
      c3_chart_internal_fn.redrawBar = function (drawBar, withTransition) {
          return [
              (withTransition ? this.mainBar.transition() : this.mainBar)
                  .attr('d', drawBar)
                  .style("fill", this.color)
                  .style("opacity", 1)
          ];
      };
      c3_chart_internal_fn.getBarW = function (axis, barTargetsNum) {
          var $$ = this, config = $$.config,
              w = typeof config.bar_width === 'number' ? config.bar_width : barTargetsNum ? (axis.tickInterval() * config.bar_width_ratio) / barTargetsNum : 0;
          return config.bar_width_max && w > config.bar_width_max ? config.bar_width_max : w;
      };
      c3_chart_internal_fn.getBars = function (i, id) {
          var $$ = this;
          return (id ? $$.main.selectAll('.' + CLASS.bars + $$.getTargetSelectorSuffix(id)) : $$.main).selectAll('.' + CLASS.bar + (isValue(i) ? '-' + i : ''));
      };
      c3_chart_internal_fn.expandBars = function (i, id, reset) {
          var $$ = this;
          if (reset) { $$.unexpandBars(); }
          $$.getBars(i, id).classed(CLASS.EXPANDED, true);
      };
      c3_chart_internal_fn.unexpandBars = function (i) {
          var $$ = this;
          $$.getBars(i).classed(CLASS.EXPANDED, false);
      };
      c3_chart_internal_fn.generateDrawBar = function (barIndices, isSub) {
          var $$ = this, config = $$.config,
              getPoints = $$.generateGetBarPoints(barIndices, isSub);
          return function (d, i) {
              // 4 points that make a bar
              var points = getPoints(d, i);
  
              // switch points if axis is rotated, not applicable for sub chart
              var indexX = config.axis_rotated ? 1 : 0;
              var indexY = config.axis_rotated ? 0 : 1;
  
              var path = 'M ' + points[0][indexX] + ',' + points[0][indexY] + ' ' +
                      'L' + points[1][indexX] + ',' + points[1][indexY] + ' ' +
                      'L' + points[2][indexX] + ',' + points[2][indexY] + ' ' +
                      'L' + points[3][indexX] + ',' + points[3][indexY] + ' ' +
                      'z';
  
              return path;
          };
      };
      c3_chart_internal_fn.generateGetBarPoints = function (barIndices, isSub) {
          var $$ = this,
              axis = isSub ? $$.subXAxis : $$.xAxis,
              barTargetsNum = barIndices.__max__ + 1,
              barW = $$.getBarW(axis, barTargetsNum),
              barX = $$.getShapeX(barW, barTargetsNum, barIndices, !!isSub),
              barY = $$.getShapeY(!!isSub),
              barOffset = $$.getShapeOffset($$.isBarType, barIndices, !!isSub),
              yScale = isSub ? $$.getSubYScale : $$.getYScale;
          return function (d, i) {
              var y0 = yScale.call($$, d.id)(0),
                  offset = barOffset(d, i) || y0, // offset is for stacked bar chart
                  posX = barX(d), posY = barY(d);
              // fix posY not to overflow opposite quadrant
              if ($$.config.axis_rotated) {
                  if ((0 < d.value && posY < y0) || (d.value < 0 && y0 < posY)) { posY = y0; }
              }
              // 4 points that make a bar
              return [
                  [posX, offset],
                  [posX, posY - (y0 - offset)],
                  [posX + barW, posY - (y0 - offset)],
                  [posX + barW, offset]
              ];
          };
      };
      c3_chart_internal_fn.isWithinBar = function (that) {
          var mouse = this.d3.mouse(that), box = that.getBoundingClientRect(),
              seg0 = that.pathSegList.getItem(0), seg1 = that.pathSegList.getItem(1),
              x = Math.min(seg0.x, seg1.x), y = Math.min(seg0.y, seg1.y),
              w = box.width, h = box.height, offset = 2,
              sx = x - offset, ex = x + w + offset, sy = y + h + offset, ey = y - offset;
          return sx < mouse[0] && mouse[0] < ex && ey < mouse[1] && mouse[1] < sy;
      };
  
      c3_chart_internal_fn.initText = function () {
          var $$ = this;
          $$.main.select('.' + CLASS.chart).append("g")
              .attr("class", CLASS.chartTexts);
          $$.mainText = $$.d3.selectAll([]);
      };
      c3_chart_internal_fn.updateTargetsForText = function (targets) {
          var $$ = this, mainTextUpdate, mainTextEnter,
              classChartText = $$.classChartText.bind($$),
              classTexts = $$.classTexts.bind($$),
              classFocus = $$.classFocus.bind($$);
          mainTextUpdate = $$.main.select('.' + CLASS.chartTexts).selectAll('.' + CLASS.chartText)
              .data(targets)
              .attr('class', function (d) { return classChartText(d) + classFocus(d); });
          mainTextEnter = mainTextUpdate.enter().append('g')
              .attr('class', classChartText)
              .style('opacity', 0)
              .style("pointer-events", "none");
          mainTextEnter.append('g')
              .attr('class', classTexts);
      };
      c3_chart_internal_fn.updateText = function (durationForExit) {
          var $$ = this, config = $$.config,
              barOrLineData = $$.barOrLineData.bind($$),
              classText = $$.classText.bind($$);
          $$.mainText = $$.main.selectAll('.' + CLASS.texts).selectAll('.' + CLASS.text)
              .data(barOrLineData);
          $$.mainText.enter().append('text')
              .attr("class", classText)
              .attr('text-anchor', function (d) { return config.axis_rotated ? (d.value < 0 ? 'end' : 'start') : 'middle'; })
              .style("stroke", 'none')
              .style("fill", function (d) { return $$.color(d); })
              .style("fill-opacity", 0);
          $$.mainText
              .text(function (d, i, j) { return $$.dataLabelFormat(d.id)(d.value, d.id, i, j); });
          $$.mainText.exit()
              .transition().duration(durationForExit)
              .style('fill-opacity', 0)
              .remove();
      };
      c3_chart_internal_fn.redrawText = function (xForText, yForText, forFlow, withTransition) {
          return [
              (withTransition ? this.mainText.transition() : this.mainText)
                  .attr('x', xForText)
                  .attr('y', yForText)
                  .style("fill", this.color)
                  .style("fill-opacity", forFlow ? 0 : this.opacityForText.bind(this))
          ];
      };
      c3_chart_internal_fn.getTextRect = function (text, cls, element) {
          var dummy = this.d3.select('body').append('div').classed('c3', true),
              svg = dummy.append("svg").style('visibility', 'hidden').style('position', 'fixed').style('top', 0).style('left', 0),
              font = this.d3.select(element).style('font'),
              rect;
          svg.selectAll('.dummy')
              .data([text])
            .enter().append('text')
              .classed(cls ? cls : "", true)
              .style('font', font)
              .text(text)
            .each(function () { rect = this.getBoundingClientRect(); });
          dummy.remove();
          return rect;
      };
      c3_chart_internal_fn.generateXYForText = function (areaIndices, barIndices, lineIndices, forX) {
          var $$ = this,
              getAreaPoints = $$.generateGetAreaPoints(areaIndices, false),
              getBarPoints = $$.generateGetBarPoints(barIndices, false),
              getLinePoints = $$.generateGetLinePoints(lineIndices, false),
              getter = forX ? $$.getXForText : $$.getYForText;
          return function (d, i) {
              var getPoints = $$.isAreaType(d) ? getAreaPoints : $$.isBarType(d) ? getBarPoints : getLinePoints;
              return getter.call($$, getPoints(d, i), d, this);
          };
      };
      c3_chart_internal_fn.getXForText = function (points, d, textElement) {
          var $$ = this,
              box = textElement.getBoundingClientRect(), xPos, padding;
          if ($$.config.axis_rotated) {
              padding = $$.isBarType(d) ? 4 : 6;
              xPos = points[2][1] + padding * (d.value < 0 ? -1 : 1);
          } else {
              xPos = $$.hasType('bar') ? (points[2][0] + points[0][0]) / 2 : points[0][0];
          }
          // show labels regardless of the domain if value is null
          if (d.value === null) {
              if (xPos > $$.width) {
                  xPos = $$.width - box.width;
              } else if (xPos < 0) {
                  xPos = 4;
              }
          }
          return xPos;
      };
      c3_chart_internal_fn.getYForText = function (points, d, textElement) {
          var $$ = this,
              box = textElement.getBoundingClientRect(),
              yPos;
          if ($$.config.axis_rotated) {
              yPos = (points[0][0] + points[2][0] + box.height * 0.6) / 2;
          } else {
              yPos = points[2][1];
              if (d.value < 0  || (d.value === 0 && !$$.hasPositiveValue)) {
                  yPos += box.height;
                  if ($$.isBarType(d) && $$.isSafari()) {
                      yPos -= 3;
                  }
                  else if (!$$.isBarType(d) && $$.isChrome()) {
                      yPos += 3;
                  }
              } else {
                  yPos += $$.isBarType(d) ? -3 : -6;
              }
          }
          // show labels regardless of the domain if value is null
          if (d.value === null && !$$.config.axis_rotated) {
              if (yPos < box.height) {
                  yPos = box.height;
              } else if (yPos > this.height) {
                  yPos = this.height - 4;
              }
          }
          return yPos;
      };
  
      c3_chart_internal_fn.setTargetType = function (targetIds, type) {
          var $$ = this, config = $$.config;
          $$.mapToTargetIds(targetIds).forEach(function (id) {
              $$.withoutFadeIn[id] = (type === config.data_types[id]);
              config.data_types[id] = type;
          });
          if (!targetIds) {
              config.data_type = type;
          }
      };
      c3_chart_internal_fn.hasType = function (type, targets) {
          var $$ = this, types = $$.config.data_types, has = false;
          targets = targets || $$.data.targets;
          if (targets && targets.length) {
              targets.forEach(function (target) {
                  var t = types[target.id];
                  if ((t && t.indexOf(type) >= 0) || (!t && type === 'line')) {
                      has = true;
                  }
              });
          } else if (Object.keys(types).length) {
              Object.keys(types).forEach(function (id) {
                  if (types[id] === type) { has = true; }
              });
          } else {
              has = $$.config.data_type === type;
          }
          return has;
      };
      c3_chart_internal_fn.hasArcType = function (targets) {
          return this.hasType('pie', targets) || this.hasType('donut', targets) || this.hasType('gauge', targets);
      };
      c3_chart_internal_fn.isLineType = function (d) {
          var config = this.config, id = isString(d) ? d : d.id;
          return !config.data_types[id] || ['line', 'spline', 'area', 'area-spline', 'step', 'area-step'].indexOf(config.data_types[id]) >= 0;
      };
      c3_chart_internal_fn.isStepType = function (d) {
          var id = isString(d) ? d : d.id;
          return ['step', 'area-step'].indexOf(this.config.data_types[id]) >= 0;
      };
      c3_chart_internal_fn.isSplineType = function (d) {
          var id = isString(d) ? d : d.id;
          return ['spline', 'area-spline'].indexOf(this.config.data_types[id]) >= 0;
      };
      c3_chart_internal_fn.isAreaType = function (d) {
          var id = isString(d) ? d : d.id;
          return ['area', 'area-spline', 'area-step'].indexOf(this.config.data_types[id]) >= 0;
      };
      c3_chart_internal_fn.isBarType = function (d) {
          var id = isString(d) ? d : d.id;
          return this.config.data_types[id] === 'bar';
      };
      c3_chart_internal_fn.isScatterType = function (d) {
          var id = isString(d) ? d : d.id;
          return this.config.data_types[id] === 'scatter';
      };
      c3_chart_internal_fn.isPieType = function (d) {
          var id = isString(d) ? d : d.id;
          return this.config.data_types[id] === 'pie';
      };
      c3_chart_internal_fn.isGaugeType = function (d) {
          var id = isString(d) ? d : d.id;
          return this.config.data_types[id] === 'gauge';
      };
      c3_chart_internal_fn.isDonutType = function (d) {
          var id = isString(d) ? d : d.id;
          return this.config.data_types[id] === 'donut';
      };
      c3_chart_internal_fn.isArcType = function (d) {
          return this.isPieType(d) || this.isDonutType(d) || this.isGaugeType(d);
      };
      c3_chart_internal_fn.lineData = function (d) {
          return this.isLineType(d) ? [d] : [];
      };
      c3_chart_internal_fn.arcData = function (d) {
          return this.isArcType(d.data) ? [d] : [];
      };
      /* not used
       function scatterData(d) {
       return isScatterType(d) ? d.values : [];
       }
       */
      c3_chart_internal_fn.barData = function (d) {
          return this.isBarType(d) ? d.values : [];
      };
      c3_chart_internal_fn.lineOrScatterData = function (d) {
          return this.isLineType(d) || this.isScatterType(d) ? d.values : [];
      };
      c3_chart_internal_fn.barOrLineData = function (d) {
          return this.isBarType(d) || this.isLineType(d) ? d.values : [];
      };
      c3_chart_internal_fn.isInterpolationType = function (type) {
          return ['linear', 'linear-closed', 'basis', 'basis-open', 'basis-closed', 'bundle', 'cardinal', 'cardinal-open', 'cardinal-closed', 'monotone'].indexOf(type) >= 0;
      };
  
      c3_chart_internal_fn.initGrid = function () {
          var $$ = this, config = $$.config, d3 = $$.d3;
          $$.grid = $$.main.append('g')
              .attr("clip-path", $$.clipPathForGrid)
              .attr('class', CLASS.grid);
          if (config.grid_x_show) {
              $$.grid.append("g").attr("class", CLASS.xgrids);
          }
          if (config.grid_y_show) {
              $$.grid.append('g').attr('class', CLASS.ygrids);
          }
          if (config.grid_focus_show) {
              $$.grid.append('g')
                  .attr("class", CLASS.xgridFocus)
                  .append('line')
                  .attr('class', CLASS.xgridFocus);
          }
          $$.xgrid = d3.selectAll([]);
          if (!config.grid_lines_front) { $$.initGridLines(); }
      };
      c3_chart_internal_fn.initGridLines = function () {
          var $$ = this, d3 = $$.d3;
          $$.gridLines = $$.main.append('g')
              .attr("clip-path", $$.clipPathForGrid)
              .attr('class', CLASS.grid + ' ' + CLASS.gridLines);
          $$.gridLines.append('g').attr("class", CLASS.xgridLines);
          $$.gridLines.append('g').attr('class', CLASS.ygridLines);
          $$.xgridLines = d3.selectAll([]);
      };
      c3_chart_internal_fn.updateXGrid = function (withoutUpdate) {
          var $$ = this, config = $$.config, d3 = $$.d3,
              xgridData = $$.generateGridData(config.grid_x_type, $$.x),
              tickOffset = $$.isCategorized() ? $$.xAxis.tickOffset() : 0;
  
          $$.xgridAttr = config.axis_rotated ? {
              'x1': 0,
              'x2': $$.width,
              'y1': function (d) { return $$.x(d) - tickOffset; },
              'y2': function (d) { return $$.x(d) - tickOffset; }
          } : {
              'x1': function (d) { return $$.x(d) + tickOffset; },
              'x2': function (d) { return $$.x(d) + tickOffset; },
              'y1': 0,
              'y2': $$.height
          };
  
          $$.xgrid = $$.main.select('.' + CLASS.xgrids).selectAll('.' + CLASS.xgrid)
              .data(xgridData);
          $$.xgrid.enter().append('line').attr("class", CLASS.xgrid);
          if (!withoutUpdate) {
              $$.xgrid.attr($$.xgridAttr)
                  .style("opacity", function () { return +d3.select(this).attr(config.axis_rotated ? 'y1' : 'x1') === (config.axis_rotated ? $$.height : 0) ? 0 : 1; });
          }
          $$.xgrid.exit().remove();
      };
  
      c3_chart_internal_fn.updateYGrid = function () {
          var $$ = this, config = $$.config,
              gridValues = $$.yAxis.tickValues() || $$.y.ticks(config.grid_y_ticks);
          $$.ygrid = $$.main.select('.' + CLASS.ygrids).selectAll('.' + CLASS.ygrid)
              .data(gridValues);
          $$.ygrid.enter().append('line')
              .attr('class', CLASS.ygrid);
          $$.ygrid.attr("x1", config.axis_rotated ? $$.y : 0)
              .attr("x2", config.axis_rotated ? $$.y : $$.width)
              .attr("y1", config.axis_rotated ? 0 : $$.y)
              .attr("y2", config.axis_rotated ? $$.height : $$.y);
          $$.ygrid.exit().remove();
          $$.smoothLines($$.ygrid, 'grid');
      };
  
      c3_chart_internal_fn.gridTextAnchor = function (d) {
          return d.position ? d.position : "end";
      };
      c3_chart_internal_fn.gridTextDx = function (d) {
          return d.position === 'start' ? 4 : d.position === 'middle' ? 0 : -4;
      };
      c3_chart_internal_fn.xGridTextX = function (d) {
          return d.position === 'start' ? -this.height : d.position === 'middle' ? -this.height / 2 : 0;
      };
      c3_chart_internal_fn.yGridTextX = function (d) {
          return d.position === 'start' ? 0 : d.position === 'middle' ? this.width / 2 : this.width;
      };
      c3_chart_internal_fn.updateGrid = function (duration) {
          var $$ = this, main = $$.main, config = $$.config,
              xgridLine, ygridLine, yv;
  
          // hide if arc type
          $$.grid.style('visibility', $$.hasArcType() ? 'hidden' : 'visible');
  
          main.select('line.' + CLASS.xgridFocus).style("visibility", "hidden");
          if (config.grid_x_show) {
              $$.updateXGrid();
          }
          $$.xgridLines = main.select('.' + CLASS.xgridLines).selectAll('.' + CLASS.xgridLine)
              .data(config.grid_x_lines);
          // enter
          xgridLine = $$.xgridLines.enter().append('g')
              .attr("class", function (d) { return CLASS.xgridLine + (d['class'] ? ' ' + d['class'] : ''); });
          xgridLine.append('line')
              .style("opacity", 0);
          xgridLine.append('text')
              .attr("text-anchor", $$.gridTextAnchor)
              .attr("transform", config.axis_rotated ? "" : "rotate(-90)")
              .attr('dx', $$.gridTextDx)
              .attr('dy', -5)
              .style("opacity", 0);
          // udpate
          // done in d3.transition() of the end of this function
          // exit
          $$.xgridLines.exit().transition().duration(duration)
              .style("opacity", 0)
              .remove();
  
          // Y-Grid
          if (config.grid_y_show) {
              $$.updateYGrid();
          }
          $$.ygridLines = main.select('.' + CLASS.ygridLines).selectAll('.' + CLASS.ygridLine)
              .data(config.grid_y_lines);
          // enter
          ygridLine = $$.ygridLines.enter().append('g')
              .attr("class", function (d) { return CLASS.ygridLine + (d['class'] ? ' ' + d['class'] : ''); });
          ygridLine.append('line')
              .style("opacity", 0);
          ygridLine.append('text')
              .attr("text-anchor", $$.gridTextAnchor)
              .attr("transform", config.axis_rotated ? "rotate(-90)" : "")
              .attr('dx', $$.gridTextDx)
              .attr('dy', -5)
              .style("opacity", 0);
          // update
          yv = $$.yv.bind($$);
          $$.ygridLines.select('line')
            .transition().duration(duration)
              .attr("x1", config.axis_rotated ? yv : 0)
              .attr("x2", config.axis_rotated ? yv : $$.width)
              .attr("y1", config.axis_rotated ? 0 : yv)
              .attr("y2", config.axis_rotated ? $$.height : yv)
              .style("opacity", 1);
          $$.ygridLines.select('text')
            .transition().duration(duration)
              .attr("x", config.axis_rotated ? $$.xGridTextX.bind($$) : $$.yGridTextX.bind($$))
              .attr("y", yv)
              .text(function (d) { return d.text; })
              .style("opacity", 1);
          // exit
          $$.ygridLines.exit().transition().duration(duration)
              .style("opacity", 0)
              .remove();
      };
      c3_chart_internal_fn.redrawGrid = function (withTransition) {
          var $$ = this, config = $$.config, xv = $$.xv.bind($$),
              lines = $$.xgridLines.select('line'),
              texts = $$.xgridLines.select('text');
          return [
              (withTransition ? lines.transition() : lines)
                  .attr("x1", config.axis_rotated ? 0 : xv)
                  .attr("x2", config.axis_rotated ? $$.width : xv)
                  .attr("y1", config.axis_rotated ? xv : 0)
                  .attr("y2", config.axis_rotated ? xv : $$.height)
                  .style("opacity", 1),
              (withTransition ? texts.transition() : texts)
                  .attr("x", config.axis_rotated ? $$.yGridTextX.bind($$) : $$.xGridTextX.bind($$))
                  .attr("y", xv)
                  .text(function (d) { return d.text; })
                  .style("opacity", 1)
          ];
      };
      c3_chart_internal_fn.showXGridFocus = function (selectedData) {
          var $$ = this, config = $$.config,
              dataToShow = selectedData.filter(function (d) { return d && isValue(d.value); }),
              focusEl = $$.main.selectAll('line.' + CLASS.xgridFocus),
              xx = $$.xx.bind($$);
          if (! config.tooltip_show) { return; }
          // Hide when scatter plot exists
          if ($$.hasType('scatter') || $$.hasArcType()) { return; }
          focusEl
              .style("visibility", "visible")
              .data([dataToShow[0]])
              .attr(config.axis_rotated ? 'y1' : 'x1', xx)
              .attr(config.axis_rotated ? 'y2' : 'x2', xx);
          $$.smoothLines(focusEl, 'grid');
      };
      c3_chart_internal_fn.hideXGridFocus = function () {
          this.main.select('line.' + CLASS.xgridFocus).style("visibility", "hidden");
      };
      c3_chart_internal_fn.updateXgridFocus = function () {
          var $$ = this, config = $$.config;
          $$.main.select('line.' + CLASS.xgridFocus)
              .attr("x1", config.axis_rotated ? 0 : -10)
              .attr("x2", config.axis_rotated ? $$.width : -10)
              .attr("y1", config.axis_rotated ? -10 : 0)
              .attr("y2", config.axis_rotated ? -10 : $$.height);
      };
      c3_chart_internal_fn.generateGridData = function (type, scale) {
          var $$ = this,
              gridData = [], xDomain, firstYear, lastYear, i,
              tickNum = $$.main.select("." + CLASS.axisX).selectAll('.tick').size();
          if (type === 'year') {
              xDomain = $$.getXDomain();
              firstYear = xDomain[0].getFullYear();
              lastYear = xDomain[1].getFullYear();
              for (i = firstYear; i <= lastYear; i++) {
                  gridData.push(new Date(i + '-01-01 00:00:00'));
              }
          } else {
              gridData = scale.ticks(10);
              if (gridData.length > tickNum) { // use only int
                  gridData = gridData.filter(function (d) { return ("" + d).indexOf('.') < 0; });
              }
          }
          return gridData;
      };
      c3_chart_internal_fn.getGridFilterToRemove = function (params) {
          return params ? function (line) {
              var found = false;
              [].concat(params).forEach(function (param) {
                  if ((('value' in param && line.value === param.value) || ('class' in param && line['class'] === param['class']))) {
                      found = true;
                  }
              });
              return found;
          } : function () { return true; };
      };
      c3_chart_internal_fn.removeGridLines = function (params, forX) {
          var $$ = this, config = $$.config,
              toRemove = $$.getGridFilterToRemove(params),
              toShow = function (line) { return !toRemove(line); },
              classLines = forX ? CLASS.xgridLines : CLASS.ygridLines,
              classLine = forX ? CLASS.xgridLine : CLASS.ygridLine;
          $$.main.select('.' + classLines).selectAll('.' + classLine).filter(toRemove)
              .transition().duration(config.transition_duration)
              .style('opacity', 0).remove();
          if (forX) {
              config.grid_x_lines = config.grid_x_lines.filter(toShow);
          } else {
              config.grid_y_lines = config.grid_y_lines.filter(toShow);
          }
      };
  
      c3_chart_internal_fn.initTooltip = function () {
          var $$ = this, config = $$.config, i;
          $$.tooltip = $$.selectChart
              .style("position", "relative")
            .append("div")
              .attr('class', CLASS.tooltipContainer)
              .style("position", "absolute")
              .style("pointer-events", "none")
              .style("display", "none");
          // Show tooltip if needed
          if (config.tooltip_init_show) {
              if ($$.isTimeSeries() && isString(config.tooltip_init_x)) {
                  config.tooltip_init_x = $$.parseDate(config.tooltip_init_x);
                  for (i = 0; i < $$.data.targets[0].values.length; i++) {
                      if (($$.data.targets[0].values[i].x - config.tooltip_init_x) === 0) { break; }
                  }
                  config.tooltip_init_x = i;
              }
              $$.tooltip.html(config.tooltip_contents.call($$, $$.data.targets.map(function (d) {
                  return $$.addName(d.values[config.tooltip_init_x]);
              }), $$.axis.getXAxisTickFormat(), $$.getYFormat($$.hasArcType()), $$.color));
              $$.tooltip.style("top", config.tooltip_init_position.top)
                  .style("left", config.tooltip_init_position.left)
                  .style("display", "block");
          }
      };
      c3_chart_internal_fn.getTooltipContent = function (d, defaultTitleFormat, defaultValueFormat, color) {
          var $$ = this, config = $$.config,
              titleFormat = config.tooltip_format_title || defaultTitleFormat,
              nameFormat = config.tooltip_format_name || function (name) { return name; },
              valueFormat = config.tooltip_format_value || defaultValueFormat,
              text, i, title, value, name, bgcolor,
              orderAsc = $$.isOrderAsc();
  
          if (config.data_groups.length === 0) {
              d.sort(function(a,b){
                  return orderAsc ? a.value - b.value : b.value - a.value;
              });
          } else {
              var ids = $$.orderTargets($$.data.targets).map(function (i) {
                  return i.id;
              });
              d.sort(function(a, b) {
                  if (a.value > 0 && b.value > 0) {
                      return orderAsc ? ids.indexOf(a.id) - ids.indexOf(b.id) : ids.indexOf(b.id) - ids.indexOf(a.id);
                  } else {
                      return orderAsc ? a.value - b.value : b.value - a.value;
                  }
              });
          }
  
          for (i = 0; i < d.length; i++) {
              if (! (d[i] && (d[i].value || d[i].value === 0))) { continue; }
  
              if (! text) {
                  title = titleFormat ? titleFormat(d[i].x) : d[i].x;
                  text = "<table class='" + $$.CLASS.tooltip + "'>" + (title || title === 0 ? "<tr><th colspan='2'>" + title + "</th></tr>" : "");
              }
  
              value = valueFormat(d[i].value, d[i].ratio, d[i].id, d[i].index);
              if (value !== undefined) {
                  // Skip elements when their name is set to null
                  if (d[i].name === null) { continue; }
                  name = nameFormat(d[i].name, d[i].ratio, d[i].id, d[i].index);
                  bgcolor = $$.levelColor ? $$.levelColor(d[i].value) : color(d[i].id);
  
                  text += "<tr class='" + $$.CLASS.tooltipName + "-" + $$.getTargetSelectorSuffix(d[i].id) + "'>";
                  text += "<td class='name'><span style='background-color:" + bgcolor + "'></span>" + name + "</td>";
                  text += "<td class='value'>" + value + "</td>";
                  text += "</tr>";
              }
          }
          return text + "</table>";
      };
      c3_chart_internal_fn.tooltipPosition = function (dataToShow, tWidth, tHeight, element) {
          var $$ = this, config = $$.config, d3 = $$.d3;
          var svgLeft, tooltipLeft, tooltipRight, tooltipTop, chartRight;
          var forArc = $$.hasArcType(),
              mouse = d3.mouse(element);
        // Determin tooltip position
          if (forArc) {
              tooltipLeft = (($$.width - ($$.isLegendRight ? $$.getLegendWidth() : 0)) / 2) + mouse[0];
              tooltipTop = ($$.height / 2) + mouse[1] + 20;
          } else {
              svgLeft = $$.getSvgLeft(true);
              if (config.axis_rotated) {
                  tooltipLeft = svgLeft + mouse[0] + 100;
                  tooltipRight = tooltipLeft + tWidth;
                  chartRight = $$.currentWidth - $$.getCurrentPaddingRight();
                  tooltipTop = $$.x(dataToShow[0].x) + 20;
              } else {
                  tooltipLeft = svgLeft + $$.getCurrentPaddingLeft(true) + $$.x(dataToShow[0].x) + 20;
                  tooltipRight = tooltipLeft + tWidth;
                  chartRight = svgLeft + $$.currentWidth - $$.getCurrentPaddingRight();
                  tooltipTop = mouse[1] + 15;
              }
  
              if (tooltipRight > chartRight) {
                  // 20 is needed for Firefox to keep tooltip width
                  tooltipLeft -= tooltipRight - chartRight + 20;
              }
              if (tooltipTop + tHeight > $$.currentHeight) {
                  tooltipTop -= tHeight + 30;
              }
          }
          if (tooltipTop < 0) {
              tooltipTop = 0;
          }
          return {top: tooltipTop, left: tooltipLeft};
      };
      c3_chart_internal_fn.showTooltip = function (selectedData, element) {
          var $$ = this, config = $$.config;
          var tWidth, tHeight, position;
          var forArc = $$.hasArcType(),
              dataToShow = selectedData.filter(function (d) { return d && isValue(d.value); }),
              positionFunction = config.tooltip_position || c3_chart_internal_fn.tooltipPosition;
          if (dataToShow.length === 0 || !config.tooltip_show) {
              return;
          }
          $$.tooltip.html(config.tooltip_contents.call($$, selectedData, $$.axis.getXAxisTickFormat(), $$.getYFormat(forArc), $$.color)).style("display", "block");
  
          // Get tooltip dimensions
          tWidth = $$.tooltip.property('offsetWidth');
          tHeight = $$.tooltip.property('offsetHeight');
  
          position = positionFunction.call(this, dataToShow, tWidth, tHeight, element);
          // Set tooltip
          $$.tooltip
              .style("top", position.top + "px")
              .style("left", position.left + 'px');
      };
      c3_chart_internal_fn.hideTooltip = function () {
          this.tooltip.style("display", "none");
      };
  
      c3_chart_internal_fn.initLegend = function () {
          var $$ = this;
          $$.legendItemTextBox = {};
          $$.legendHasRendered = false;
          $$.legend = $$.svg.append("g").attr("transform", $$.getTranslate('legend'));
          if (!$$.config.legend_show) {
              $$.legend.style('visibility', 'hidden');
              $$.hiddenLegendIds = $$.mapToIds($$.data.targets);
              return;
          }
          // MEMO: call here to update legend box and tranlate for all
          // MEMO: translate will be upated by this, so transform not needed in updateLegend()
          $$.updateLegendWithDefaults();
      };
      c3_chart_internal_fn.updateLegendWithDefaults = function () {
          var $$ = this;
          $$.updateLegend($$.mapToIds($$.data.targets), {withTransform: false, withTransitionForTransform: false, withTransition: false});
      };
      c3_chart_internal_fn.updateSizeForLegend = function (legendHeight, legendWidth) {
          var $$ = this, config = $$.config, insetLegendPosition = {
              top: $$.isLegendTop ? $$.getCurrentPaddingTop() + config.legend_inset_y + 5.5 : $$.currentHeight - legendHeight - $$.getCurrentPaddingBottom() - config.legend_inset_y,
              left: $$.isLegendLeft ? $$.getCurrentPaddingLeft() + config.legend_inset_x + 0.5 : $$.currentWidth - legendWidth - $$.getCurrentPaddingRight() - config.legend_inset_x + 0.5
          };
  
          $$.margin3 = {
              top: $$.isLegendRight ? 0 : $$.isLegendInset ? insetLegendPosition.top : $$.currentHeight - legendHeight,
              right: NaN,
              bottom: 0,
              left: $$.isLegendRight ? $$.currentWidth - legendWidth : $$.isLegendInset ? insetLegendPosition.left : 0
          };
      };
      c3_chart_internal_fn.transformLegend = function (withTransition) {
          var $$ = this;
          (withTransition ? $$.legend.transition() : $$.legend).attr("transform", $$.getTranslate('legend'));
      };
      c3_chart_internal_fn.updateLegendStep = function (step) {
          this.legendStep = step;
      };
      c3_chart_internal_fn.updateLegendItemWidth = function (w) {
          this.legendItemWidth = w;
      };
      c3_chart_internal_fn.updateLegendItemHeight = function (h) {
          this.legendItemHeight = h;
      };
      c3_chart_internal_fn.getLegendWidth = function () {
          var $$ = this;
          return $$.config.legend_show ? $$.isLegendRight || $$.isLegendInset ? $$.legendItemWidth * ($$.legendStep + 1) : $$.currentWidth : 0;
      };
      c3_chart_internal_fn.getLegendHeight = function () {
          var $$ = this, h = 0;
          if ($$.config.legend_show) {
              if ($$.isLegendRight) {
                  h = $$.currentHeight;
              } else {
                  h = Math.max(20, $$.legendItemHeight) * ($$.legendStep + 1);
              }
          }
          return h;
      };
      c3_chart_internal_fn.opacityForLegend = function (legendItem) {
          return legendItem.classed(CLASS.legendItemHidden) ? null : 1;
      };
      c3_chart_internal_fn.opacityForUnfocusedLegend = function (legendItem) {
          return legendItem.classed(CLASS.legendItemHidden) ? null : 0.3;
      };
      c3_chart_internal_fn.toggleFocusLegend = function (targetIds, focus) {
          var $$ = this;
          targetIds = $$.mapToTargetIds(targetIds);
          $$.legend.selectAll('.' + CLASS.legendItem)
              .filter(function (id) { return targetIds.indexOf(id) >= 0; })
              .classed(CLASS.legendItemFocused, focus)
            .transition().duration(100)
              .style('opacity', function () {
                  var opacity = focus ? $$.opacityForLegend : $$.opacityForUnfocusedLegend;
                  return opacity.call($$, $$.d3.select(this));
              });
      };
      c3_chart_internal_fn.revertLegend = function () {
          var $$ = this, d3 = $$.d3;
          $$.legend.selectAll('.' + CLASS.legendItem)
              .classed(CLASS.legendItemFocused, false)
              .transition().duration(100)
              .style('opacity', function () { return $$.opacityForLegend(d3.select(this)); });
      };
      c3_chart_internal_fn.showLegend = function (targetIds) {
          var $$ = this, config = $$.config;
          if (!config.legend_show) {
              config.legend_show = true;
              $$.legend.style('visibility', 'visible');
              if (!$$.legendHasRendered) {
                  $$.updateLegendWithDefaults();
              }
          }
          $$.removeHiddenLegendIds(targetIds);
          $$.legend.selectAll($$.selectorLegends(targetIds))
              .style('visibility', 'visible')
              .transition()
              .style('opacity', function () { return $$.opacityForLegend($$.d3.select(this)); });
      };
      c3_chart_internal_fn.hideLegend = function (targetIds) {
          var $$ = this, config = $$.config;
          if (config.legend_show && isEmpty(targetIds)) {
              config.legend_show = false;
              $$.legend.style('visibility', 'hidden');
          }
          $$.addHiddenLegendIds(targetIds);
          $$.legend.selectAll($$.selectorLegends(targetIds))
              .style('opacity', 0)
              .style('visibility', 'hidden');
      };
      c3_chart_internal_fn.clearLegendItemTextBoxCache = function () {
          this.legendItemTextBox = {};
      };
      c3_chart_internal_fn.updateLegend = function (targetIds, options, transitions) {
          var $$ = this, config = $$.config;
          var xForLegend, xForLegendText, xForLegendRect, yForLegend, yForLegendText, yForLegendRect, x1ForLegendTile, x2ForLegendTile, yForLegendTile;
          var paddingTop = 4, paddingRight = 10, maxWidth = 0, maxHeight = 0, posMin = 10, tileWidth = config.legend_item_tile_width + 5;
          var l, totalLength = 0, offsets = {}, widths = {}, heights = {}, margins = [0], steps = {}, step = 0;
          var withTransition, withTransitionForTransform;
          var texts, rects, tiles, background;
  
          // Skip elements when their name is set to null
          targetIds = targetIds.filter(function(id) {
              return !isDefined(config.data_names[id]) || config.data_names[id] !== null;
          });
  
          options = options || {};
          withTransition = getOption(options, "withTransition", true);
          withTransitionForTransform = getOption(options, "withTransitionForTransform", true);
  
          function getTextBox(textElement, id) {
              if (!$$.legendItemTextBox[id]) {
                  $$.legendItemTextBox[id] = $$.getTextRect(textElement.textContent, CLASS.legendItem, textElement);
              }
              return $$.legendItemTextBox[id];
          }
  
          function updatePositions(textElement, id, index) {
              var reset = index === 0, isLast = index === targetIds.length - 1,
                  box = getTextBox(textElement, id),
                  itemWidth = box.width + tileWidth + (isLast && !($$.isLegendRight || $$.isLegendInset) ? 0 : paddingRight) + config.legend_padding,
                  itemHeight = box.height + paddingTop,
                  itemLength = $$.isLegendRight || $$.isLegendInset ? itemHeight : itemWidth,
                  areaLength = $$.isLegendRight || $$.isLegendInset ? $$.getLegendHeight() : $$.getLegendWidth(),
                  margin, maxLength;
  
              // MEMO: care about condifion of step, totalLength
              function updateValues(id, withoutStep) {
                  if (!withoutStep) {
                      margin = (areaLength - totalLength - itemLength) / 2;
                      if (margin < posMin) {
                          margin = (areaLength - itemLength) / 2;
                          totalLength = 0;
                          step++;
                      }
                  }
                  steps[id] = step;
                  margins[step] = $$.isLegendInset ? 10 : margin;
                  offsets[id] = totalLength;
                  totalLength += itemLength;
              }
  
              if (reset) {
                  totalLength = 0;
                  step = 0;
                  maxWidth = 0;
                  maxHeight = 0;
              }
  
              if (config.legend_show && !$$.isLegendToShow(id)) {
                  widths[id] = heights[id] = steps[id] = offsets[id] = 0;
                  return;
              }
  
              widths[id] = itemWidth;
              heights[id] = itemHeight;
  
              if (!maxWidth || itemWidth >= maxWidth) { maxWidth = itemWidth; }
              if (!maxHeight || itemHeight >= maxHeight) { maxHeight = itemHeight; }
              maxLength = $$.isLegendRight || $$.isLegendInset ? maxHeight : maxWidth;
  
              if (config.legend_equally) {
                  Object.keys(widths).forEach(function (id) { widths[id] = maxWidth; });
                  Object.keys(heights).forEach(function (id) { heights[id] = maxHeight; });
                  margin = (areaLength - maxLength * targetIds.length) / 2;
                  if (margin < posMin) {
                      totalLength = 0;
                      step = 0;
                      targetIds.forEach(function (id) { updateValues(id); });
                  }
                  else {
                      updateValues(id, true);
                  }
              } else {
                  updateValues(id);
              }
          }
  
          if ($$.isLegendInset) {
              step = config.legend_inset_step ? config.legend_inset_step : targetIds.length;
              $$.updateLegendStep(step);
          }
  
          if ($$.isLegendRight) {
              xForLegend = function (id) { return maxWidth * steps[id]; };
              yForLegend = function (id) { return margins[steps[id]] + offsets[id]; };
          } else if ($$.isLegendInset) {
              xForLegend = function (id) { return maxWidth * steps[id] + 10; };
              yForLegend = function (id) { return margins[steps[id]] + offsets[id]; };
          } else {
              xForLegend = function (id) { return margins[steps[id]] + offsets[id]; };
              yForLegend = function (id) { return maxHeight * steps[id]; };
          }
          xForLegendText = function (id, i) { return xForLegend(id, i) + 4 + config.legend_item_tile_width; };
          yForLegendText = function (id, i) { return yForLegend(id, i) + 9; };
          xForLegendRect = function (id, i) { return xForLegend(id, i); };
          yForLegendRect = function (id, i) { return yForLegend(id, i) - 5; };
          x1ForLegendTile = function (id, i) { return xForLegend(id, i) - 2; };
          x2ForLegendTile = function (id, i) { return xForLegend(id, i) - 2 + config.legend_item_tile_width; };
          yForLegendTile = function (id, i) { return yForLegend(id, i) + 4; };
  
          // Define g for legend area
          l = $$.legend.selectAll('.' + CLASS.legendItem)
              .data(targetIds)
              .enter().append('g')
              .attr('class', function (id) { return $$.generateClass(CLASS.legendItem, id); })
              .style('visibility', function (id) { return $$.isLegendToShow(id) ? 'visible' : 'hidden'; })
              .style('cursor', 'pointer')
              .on('click', function (id) {
                  if (config.legend_item_onclick) {
                      config.legend_item_onclick.call($$, id);
                  } else {
                      if ($$.d3.event.altKey) {
                          $$.api.hide();
                          $$.api.show(id);
                      } else {
                          $$.api.toggle(id);
                          $$.isTargetToShow(id) ? $$.api.focus(id) : $$.api.revert();
                      }
                  }
              })
              .on('mouseover', function (id) {
                  if (config.legend_item_onmouseover) {
                      config.legend_item_onmouseover.call($$, id);
                  }
                  else {
                      $$.d3.select(this).classed(CLASS.legendItemFocused, true);
                      if (!$$.transiting && $$.isTargetToShow(id)) {
                          $$.api.focus(id);
                      }
                  }
              })
              .on('mouseout', function (id) {
                  if (config.legend_item_onmouseout) {
                      config.legend_item_onmouseout.call($$, id);
                  }
                  else {
                      $$.d3.select(this).classed(CLASS.legendItemFocused, false);
                      $$.api.revert();
                  }
              });
          l.append('text')
              .text(function (id) { return isDefined(config.data_names[id]) ? config.data_names[id] : id; })
              .each(function (id, i) { updatePositions(this, id, i); })
              .style("pointer-events", "none")
              .attr('x', $$.isLegendRight || $$.isLegendInset ? xForLegendText : -200)
              .attr('y', $$.isLegendRight || $$.isLegendInset ? -200 : yForLegendText);
          l.append('rect')
              .attr("class", CLASS.legendItemEvent)
              .style('fill-opacity', 0)
              .attr('x', $$.isLegendRight || $$.isLegendInset ? xForLegendRect : -200)
              .attr('y', $$.isLegendRight || $$.isLegendInset ? -200 : yForLegendRect);
          l.append('line')
              .attr('class', CLASS.legendItemTile)
              .style('stroke', $$.color)
              .style("pointer-events", "none")
              .attr('x1', $$.isLegendRight || $$.isLegendInset ? x1ForLegendTile : -200)
              .attr('y1', $$.isLegendRight || $$.isLegendInset ? -200 : yForLegendTile)
              .attr('x2', $$.isLegendRight || $$.isLegendInset ? x2ForLegendTile : -200)
              .attr('y2', $$.isLegendRight || $$.isLegendInset ? -200 : yForLegendTile)
              .attr('stroke-width', config.legend_item_tile_height);
  
          // Set background for inset legend
          background = $$.legend.select('.' + CLASS.legendBackground + ' rect');
          if ($$.isLegendInset && maxWidth > 0 && background.size() === 0) {
              background = $$.legend.insert('g', '.' + CLASS.legendItem)
                  .attr("class", CLASS.legendBackground)
                  .append('rect');
          }
  
          texts = $$.legend.selectAll('text')
              .data(targetIds)
              .text(function (id) { return isDefined(config.data_names[id]) ? config.data_names[id] : id; }) // MEMO: needed for update
              .each(function (id, i) { updatePositions(this, id, i); });
          (withTransition ? texts.transition() : texts)
              .attr('x', xForLegendText)
              .attr('y', yForLegendText);
  
          rects = $$.legend.selectAll('rect.' + CLASS.legendItemEvent)
              .data(targetIds);
          (withTransition ? rects.transition() : rects)
              .attr('width', function (id) { return widths[id]; })
              .attr('height', function (id) { return heights[id]; })
              .attr('x', xForLegendRect)
              .attr('y', yForLegendRect);
  
          tiles = $$.legend.selectAll('line.' + CLASS.legendItemTile)
                  .data(targetIds);
              (withTransition ? tiles.transition() : tiles)
                  .style('stroke', $$.color)
                  .attr('x1', x1ForLegendTile)
                  .attr('y1', yForLegendTile)
                  .attr('x2', x2ForLegendTile)
                  .attr('y2', yForLegendTile);
  
          if (background) {
              (withTransition ? background.transition() : background)
                  .attr('height', $$.getLegendHeight() - 12)
                  .attr('width', maxWidth * (step + 1) + 10);
          }
  
          // toggle legend state
          $$.legend.selectAll('.' + CLASS.legendItem)
              .classed(CLASS.legendItemHidden, function (id) { return !$$.isTargetToShow(id); });
  
          // Update all to reflect change of legend
          $$.updateLegendItemWidth(maxWidth);
          $$.updateLegendItemHeight(maxHeight);
          $$.updateLegendStep(step);
          // Update size and scale
          $$.updateSizes();
          $$.updateScales();
          $$.updateSvgSize();
          // Update g positions
          $$.transformAll(withTransitionForTransform, transitions);
          $$.legendHasRendered = true;
      };
  
      c3_chart_internal_fn.initTitle = function () {
          var $$ = this;
          $$.title = $$.svg.append("text")
                .text($$.config.title_text)
                .attr("class", $$.CLASS.title);
      };
      c3_chart_internal_fn.redrawTitle = function () {
          var $$ = this;
          $$.title
                .attr("x", $$.xForTitle.bind($$))
                .attr("y", $$.yForTitle.bind($$));
      };
      c3_chart_internal_fn.xForTitle = function () {
          var $$ = this, config = $$.config, position = config.title_position || 'left', x;
          if (position.indexOf('right') >= 0) {
              x = $$.currentWidth - $$.getTextRect($$.title.node().textContent, $$.CLASS.title, $$.title.node()).width - config.title_padding.right;
          } else if (position.indexOf('center') >= 0) {
              x = ($$.currentWidth - $$.getTextRect($$.title.node().textContent, $$.CLASS.title, $$.title.node()).width) / 2;
          } else { // left
              x = config.title_padding.left;
          }
          return x;
      };
      c3_chart_internal_fn.yForTitle = function () {
          var $$ = this;
          return $$.config.title_padding.top + $$.getTextRect($$.title.node().textContent, $$.CLASS.title, $$.title.node()).height;
      };
      c3_chart_internal_fn.getTitlePadding = function() {
          var $$ = this;
          return $$.yForTitle() + $$.config.title_padding.bottom;
      };
  
      function Axis(owner) {
          API.call(this, owner);
      }
  
      inherit(API, Axis);
  
      Axis.prototype.init = function init() {
  
          var $$ = this.owner, config = $$.config, main = $$.main;
          $$.axes.x = main.append("g")
              .attr("class", CLASS.axis + ' ' + CLASS.axisX)
              .attr("clip-path", $$.clipPathForXAxis)
              .attr("transform", $$.getTranslate('x'))
              .style("visibility", config.axis_x_show ? 'visible' : 'hidden');
          $$.axes.x.append("text")
              .attr("class", CLASS.axisXLabel)
              .attr("transform", config.axis_rotated ? "rotate(-90)" : "")
              .style("text-anchor", this.textAnchorForXAxisLabel.bind(this));
          $$.axes.y = main.append("g")
              .attr("class", CLASS.axis + ' ' + CLASS.axisY)
              .attr("clip-path", config.axis_y_inner ? "" : $$.clipPathForYAxis)
              .attr("transform", $$.getTranslate('y'))
              .style("visibility", config.axis_y_show ? 'visible' : 'hidden');
          $$.axes.y.append("text")
              .attr("class", CLASS.axisYLabel)
              .attr("transform", config.axis_rotated ? "" : "rotate(-90)")
              .style("text-anchor", this.textAnchorForYAxisLabel.bind(this));
  
          $$.axes.y2 = main.append("g")
              .attr("class", CLASS.axis + ' ' + CLASS.axisY2)
              // clip-path?
              .attr("transform", $$.getTranslate('y2'))
              .style("visibility", config.axis_y2_show ? 'visible' : 'hidden');
          $$.axes.y2.append("text")
              .attr("class", CLASS.axisY2Label)
              .attr("transform", config.axis_rotated ? "" : "rotate(-90)")
              .style("text-anchor", this.textAnchorForY2AxisLabel.bind(this));
      };
      Axis.prototype.getXAxis = function getXAxis(scale, orient, tickFormat, tickValues, withOuterTick, withoutTransition, withoutRotateTickText) {
          var $$ = this.owner, config = $$.config,
              axisParams = {
                  isCategory: $$.isCategorized(),
                  withOuterTick: withOuterTick,
                  tickMultiline: config.axis_x_tick_multiline,
                  tickWidth: config.axis_x_tick_width,
                  tickTextRotate: withoutRotateTickText ? 0 : config.axis_x_tick_rotate,
                  withoutTransition: withoutTransition,
              },
              axis = c3_axis($$.d3, axisParams).scale(scale).orient(orient);
  
          if ($$.isTimeSeries() && tickValues && typeof tickValues !== "function") {
              tickValues = tickValues.map(function (v) { return $$.parseDate(v); });
          }
  
          // Set tick
          axis.tickFormat(tickFormat).tickValues(tickValues);
          if ($$.isCategorized()) {
              axis.tickCentered(config.axis_x_tick_centered);
              if (isEmpty(config.axis_x_tick_culling)) {
                  config.axis_x_tick_culling = false;
              }
          }
  
          return axis;
      };
      Axis.prototype.updateXAxisTickValues = function updateXAxisTickValues(targets, axis) {
          var $$ = this.owner, config = $$.config, tickValues;
          if (config.axis_x_tick_fit || config.axis_x_tick_count) {
              tickValues = this.generateTickValues($$.mapTargetsToUniqueXs(targets), config.axis_x_tick_count, $$.isTimeSeries());
          }
          if (axis) {
              axis.tickValues(tickValues);
          } else {
              $$.xAxis.tickValues(tickValues);
              $$.subXAxis.tickValues(tickValues);
          }
          return tickValues;
      };
      Axis.prototype.getYAxis = function getYAxis(scale, orient, tickFormat, tickValues, withOuterTick, withoutTransition) {
          var axisParams = {
              withOuterTick: withOuterTick,
              withoutTransition: withoutTransition,
          },
              $$ = this.owner,
              d3 = $$.d3,
              config = $$.config,
              axis = c3_axis(d3, axisParams).scale(scale).orient(orient).tickFormat(tickFormat);
          if ($$.isTimeSeriesY()) {
              axis.ticks(d3.time[config.axis_y_tick_time_value], config.axis_y_tick_time_interval);
          } else {
              axis.tickValues(tickValues);
          }
          return axis;
      };
      Axis.prototype.getId = function getId(id) {
          var config = this.owner.config;
          return id in config.data_axes ? config.data_axes[id] : 'y';
      };
      Axis.prototype.getXAxisTickFormat = function getXAxisTickFormat() {
          var $$ = this.owner, config = $$.config,
              format = $$.isTimeSeries() ? $$.defaultAxisTimeFormat : $$.isCategorized() ? $$.categoryName : function (v) { return v < 0 ? v.toFixed(0) : v; };
          if (config.axis_x_tick_format) {
              if (isFunction(config.axis_x_tick_format)) {
                  format = config.axis_x_tick_format;
              } else if ($$.isTimeSeries()) {
                  format = function (date) {
                      return date ? $$.axisTimeFormat(config.axis_x_tick_format)(date) : "";
                  };
              }
          }
          return isFunction(format) ? function (v) { return format.call($$, v); } : format;
      };
      Axis.prototype.getTickValues = function getTickValues(tickValues, axis) {
          return tickValues ? tickValues : axis ? axis.tickValues() : undefined;
      };
      Axis.prototype.getXAxisTickValues = function getXAxisTickValues() {
          return this.getTickValues(this.owner.config.axis_x_tick_values, this.owner.xAxis);
      };
      Axis.prototype.getYAxisTickValues = function getYAxisTickValues() {
          return this.getTickValues(this.owner.config.axis_y_tick_values, this.owner.yAxis);
      };
      Axis.prototype.getY2AxisTickValues = function getY2AxisTickValues() {
          return this.getTickValues(this.owner.config.axis_y2_tick_values, this.owner.y2Axis);
      };
      Axis.prototype.getLabelOptionByAxisId = function getLabelOptionByAxisId(axisId) {
          var $$ = this.owner, config = $$.config, option;
          if (axisId === 'y') {
              option = config.axis_y_label;
          } else if (axisId === 'y2') {
              option = config.axis_y2_label;
          } else if (axisId === 'x') {
              option = config.axis_x_label;
          }
          return option;
      };
      Axis.prototype.getLabelText = function getLabelText(axisId) {
          var option = this.getLabelOptionByAxisId(axisId);
          return isString(option) ? option : option ? option.text : null;
      };
      Axis.prototype.setLabelText = function setLabelText(axisId, text) {
          var $$ = this.owner, config = $$.config,
              option = this.getLabelOptionByAxisId(axisId);
          if (isString(option)) {
              if (axisId === 'y') {
                  config.axis_y_label = text;
              } else if (axisId === 'y2') {
                  config.axis_y2_label = text;
              } else if (axisId === 'x') {
                  config.axis_x_label = text;
              }
          } else if (option) {
              option.text = text;
          }
      };
      Axis.prototype.getLabelPosition = function getLabelPosition(axisId, defaultPosition) {
          var option = this.getLabelOptionByAxisId(axisId),
              position = (option && typeof option === 'object' && option.position) ? option.position : defaultPosition;
          return {
              isInner: position.indexOf('inner') >= 0,
              isOuter: position.indexOf('outer') >= 0,
              isLeft: position.indexOf('left') >= 0,
              isCenter: position.indexOf('center') >= 0,
              isRight: position.indexOf('right') >= 0,
              isTop: position.indexOf('top') >= 0,
              isMiddle: position.indexOf('middle') >= 0,
              isBottom: position.indexOf('bottom') >= 0
          };
      };
      Axis.prototype.getXAxisLabelPosition = function getXAxisLabelPosition() {
          return this.getLabelPosition('x', this.owner.config.axis_rotated ? 'inner-top' : 'inner-right');
      };
      Axis.prototype.getYAxisLabelPosition = function getYAxisLabelPosition() {
          return this.getLabelPosition('y', this.owner.config.axis_rotated ? 'inner-right' : 'inner-top');
      };
      Axis.prototype.getY2AxisLabelPosition = function getY2AxisLabelPosition() {
          return this.getLabelPosition('y2', this.owner.config.axis_rotated ? 'inner-right' : 'inner-top');
      };
      Axis.prototype.getLabelPositionById = function getLabelPositionById(id) {
          return id === 'y2' ? this.getY2AxisLabelPosition() : id === 'y' ? this.getYAxisLabelPosition() : this.getXAxisLabelPosition();
      };
      Axis.prototype.textForXAxisLabel = function textForXAxisLabel() {
          return this.getLabelText('x');
      };
      Axis.prototype.textForYAxisLabel = function textForYAxisLabel() {
          return this.getLabelText('y');
      };
      Axis.prototype.textForY2AxisLabel = function textForY2AxisLabel() {
          return this.getLabelText('y2');
      };
      Axis.prototype.xForAxisLabel = function xForAxisLabel(forHorizontal, position) {
          var $$ = this.owner;
          if (forHorizontal) {
              return position.isLeft ? 0 : position.isCenter ? $$.width / 2 : $$.width;
          } else {
              return position.isBottom ? -$$.height : position.isMiddle ? -$$.height / 2 : 0;
          }
      };
      Axis.prototype.dxForAxisLabel = function dxForAxisLabel(forHorizontal, position) {
          if (forHorizontal) {
              return position.isLeft ? "0.5em" : position.isRight ? "-0.5em" : "0";
          } else {
              return position.isTop ? "-0.5em" : position.isBottom ? "0.5em" : "0";
          }
      };
      Axis.prototype.textAnchorForAxisLabel = function textAnchorForAxisLabel(forHorizontal, position) {
          if (forHorizontal) {
              return position.isLeft ? 'start' : position.isCenter ? 'middle' : 'end';
          } else {
              return position.isBottom ? 'start' : position.isMiddle ? 'middle' : 'end';
          }
      };
      Axis.prototype.xForXAxisLabel = function xForXAxisLabel() {
          return this.xForAxisLabel(!this.owner.config.axis_rotated, this.getXAxisLabelPosition());
      };
      Axis.prototype.xForYAxisLabel = function xForYAxisLabel() {
          return this.xForAxisLabel(this.owner.config.axis_rotated, this.getYAxisLabelPosition());
      };
      Axis.prototype.xForY2AxisLabel = function xForY2AxisLabel() {
          return this.xForAxisLabel(this.owner.config.axis_rotated, this.getY2AxisLabelPosition());
      };
      Axis.prototype.dxForXAxisLabel = function dxForXAxisLabel() {
          return this.dxForAxisLabel(!this.owner.config.axis_rotated, this.getXAxisLabelPosition());
      };
      Axis.prototype.dxForYAxisLabel = function dxForYAxisLabel() {
          return this.dxForAxisLabel(this.owner.config.axis_rotated, this.getYAxisLabelPosition());
      };
      Axis.prototype.dxForY2AxisLabel = function dxForY2AxisLabel() {
          return this.dxForAxisLabel(this.owner.config.axis_rotated, this.getY2AxisLabelPosition());
      };
      Axis.prototype.dyForXAxisLabel = function dyForXAxisLabel() {
          var $$ = this.owner, config = $$.config,
              position = this.getXAxisLabelPosition();
          if (config.axis_rotated) {
              return position.isInner ? "1.2em" : -25 - this.getMaxTickWidth('x');
          } else {
              return position.isInner ? "-0.5em" : config.axis_x_height ? config.axis_x_height - 10 : "3em";
          }
      };
      Axis.prototype.dyForYAxisLabel = function dyForYAxisLabel() {
          var $$ = this.owner,
              position = this.getYAxisLabelPosition();
          if ($$.config.axis_rotated) {
              return position.isInner ? "-0.5em" : "3em";
          } else {
              return position.isInner ? "1.2em" : -10 - ($$.config.axis_y_inner ? 0 : (this.getMaxTickWidth('y') + 10));
          }
      };
      Axis.prototype.dyForY2AxisLabel = function dyForY2AxisLabel() {
          var $$ = this.owner,
              position = this.getY2AxisLabelPosition();
          if ($$.config.axis_rotated) {
              return position.isInner ? "1.2em" : "-2.2em";
          } else {
              return position.isInner ? "-0.5em" : 15 + ($$.config.axis_y2_inner ? 0 : (this.getMaxTickWidth('y2') + 15));
          }
      };
      Axis.prototype.textAnchorForXAxisLabel = function textAnchorForXAxisLabel() {
          var $$ = this.owner;
          return this.textAnchorForAxisLabel(!$$.config.axis_rotated, this.getXAxisLabelPosition());
      };
      Axis.prototype.textAnchorForYAxisLabel = function textAnchorForYAxisLabel() {
          var $$ = this.owner;
          return this.textAnchorForAxisLabel($$.config.axis_rotated, this.getYAxisLabelPosition());
      };
      Axis.prototype.textAnchorForY2AxisLabel = function textAnchorForY2AxisLabel() {
          var $$ = this.owner;
          return this.textAnchorForAxisLabel($$.config.axis_rotated, this.getY2AxisLabelPosition());
      };
      Axis.prototype.getMaxTickWidth = function getMaxTickWidth(id, withoutRecompute) {
          var $$ = this.owner, config = $$.config,
              maxWidth = 0, targetsToShow, scale, axis, dummy, svg;
          if (withoutRecompute && $$.currentMaxTickWidths[id]) {
              return $$.currentMaxTickWidths[id];
          }
          if ($$.svg) {
              targetsToShow = $$.filterTargetsToShow($$.data.targets);
              if (id === 'y') {
                  scale = $$.y.copy().domain($$.getYDomain(targetsToShow, 'y'));
                  axis = this.getYAxis(scale, $$.yOrient, config.axis_y_tick_format, $$.yAxisTickValues, false, true);
              } else if (id === 'y2') {
                  scale = $$.y2.copy().domain($$.getYDomain(targetsToShow, 'y2'));
                  axis = this.getYAxis(scale, $$.y2Orient, config.axis_y2_tick_format, $$.y2AxisTickValues, false, true);
              } else {
                  scale = $$.x.copy().domain($$.getXDomain(targetsToShow));
                  axis = this.getXAxis(scale, $$.xOrient, $$.xAxisTickFormat, $$.xAxisTickValues, false, true, true);
                  this.updateXAxisTickValues(targetsToShow, axis);
              }
              dummy = $$.d3.select('body').append('div').classed('c3', true);
              svg = dummy.append("svg").style('visibility', 'hidden').style('position', 'fixed').style('top', 0).style('left', 0),
              svg.append('g').call(axis).each(function () {
                  $$.d3.select(this).selectAll('text').each(function () {
                      var box = this.getBoundingClientRect();
                      if (maxWidth < box.width) { maxWidth = box.width; }
                  });
                  dummy.remove();
              });
          }
          $$.currentMaxTickWidths[id] = maxWidth <= 0 ? $$.currentMaxTickWidths[id] : maxWidth;
          return $$.currentMaxTickWidths[id];
      };
  
      Axis.prototype.updateLabels = function updateLabels(withTransition) {
          var $$ = this.owner;
          var axisXLabel = $$.main.select('.' + CLASS.axisX + ' .' + CLASS.axisXLabel),
              axisYLabel = $$.main.select('.' + CLASS.axisY + ' .' + CLASS.axisYLabel),
              axisY2Label = $$.main.select('.' + CLASS.axisY2 + ' .' + CLASS.axisY2Label);
          (withTransition ? axisXLabel.transition() : axisXLabel)
              .attr("x", this.xForXAxisLabel.bind(this))
              .attr("dx", this.dxForXAxisLabel.bind(this))
              .attr("dy", this.dyForXAxisLabel.bind(this))
              .text(this.textForXAxisLabel.bind(this));
          (withTransition ? axisYLabel.transition() : axisYLabel)
              .attr("x", this.xForYAxisLabel.bind(this))
              .attr("dx", this.dxForYAxisLabel.bind(this))
              .attr("dy", this.dyForYAxisLabel.bind(this))
              .text(this.textForYAxisLabel.bind(this));
          (withTransition ? axisY2Label.transition() : axisY2Label)
              .attr("x", this.xForY2AxisLabel.bind(this))
              .attr("dx", this.dxForY2AxisLabel.bind(this))
              .attr("dy", this.dyForY2AxisLabel.bind(this))
              .text(this.textForY2AxisLabel.bind(this));
      };
      Axis.prototype.getPadding = function getPadding(padding, key, defaultValue, domainLength) {
          var p = typeof padding === 'number' ? padding : padding[key];
          if (!isValue(p)) {
              return defaultValue;
          }
          if (padding.unit === 'ratio') {
              return padding[key] * domainLength;
          }
          // assume padding is pixels if unit is not specified
          return this.convertPixelsToAxisPadding(p, domainLength);
      };
      Axis.prototype.convertPixelsToAxisPadding = function convertPixelsToAxisPadding(pixels, domainLength) {
          var $$ = this.owner,
              length = $$.config.axis_rotated ? $$.width : $$.height;
          return domainLength * (pixels / length);
      };
      Axis.prototype.generateTickValues = function generateTickValues(values, tickCount, forTimeSeries) {
          var tickValues = values, targetCount, start, end, count, interval, i, tickValue;
          if (tickCount) {
              targetCount = isFunction(tickCount) ? tickCount() : tickCount;
              // compute ticks according to tickCount
              if (targetCount === 1) {
                  tickValues = [values[0]];
              } else if (targetCount === 2) {
                  tickValues = [values[0], values[values.length - 1]];
              } else if (targetCount > 2) {
                  count = targetCount - 2;
                  start = values[0];
                  end = values[values.length - 1];
                  interval = (end - start) / (count + 1);
                  // re-construct unique values
                  tickValues = [start];
                  for (i = 0; i < count; i++) {
                      tickValue = +start + interval * (i + 1);
                      tickValues.push(forTimeSeries ? new Date(tickValue) : tickValue);
                  }
                  tickValues.push(end);
              }
          }
          if (!forTimeSeries) { tickValues = tickValues.sort(function (a, b) { return a - b; }); }
          return tickValues;
      };
      Axis.prototype.generateTransitions = function generateTransitions(duration) {
          var $$ = this.owner, axes = $$.axes;
          return {
              axisX: duration ? axes.x.transition().duration(duration) : axes.x,
              axisY: duration ? axes.y.transition().duration(duration) : axes.y,
              axisY2: duration ? axes.y2.transition().duration(duration) : axes.y2,
              axisSubX: duration ? axes.subx.transition().duration(duration) : axes.subx
          };
      };
      Axis.prototype.redraw = function redraw(transitions, isHidden) {
          var $$ = this.owner;
          $$.axes.x.style("opacity", isHidden ? 0 : 1);
          $$.axes.y.style("opacity", isHidden ? 0 : 1);
          $$.axes.y2.style("opacity", isHidden ? 0 : 1);
          $$.axes.subx.style("opacity", isHidden ? 0 : 1);
          transitions.axisX.call($$.xAxis);
          transitions.axisY.call($$.yAxis);
          transitions.axisY2.call($$.y2Axis);
          transitions.axisSubX.call($$.subXAxis);
      };
  
      c3_chart_internal_fn.getClipPath = function (id) {
          var isIE9 = window.navigator.appVersion.toLowerCase().indexOf("msie 9.") >= 0;
          return "url(" + (isIE9 ? "" : document.URL.split('#')[0]) + "#" + id + ")";
      };
      c3_chart_internal_fn.appendClip = function (parent, id) {
          return parent.append("clipPath").attr("id", id).append("rect");
      };
      c3_chart_internal_fn.getAxisClipX = function (forHorizontal) {
          // axis line width + padding for left
          var left = Math.max(30, this.margin.left);
          return forHorizontal ? -(1 + left) : -(left - 1);
      };
      c3_chart_internal_fn.getAxisClipY = function (forHorizontal) {
          return forHorizontal ? -20 : -this.margin.top;
      };
      c3_chart_internal_fn.getXAxisClipX = function () {
          var $$ = this;
          return $$.getAxisClipX(!$$.config.axis_rotated);
      };
      c3_chart_internal_fn.getXAxisClipY = function () {
          var $$ = this;
          return $$.getAxisClipY(!$$.config.axis_rotated);
      };
      c3_chart_internal_fn.getYAxisClipX = function () {
          var $$ = this;
          return $$.config.axis_y_inner ? -1 : $$.getAxisClipX($$.config.axis_rotated);
      };
      c3_chart_internal_fn.getYAxisClipY = function () {
          var $$ = this;
          return $$.getAxisClipY($$.config.axis_rotated);
      };
      c3_chart_internal_fn.getAxisClipWidth = function (forHorizontal) {
          var $$ = this,
              left = Math.max(30, $$.margin.left),
              right = Math.max(30, $$.margin.right);
          // width + axis line width + padding for left/right
          return forHorizontal ? $$.width + 2 + left + right : $$.margin.left + 20;
      };
      c3_chart_internal_fn.getAxisClipHeight = function (forHorizontal) {
          // less than 20 is not enough to show the axis label 'outer' without legend
          return (forHorizontal ? this.margin.bottom : (this.margin.top + this.height)) + 20;
      };
      c3_chart_internal_fn.getXAxisClipWidth = function () {
          var $$ = this;
          return $$.getAxisClipWidth(!$$.config.axis_rotated);
      };
      c3_chart_internal_fn.getXAxisClipHeight = function () {
          var $$ = this;
          return $$.getAxisClipHeight(!$$.config.axis_rotated);
      };
      c3_chart_internal_fn.getYAxisClipWidth = function () {
          var $$ = this;
          return $$.getAxisClipWidth($$.config.axis_rotated) + ($$.config.axis_y_inner ? 20 : 0);
      };
      c3_chart_internal_fn.getYAxisClipHeight = function () {
          var $$ = this;
          return $$.getAxisClipHeight($$.config.axis_rotated);
      };
  
      c3_chart_internal_fn.initPie = function () {
          var $$ = this, d3 = $$.d3, config = $$.config;
          $$.pie = d3.layout.pie().value(function (d) {
              return d.values.reduce(function (a, b) { return a + b.value; }, 0);
          });
          if (!config.data_order) {
              $$.pie.sort(null);
          }
      };
  
      c3_chart_internal_fn.updateRadius = function () {
          var $$ = this, config = $$.config,
              w = config.gauge_width || config.donut_width;
          $$.radiusExpanded = Math.min($$.arcWidth, $$.arcHeight) / 2;
          $$.radius = $$.radiusExpanded * 0.95;
          $$.innerRadiusRatio = w ? ($$.radius - w) / $$.radius : 0.6;
          $$.innerRadius = $$.hasType('donut') || $$.hasType('gauge') ? $$.radius * $$.innerRadiusRatio : 0;
      };
  
      c3_chart_internal_fn.updateArc = function () {
          var $$ = this;
          $$.svgArc = $$.getSvgArc();
          $$.svgArcExpanded = $$.getSvgArcExpanded();
          $$.svgArcExpandedSub = $$.getSvgArcExpanded(0.98);
      };
  
      c3_chart_internal_fn.updateAngle = function (d) {
          var $$ = this, config = $$.config,
              found = false, index = 0,
              gMin = config.gauge_min, gMax = config.gauge_max, gTic, gValue;
          $$.pie($$.filterTargetsToShow($$.data.targets)).forEach(function (t) {
              if (! found && t.data.id === d.data.id) {
                  found = true;
                  d = t;
                  d.index = index;
              }
              index++;
          });
          if (isNaN(d.startAngle)) {
              d.startAngle = 0;
          }
          if (isNaN(d.endAngle)) {
              d.endAngle = d.startAngle;
          }
          if ($$.isGaugeType(d.data)) {
              gTic = (Math.PI) / (gMax - gMin);
              gValue = d.value < gMin ? 0 : d.value < gMax ? d.value - gMin : (gMax - gMin);
              d.startAngle = -1 * (Math.PI / 2);
              d.endAngle = d.startAngle + gTic * gValue;
          }
          return found ? d : null;
      };
  
      c3_chart_internal_fn.getSvgArc = function () {
          var $$ = this,
              arc = $$.d3.svg.arc().outerRadius($$.radius).innerRadius($$.innerRadius),
              newArc = function (d, withoutUpdate) {
                  var updated;
                  if (withoutUpdate) { return arc(d); } // for interpolate
                  updated = $$.updateAngle(d);
                  return updated ? arc(updated) : "M 0 0";
              };
          // TODO: extends all function
          newArc.centroid = arc.centroid;
          return newArc;
      };
  
      c3_chart_internal_fn.getSvgArcExpanded = function (rate) {
          var $$ = this,
              arc = $$.d3.svg.arc().outerRadius($$.radiusExpanded * (rate ? rate : 1)).innerRadius($$.innerRadius);
          return function (d) {
              var updated = $$.updateAngle(d);
              return updated ? arc(updated) : "M 0 0";
          };
      };
  
      c3_chart_internal_fn.getArc = function (d, withoutUpdate, force) {
          return force || this.isArcType(d.data) ? this.svgArc(d, withoutUpdate) : "M 0 0";
      };
  
  
      c3_chart_internal_fn.transformForArcLabel = function (d) {
          var $$ = this,
              updated = $$.updateAngle(d), c, x, y, h, ratio, translate = "";
          if (updated && !$$.hasType('gauge')) {
              c = this.svgArc.centroid(updated);
              x = isNaN(c[0]) ? 0 : c[0];
              y = isNaN(c[1]) ? 0 : c[1];
              h = Math.sqrt(x * x + y * y);
              // TODO: ratio should be an option?
              ratio = $$.radius && h ? (36 / $$.radius > 0.375 ? 1.175 - 36 / $$.radius : 0.8) * $$.radius / h : 0;
              translate = "translate(" + (x * ratio) +  ',' + (y * ratio) +  ")";
          }
          return translate;
      };
  
      c3_chart_internal_fn.getArcRatio = function (d) {
          var $$ = this,
              whole = $$.hasType('gauge') ? Math.PI : (Math.PI * 2);
          return d ? (d.endAngle - d.startAngle) / whole : null;
      };
  
      c3_chart_internal_fn.convertToArcData = function (d) {
          return this.addName({
              id: d.data.id,
              value: d.value,
              ratio: this.getArcRatio(d),
              index: d.index
          });
      };
  
      c3_chart_internal_fn.textForArcLabel = function (d) {
          var $$ = this,
              updated, value, ratio, id, format;
          if (! $$.shouldShowArcLabel()) { return ""; }
          updated = $$.updateAngle(d);
          value = updated ? updated.value : null;
          ratio = $$.getArcRatio(updated);
          id = d.data.id;
          if (! $$.hasType('gauge') && ! $$.meetsArcLabelThreshold(ratio)) { return ""; }
          format = $$.getArcLabelFormat();
          return format ? format(value, ratio, id) : $$.defaultArcValueFormat(value, ratio);
      };
  
      c3_chart_internal_fn.expandArc = function (targetIds) {
          var $$ = this, interval;
  
          // MEMO: avoid to cancel transition
          if ($$.transiting) {
              interval = window.setInterval(function () {
                  if (!$$.transiting) {
                      window.clearInterval(interval);
                      if ($$.legend.selectAll('.c3-legend-item-focused').size() > 0) {
                          $$.expandArc(targetIds);
                      }
                  }
              }, 10);
              return;
          }
  
          targetIds = $$.mapToTargetIds(targetIds);
  
          $$.svg.selectAll($$.selectorTargets(targetIds, '.' + CLASS.chartArc)).each(function (d) {
              if (! $$.shouldExpand(d.data.id)) { return; }
              $$.d3.select(this).selectAll('path')
                  .transition().duration($$.expandDuration(d.data.id))
                  .attr("d", $$.svgArcExpanded)
                  .transition().duration($$.expandDuration(d.data.id) * 2)
                  .attr("d", $$.svgArcExpandedSub)
                  .each(function (d) {
                      if ($$.isDonutType(d.data)) {
                          // callback here
                      }
                  });
          });
      };
  
      c3_chart_internal_fn.unexpandArc = function (targetIds) {
          var $$ = this;
  
          if ($$.transiting) { return; }
  
          targetIds = $$.mapToTargetIds(targetIds);
  
          $$.svg.selectAll($$.selectorTargets(targetIds, '.' + CLASS.chartArc)).selectAll('path')
              .transition().duration(function(d) {
                  return $$.expandDuration(d.data.id);
              })
              .attr("d", $$.svgArc);
          $$.svg.selectAll('.' + CLASS.arc)
              .style("opacity", 1);
      };
  
      c3_chart_internal_fn.expandDuration = function (id) {
          var $$ = this, config = $$.config;
  
          if ($$.isDonutType(id)) {
              return config.donut_expand_duration;
          } else if ($$.isGaugeType(id)) {
              return config.gauge_expand_duration;
          } else if ($$.isPieType(id)) {
              return config.pie_expand_duration;
          } else {
              return 50;
          }
  
      };
  
      c3_chart_internal_fn.shouldExpand = function (id) {
          var $$ = this, config = $$.config;
          return ($$.isDonutType(id) && config.donut_expand) ||
                 ($$.isGaugeType(id) && config.gauge_expand) ||
                 ($$.isPieType(id) && config.pie_expand);
      };
  
      c3_chart_internal_fn.shouldShowArcLabel = function () {
          var $$ = this, config = $$.config, shouldShow = true;
          if ($$.hasType('donut')) {
              shouldShow = config.donut_label_show;
          } else if ($$.hasType('pie')) {
              shouldShow = config.pie_label_show;
          }
          // when gauge, always true
          return shouldShow;
      };
  
      c3_chart_internal_fn.meetsArcLabelThreshold = function (ratio) {
          var $$ = this, config = $$.config,
              threshold = $$.hasType('donut') ? config.donut_label_threshold : config.pie_label_threshold;
          return ratio >= threshold;
      };
  
      c3_chart_internal_fn.getArcLabelFormat = function () {
          var $$ = this, config = $$.config,
              format = config.pie_label_format;
          if ($$.hasType('gauge')) {
              format = config.gauge_label_format;
          } else if ($$.hasType('donut')) {
              format = config.donut_label_format;
          }
          return format;
      };
  
      c3_chart_internal_fn.getArcTitle = function () {
          var $$ = this;
          return $$.hasType('donut') ? $$.config.donut_title : "";
      };
  
      c3_chart_internal_fn.updateTargetsForArc = function (targets) {
          var $$ = this, main = $$.main,
              mainPieUpdate, mainPieEnter,
              classChartArc = $$.classChartArc.bind($$),
              classArcs = $$.classArcs.bind($$),
              classFocus = $$.classFocus.bind($$);
          mainPieUpdate = main.select('.' + CLASS.chartArcs).selectAll('.' + CLASS.chartArc)
              .data($$.pie(targets))
              .attr("class", function (d) { return classChartArc(d) + classFocus(d.data); });
          mainPieEnter = mainPieUpdate.enter().append("g")
              .attr("class", classChartArc);
          mainPieEnter.append('g')
              .attr('class', classArcs);
          mainPieEnter.append("text")
              .attr("dy", $$.hasType('gauge') ? "-.1em" : ".35em")
              .style("opacity", 0)
              .style("text-anchor", "middle")
              .style("pointer-events", "none");
          // MEMO: can not keep same color..., but not bad to update color in redraw
          //mainPieUpdate.exit().remove();
      };
  
      c3_chart_internal_fn.initArc = function () {
          var $$ = this;
          $$.arcs = $$.main.select('.' + CLASS.chart).append("g")
              .attr("class", CLASS.chartArcs)
              .attr("transform", $$.getTranslate('arc'));
          $$.arcs.append('text')
              .attr('class', CLASS.chartArcsTitle)
              .style("text-anchor", "middle")
              .text($$.getArcTitle());
      };
  
      c3_chart_internal_fn.redrawArc = function (duration, durationForExit, withTransform) {
          var $$ = this, d3 = $$.d3, config = $$.config, main = $$.main,
              mainArc;
          mainArc = main.selectAll('.' + CLASS.arcs).selectAll('.' + CLASS.arc)
              .data($$.arcData.bind($$));
          mainArc.enter().append('path')
              .attr("class", $$.classArc.bind($$))
              .style("fill", function (d) { return $$.color(d.data); })
              .style("cursor", function (d) { return config.interaction_enabled && config.data_selection_isselectable(d) ? "pointer" : null; })
              .style("opacity", 0)
              .each(function (d) {
                  if ($$.isGaugeType(d.data)) {
                      d.startAngle = d.endAngle = -1 * (Math.PI / 2);
                  }
                  this._current = d;
              });
          mainArc
              .attr("transform", function (d) { return !$$.isGaugeType(d.data) && withTransform ? "scale(0)" : ""; })
              .style("opacity", function (d) { return d === this._current ? 0 : 1; })
              .on('mouseover', config.interaction_enabled ? function (d) {
                  var updated, arcData;
                  if ($$.transiting) { // skip while transiting
                      return;
                  }
                  updated = $$.updateAngle(d);
                  if (updated) {
                      arcData = $$.convertToArcData(updated);
                      // transitions
                      $$.expandArc(updated.data.id);
                      $$.api.focus(updated.data.id);
                      $$.toggleFocusLegend(updated.data.id, true);
                      $$.config.data_onmouseover(arcData, this);
                  }
              } : null)
              .on('mousemove', config.interaction_enabled ? function (d) {
                  var updated = $$.updateAngle(d), arcData, selectedData;
                  if (updated) {
                      arcData = $$.convertToArcData(updated),
                      selectedData = [arcData];
                      $$.showTooltip(selectedData, this);
                  }
              } : null)
              .on('mouseout', config.interaction_enabled ? function (d) {
                  var updated, arcData;
                  if ($$.transiting) { // skip while transiting
                      return;
                  }
                  updated = $$.updateAngle(d);
                  if (updated) {
                      arcData = $$.convertToArcData(updated);
                      // transitions
                      $$.unexpandArc(updated.data.id);
                      $$.api.revert();
                      $$.revertLegend();
                      $$.hideTooltip();
                      $$.config.data_onmouseout(arcData, this);
                  }
              } : null)
              .on('click', config.interaction_enabled ? function (d, i) {
                  var updated = $$.updateAngle(d), arcData;
                  if (updated) {
                      arcData = $$.convertToArcData(updated);
                      if ($$.toggleShape) {
                          $$.toggleShape(this, arcData, i);
                      }
                      $$.config.data_onclick.call($$.api, arcData, this);
                  }
              } : null)
              .each(function () { $$.transiting = true; })
              .transition().duration(duration)
              .attrTween("d", function (d) {
                  var updated = $$.updateAngle(d), interpolate;
                  if (! updated) {
                      return function () { return "M 0 0"; };
                  }
                  //                if (this._current === d) {
                  //                    this._current = {
                  //                        startAngle: Math.PI*2,
                  //                        endAngle: Math.PI*2,
                  //                    };
                  //                }
                  if (isNaN(this._current.startAngle)) {
                      this._current.startAngle = 0;
                  }
                  if (isNaN(this._current.endAngle)) {
                      this._current.endAngle = this._current.startAngle;
                  }
                  interpolate = d3.interpolate(this._current, updated);
                  this._current = interpolate(0);
                  return function (t) {
                      var interpolated = interpolate(t);
                      interpolated.data = d.data; // data.id will be updated by interporator
                      return $$.getArc(interpolated, true);
                  };
              })
              .attr("transform", withTransform ? "scale(1)" : "")
              .style("fill", function (d) {
                  return $$.levelColor ? $$.levelColor(d.data.values[0].value) : $$.color(d.data.id);
              }) // Where gauge reading color would receive customization.
              .style("opacity", 1)
              .call($$.endall, function () {
                  $$.transiting = false;
              });
          mainArc.exit().transition().duration(durationForExit)
              .style('opacity', 0)
              .remove();
          main.selectAll('.' + CLASS.chartArc).select('text')
              .style("opacity", 0)
              .attr('class', function (d) { return $$.isGaugeType(d.data) ? CLASS.gaugeValue : ''; })
              .text($$.textForArcLabel.bind($$))
              .attr("transform", $$.transformForArcLabel.bind($$))
              .style('font-size', function (d) { return $$.isGaugeType(d.data) ? Math.round($$.radius / 5) + 'px' : ''; })
            .transition().duration(duration)
              .style("opacity", function (d) { return $$.isTargetToShow(d.data.id) && $$.isArcType(d.data) ? 1 : 0; });
          main.select('.' + CLASS.chartArcsTitle)
              .style("opacity", $$.hasType('donut') || $$.hasType('gauge') ? 1 : 0);
  
          if ($$.hasType('gauge')) {
              $$.arcs.select('.' + CLASS.chartArcsBackground)
                  .attr("d", function () {
                      var d = {
                          data: [{value: config.gauge_max}],
                          startAngle: -1 * (Math.PI / 2),
                          endAngle: Math.PI / 2
                      };
                      return $$.getArc(d, true, true);
                  });
              $$.arcs.select('.' + CLASS.chartArcsGaugeUnit)
                  .attr("dy", ".75em")
                  .text(config.gauge_label_show ? config.gauge_units : '');
              $$.arcs.select('.' + CLASS.chartArcsGaugeMin)
                  .attr("dx", -1 * ($$.innerRadius + (($$.radius - $$.innerRadius) / 2)) + "px")
                  .attr("dy", "1.2em")
                  .text(config.gauge_label_show ? config.gauge_min : '');
              $$.arcs.select('.' + CLASS.chartArcsGaugeMax)
                  .attr("dx", $$.innerRadius + (($$.radius - $$.innerRadius) / 2) + "px")
                  .attr("dy", "1.2em")
                  .text(config.gauge_label_show ? config.gauge_max : '');
          }
      };
      c3_chart_internal_fn.initGauge = function () {
          var arcs = this.arcs;
          if (this.hasType('gauge')) {
              arcs.append('path')
                  .attr("class", CLASS.chartArcsBackground);
              arcs.append("text")
                  .attr("class", CLASS.chartArcsGaugeUnit)
                  .style("text-anchor", "middle")
                  .style("pointer-events", "none");
              arcs.append("text")
                  .attr("class", CLASS.chartArcsGaugeMin)
                  .style("text-anchor", "middle")
                  .style("pointer-events", "none");
              arcs.append("text")
                  .attr("class", CLASS.chartArcsGaugeMax)
                  .style("text-anchor", "middle")
                  .style("pointer-events", "none");
          }
      };
      c3_chart_internal_fn.getGaugeLabelHeight = function () {
          return this.config.gauge_label_show ? 20 : 0;
      };
  
      c3_chart_internal_fn.initRegion = function () {
          var $$ = this;
          $$.region = $$.main.append('g')
              .attr("clip-path", $$.clipPath)
              .attr("class", CLASS.regions);
      };
      c3_chart_internal_fn.updateRegion = function (duration) {
          var $$ = this, config = $$.config;
  
          // hide if arc type
          $$.region.style('visibility', $$.hasArcType() ? 'hidden' : 'visible');
  
          $$.mainRegion = $$.main.select('.' + CLASS.regions).selectAll('.' + CLASS.region)
              .data(config.regions);
          $$.mainRegion.enter().append('g')
              .attr('class', $$.classRegion.bind($$))
            .append('rect')
              .style("fill-opacity", 0);
          $$.mainRegion.exit().transition().duration(duration)
              .style("opacity", 0)
              .remove();
      };
      c3_chart_internal_fn.redrawRegion = function (withTransition) {
          var $$ = this,
              regions = $$.mainRegion.selectAll('rect'),
              x = $$.regionX.bind($$),
              y = $$.regionY.bind($$),
              w = $$.regionWidth.bind($$),
              h = $$.regionHeight.bind($$);
          return [
              (withTransition ? regions.transition() : regions)
                  .attr("x", x)
                  .attr("y", y)
                  .attr("width", w)
                  .attr("height", h)
                  .style("fill-opacity", function (d) { return isValue(d.opacity) ? d.opacity : 0.1; })
          ];
      };
      c3_chart_internal_fn.regionX = function (d) {
          var $$ = this, config = $$.config,
              xPos, yScale = d.axis === 'y' ? $$.y : $$.y2;
          if (d.axis === 'y' || d.axis === 'y2') {
              xPos = config.axis_rotated ? ('start' in d ? yScale(d.start) : 0) : 0;
          } else {
              xPos = config.axis_rotated ? 0 : ('start' in d ? $$.x($$.isTimeSeries() ? $$.parseDate(d.start) : d.start) : 0);
          }
          return xPos;
      };
      c3_chart_internal_fn.regionY = function (d) {
          var $$ = this, config = $$.config,
              yPos, yScale = d.axis === 'y' ? $$.y : $$.y2;
          if (d.axis === 'y' || d.axis === 'y2') {
              yPos = config.axis_rotated ? 0 : ('end' in d ? yScale(d.end) : 0);
          } else {
              yPos = config.axis_rotated ? ('start' in d ? $$.x($$.isTimeSeries() ? $$.parseDate(d.start) : d.start) : 0) : 0;
          }
          return yPos;
      };
      c3_chart_internal_fn.regionWidth = function (d) {
          var $$ = this, config = $$.config,
              start = $$.regionX(d), end, yScale = d.axis === 'y' ? $$.y : $$.y2;
          if (d.axis === 'y' || d.axis === 'y2') {
              end = config.axis_rotated ? ('end' in d ? yScale(d.end) : $$.width) : $$.width;
          } else {
              end = config.axis_rotated ? $$.width : ('end' in d ? $$.x($$.isTimeSeries() ? $$.parseDate(d.end) : d.end) : $$.width);
          }
          return end < start ? 0 : end - start;
      };
      c3_chart_internal_fn.regionHeight = function (d) {
          var $$ = this, config = $$.config,
              start = this.regionY(d), end, yScale = d.axis === 'y' ? $$.y : $$.y2;
          if (d.axis === 'y' || d.axis === 'y2') {
              end = config.axis_rotated ? $$.height : ('start' in d ? yScale(d.start) : $$.height);
          } else {
              end = config.axis_rotated ? ('end' in d ? $$.x($$.isTimeSeries() ? $$.parseDate(d.end) : d.end) : $$.height) : $$.height;
          }
          return end < start ? 0 : end - start;
      };
      c3_chart_internal_fn.isRegionOnX = function (d) {
          return !d.axis || d.axis === 'x';
      };
  
      c3_chart_internal_fn.drag = function (mouse) {
          var $$ = this, config = $$.config, main = $$.main, d3 = $$.d3;
          var sx, sy, mx, my, minX, maxX, minY, maxY;
  
          if ($$.hasArcType()) { return; }
          if (! config.data_selection_enabled) { return; } // do nothing if not selectable
          if (config.zoom_enabled && ! $$.zoom.altDomain) { return; } // skip if zoomable because of conflict drag dehavior
          if (!config.data_selection_multiple) { return; } // skip when single selection because drag is used for multiple selection
  
          sx = $$.dragStart[0];
          sy = $$.dragStart[1];
          mx = mouse[0];
          my = mouse[1];
          minX = Math.min(sx, mx);
          maxX = Math.max(sx, mx);
          minY = (config.data_selection_grouped) ? $$.margin.top : Math.min(sy, my);
          maxY = (config.data_selection_grouped) ? $$.height : Math.max(sy, my);
  
          main.select('.' + CLASS.dragarea)
              .attr('x', minX)
              .attr('y', minY)
              .attr('width', maxX - minX)
              .attr('height', maxY - minY);
          // TODO: binary search when multiple xs
          main.selectAll('.' + CLASS.shapes).selectAll('.' + CLASS.shape)
              .filter(function (d) { return config.data_selection_isselectable(d); })
              .each(function (d, i) {
                  var shape = d3.select(this),
                      isSelected = shape.classed(CLASS.SELECTED),
                      isIncluded = shape.classed(CLASS.INCLUDED),
                      _x, _y, _w, _h, toggle, isWithin = false, box;
                  if (shape.classed(CLASS.circle)) {
                      _x = shape.attr("cx") * 1;
                      _y = shape.attr("cy") * 1;
                      toggle = $$.togglePoint;
                      isWithin = minX < _x && _x < maxX && minY < _y && _y < maxY;
                  }
                  else if (shape.classed(CLASS.bar)) {
                      box = getPathBox(this);
                      _x = box.x;
                      _y = box.y;
                      _w = box.width;
                      _h = box.height;
                      toggle = $$.togglePath;
                      isWithin = !(maxX < _x || _x + _w < minX) && !(maxY < _y || _y + _h < minY);
                  } else {
                      // line/area selection not supported yet
                      return;
                  }
                  if (isWithin ^ isIncluded) {
                      shape.classed(CLASS.INCLUDED, !isIncluded);
                      // TODO: included/unincluded callback here
                      shape.classed(CLASS.SELECTED, !isSelected);
                      toggle.call($$, !isSelected, shape, d, i);
                  }
              });
      };
  
      c3_chart_internal_fn.dragstart = function (mouse) {
          var $$ = this, config = $$.config;
          if ($$.hasArcType()) { return; }
          if (! config.data_selection_enabled) { return; } // do nothing if not selectable
          $$.dragStart = mouse;
          $$.main.select('.' + CLASS.chart).append('rect')
              .attr('class', CLASS.dragarea)
              .style('opacity', 0.1);
          $$.dragging = true;
      };
  
      c3_chart_internal_fn.dragend = function () {
          var $$ = this, config = $$.config;
          if ($$.hasArcType()) { return; }
          if (! config.data_selection_enabled) { return; } // do nothing if not selectable
          $$.main.select('.' + CLASS.dragarea)
              .transition().duration(100)
              .style('opacity', 0)
              .remove();
          $$.main.selectAll('.' + CLASS.shape)
              .classed(CLASS.INCLUDED, false);
          $$.dragging = false;
      };
  
      c3_chart_internal_fn.selectPoint = function (target, d, i) {
          var $$ = this, config = $$.config,
              cx = (config.axis_rotated ? $$.circleY : $$.circleX).bind($$),
              cy = (config.axis_rotated ? $$.circleX : $$.circleY).bind($$),
              r = $$.pointSelectR.bind($$);
          config.data_onselected.call($$.api, d, target.node());
          // add selected-circle on low layer g
          $$.main.select('.' + CLASS.selectedCircles + $$.getTargetSelectorSuffix(d.id)).selectAll('.' + CLASS.selectedCircle + '-' + i)
              .data([d])
              .enter().append('circle')
              .attr("class", function () { return $$.generateClass(CLASS.selectedCircle, i); })
              .attr("cx", cx)
              .attr("cy", cy)
              .attr("stroke", function () { return $$.color(d); })
              .attr("r", function (d) { return $$.pointSelectR(d) * 1.4; })
              .transition().duration(100)
              .attr("r", r);
      };
      c3_chart_internal_fn.unselectPoint = function (target, d, i) {
          var $$ = this;
          $$.config.data_onunselected.call($$.api, d, target.node());
          // remove selected-circle from low layer g
          $$.main.select('.' + CLASS.selectedCircles + $$.getTargetSelectorSuffix(d.id)).selectAll('.' + CLASS.selectedCircle + '-' + i)
              .transition().duration(100).attr('r', 0)
              .remove();
      };
      c3_chart_internal_fn.togglePoint = function (selected, target, d, i) {
          selected ? this.selectPoint(target, d, i) : this.unselectPoint(target, d, i);
      };
      c3_chart_internal_fn.selectPath = function (target, d) {
          var $$ = this;
          $$.config.data_onselected.call($$, d, target.node());
          target.transition().duration(100)
              .style("fill", function () { return $$.d3.rgb($$.color(d)).brighter(0.75); });
      };
      c3_chart_internal_fn.unselectPath = function (target, d) {
          var $$ = this;
          $$.config.data_onunselected.call($$, d, target.node());
          target.transition().duration(100)
              .style("fill", function () { return $$.color(d); });
      };
      c3_chart_internal_fn.togglePath = function (selected, target, d, i) {
          selected ? this.selectPath(target, d, i) : this.unselectPath(target, d, i);
      };
      c3_chart_internal_fn.getToggle = function (that, d) {
          var $$ = this, toggle;
          if (that.nodeName === 'circle') {
              if ($$.isStepType(d)) {
                  // circle is hidden in step chart, so treat as within the click area
                  toggle = function () {}; // TODO: how to select step chart?
              } else {
                  toggle = $$.togglePoint;
              }
          }
          else if (that.nodeName === 'path') {
              toggle = $$.togglePath;
          }
          return toggle;
      };
      c3_chart_internal_fn.toggleShape = function (that, d, i) {
          var $$ = this, d3 = $$.d3, config = $$.config,
              shape = d3.select(that), isSelected = shape.classed(CLASS.SELECTED),
              toggle = $$.getToggle(that, d).bind($$);
  
          if (config.data_selection_enabled && config.data_selection_isselectable(d)) {
              if (!config.data_selection_multiple) {
                  $$.main.selectAll('.' + CLASS.shapes + (config.data_selection_grouped ? $$.getTargetSelectorSuffix(d.id) : "")).selectAll('.' + CLASS.shape).each(function (d, i) {
                      var shape = d3.select(this);
                      if (shape.classed(CLASS.SELECTED)) { toggle(false, shape.classed(CLASS.SELECTED, false), d, i); }
                  });
              }
              shape.classed(CLASS.SELECTED, !isSelected);
              toggle(!isSelected, shape, d, i);
          }
      };
  
      c3_chart_internal_fn.initBrush = function () {
          var $$ = this, d3 = $$.d3;
          $$.brush = d3.svg.brush().on("brush", function () { $$.redrawForBrush(); });
          $$.brush.update = function () {
              if ($$.context) { $$.context.select('.' + CLASS.brush).call(this); }
              return this;
          };
          $$.brush.scale = function (scale) {
              return $$.config.axis_rotated ? this.y(scale) : this.x(scale);
          };
      };
      c3_chart_internal_fn.initSubchart = function () {
          var $$ = this, config = $$.config,
              context = $$.context = $$.svg.append("g").attr("transform", $$.getTranslate('context')),
              visibility = config.subchart_show ? 'visible' : 'hidden';
  
          context.style('visibility', visibility);
  
          // Define g for chart area
          context.append('g')
              .attr("clip-path", $$.clipPathForSubchart)
              .attr('class', CLASS.chart);
  
          // Define g for bar chart area
          context.select('.' + CLASS.chart).append("g")
              .attr("class", CLASS.chartBars);
  
          // Define g for line chart area
          context.select('.' + CLASS.chart).append("g")
              .attr("class", CLASS.chartLines);
  
          // Add extent rect for Brush
          context.append("g")
              .attr("clip-path", $$.clipPath)
              .attr("class", CLASS.brush)
              .call($$.brush);
  
          // ATTENTION: This must be called AFTER chart added
          // Add Axis
          $$.axes.subx = context.append("g")
              .attr("class", CLASS.axisX)
              .attr("transform", $$.getTranslate('subx'))
              .attr("clip-path", config.axis_rotated ? "" : $$.clipPathForXAxis)
              .style("visibility", config.subchart_axis_x_show ? visibility : 'hidden');
      };
      c3_chart_internal_fn.updateTargetsForSubchart = function (targets) {
          var $$ = this, context = $$.context, config = $$.config,
              contextLineEnter, contextLineUpdate, contextBarEnter, contextBarUpdate,
              classChartBar = $$.classChartBar.bind($$),
              classBars = $$.classBars.bind($$),
              classChartLine = $$.classChartLine.bind($$),
              classLines = $$.classLines.bind($$),
              classAreas = $$.classAreas.bind($$);
  
          if (config.subchart_show) {
              //-- Bar --//
              contextBarUpdate = context.select('.' + CLASS.chartBars).selectAll('.' + CLASS.chartBar)
                  .data(targets)
                  .attr('class', classChartBar);
              contextBarEnter = contextBarUpdate.enter().append('g')
                  .style('opacity', 0)
                  .attr('class', classChartBar);
              // Bars for each data
              contextBarEnter.append('g')
                  .attr("class", classBars);
  
              //-- Line --//
              contextLineUpdate = context.select('.' + CLASS.chartLines).selectAll('.' + CLASS.chartLine)
                  .data(targets)
                  .attr('class', classChartLine);
              contextLineEnter = contextLineUpdate.enter().append('g')
                  .style('opacity', 0)
                  .attr('class', classChartLine);
              // Lines for each data
              contextLineEnter.append("g")
                  .attr("class", classLines);
              // Area
              contextLineEnter.append("g")
                  .attr("class", classAreas);
  
              //-- Brush --//
              context.selectAll('.' + CLASS.brush + ' rect')
                  .attr(config.axis_rotated ? "width" : "height", config.axis_rotated ? $$.width2 : $$.height2);
          }
      };
      c3_chart_internal_fn.updateBarForSubchart = function (durationForExit) {
          var $$ = this;
          $$.contextBar = $$.context.selectAll('.' + CLASS.bars).selectAll('.' + CLASS.bar)
              .data($$.barData.bind($$));
          $$.contextBar.enter().append('path')
              .attr("class", $$.classBar.bind($$))
              .style("stroke", 'none')
              .style("fill", $$.color);
          $$.contextBar
              .style("opacity", $$.initialOpacity.bind($$));
          $$.contextBar.exit().transition().duration(durationForExit)
              .style('opacity', 0)
              .remove();
      };
      c3_chart_internal_fn.redrawBarForSubchart = function (drawBarOnSub, withTransition, duration) {
          (withTransition ? this.contextBar.transition().duration(duration) : this.contextBar)
              .attr('d', drawBarOnSub)
              .style('opacity', 1);
      };
      c3_chart_internal_fn.updateLineForSubchart = function (durationForExit) {
          var $$ = this;
          $$.contextLine = $$.context.selectAll('.' + CLASS.lines).selectAll('.' + CLASS.line)
              .data($$.lineData.bind($$));
          $$.contextLine.enter().append('path')
              .attr('class', $$.classLine.bind($$))
              .style('stroke', $$.color);
          $$.contextLine
              .style("opacity", $$.initialOpacity.bind($$));
          $$.contextLine.exit().transition().duration(durationForExit)
              .style('opacity', 0)
              .remove();
      };
      c3_chart_internal_fn.redrawLineForSubchart = function (drawLineOnSub, withTransition, duration) {
          (withTransition ? this.contextLine.transition().duration(duration) : this.contextLine)
              .attr("d", drawLineOnSub)
              .style('opacity', 1);
      };
      c3_chart_internal_fn.updateAreaForSubchart = function (durationForExit) {
          var $$ = this, d3 = $$.d3;
          $$.contextArea = $$.context.selectAll('.' + CLASS.areas).selectAll('.' + CLASS.area)
              .data($$.lineData.bind($$));
          $$.contextArea.enter().append('path')
              .attr("class", $$.classArea.bind($$))
              .style("fill", $$.color)
              .style("opacity", function () { $$.orgAreaOpacity = +d3.select(this).style('opacity'); return 0; });
          $$.contextArea
              .style("opacity", 0);
          $$.contextArea.exit().transition().duration(durationForExit)
              .style('opacity', 0)
              .remove();
      };
      c3_chart_internal_fn.redrawAreaForSubchart = function (drawAreaOnSub, withTransition, duration) {
          (withTransition ? this.contextArea.transition().duration(duration) : this.contextArea)
              .attr("d", drawAreaOnSub)
              .style("fill", this.color)
              .style("opacity", this.orgAreaOpacity);
      };
      c3_chart_internal_fn.redrawSubchart = function (withSubchart, transitions, duration, durationForExit, areaIndices, barIndices, lineIndices) {
          var $$ = this, d3 = $$.d3, config = $$.config,
              drawAreaOnSub, drawBarOnSub, drawLineOnSub;
  
          $$.context.style('visibility', config.subchart_show ? 'visible' : 'hidden');
  
          // subchart
          if (config.subchart_show) {
              // reflect main chart to extent on subchart if zoomed
              if (d3.event && d3.event.type === 'zoom') {
                  $$.brush.extent($$.x.orgDomain()).update();
              }
              // update subchart elements if needed
              if (withSubchart) {
  
                  // extent rect
                  if (!$$.brush.empty()) {
                      $$.brush.extent($$.x.orgDomain()).update();
                  }
                  // setup drawer - MEMO: this must be called after axis updated
                  drawAreaOnSub = $$.generateDrawArea(areaIndices, true);
                  drawBarOnSub = $$.generateDrawBar(barIndices, true);
                  drawLineOnSub = $$.generateDrawLine(lineIndices, true);
  
                  $$.updateBarForSubchart(duration);
                  $$.updateLineForSubchart(duration);
                  $$.updateAreaForSubchart(duration);
  
                  $$.redrawBarForSubchart(drawBarOnSub, duration, duration);
                  $$.redrawLineForSubchart(drawLineOnSub, duration, duration);
                  $$.redrawAreaForSubchart(drawAreaOnSub, duration, duration);
              }
          }
      };
      c3_chart_internal_fn.redrawForBrush = function () {
          var $$ = this, x = $$.x;
          $$.redraw({
              withTransition: false,
              withY: $$.config.zoom_rescale,
              withSubchart: false,
              withUpdateXDomain: true,
              withDimension: false
          });
          $$.config.subchart_onbrush.call($$.api, x.orgDomain());
      };
      c3_chart_internal_fn.transformContext = function (withTransition, transitions) {
          var $$ = this, subXAxis;
          if (transitions && transitions.axisSubX) {
              subXAxis = transitions.axisSubX;
          } else {
              subXAxis = $$.context.select('.' + CLASS.axisX);
              if (withTransition) { subXAxis = subXAxis.transition(); }
          }
          $$.context.attr("transform", $$.getTranslate('context'));
          subXAxis.attr("transform", $$.getTranslate('subx'));
      };
      c3_chart_internal_fn.getDefaultExtent = function () {
          var $$ = this, config = $$.config,
              extent = isFunction(config.axis_x_extent) ? config.axis_x_extent($$.getXDomain($$.data.targets)) : config.axis_x_extent;
          if ($$.isTimeSeries()) {
              extent = [$$.parseDate(extent[0]), $$.parseDate(extent[1])];
          }
          return extent;
      };
  
      c3_chart_internal_fn.initZoom = function () {
          var $$ = this, d3 = $$.d3, config = $$.config, startEvent;
  
          $$.zoom = d3.behavior.zoom()
              .on("zoomstart", function () {
                  startEvent = d3.event.sourceEvent;
                  $$.zoom.altDomain = d3.event.sourceEvent.altKey ? $$.x.orgDomain() : null;
                  config.zoom_onzoomstart.call($$.api, d3.event.sourceEvent);
              })
              .on("zoom", function () {
                  $$.redrawForZoom.call($$);
              })
              .on('zoomend', function () {
                  var event = d3.event.sourceEvent;
                  // if click, do nothing. otherwise, click interaction will be canceled.
                  if (event && startEvent.clientX === event.clientX && startEvent.clientY === event.clientY) {
                      return;
                  }
                  $$.redrawEventRect();
                  $$.updateZoom();
                  config.zoom_onzoomend.call($$.api, $$.x.orgDomain());
              });
          $$.zoom.scale = function (scale) {
              return config.axis_rotated ? this.y(scale) : this.x(scale);
          };
          $$.zoom.orgScaleExtent = function () {
              var extent = config.zoom_extent ? config.zoom_extent : [1, 10];
              return [extent[0], Math.max($$.getMaxDataCount() / extent[1], extent[1])];
          };
          $$.zoom.updateScaleExtent = function () {
              var ratio = diffDomain($$.x.orgDomain()) / diffDomain($$.getZoomDomain()),
                  extent = this.orgScaleExtent();
              this.scaleExtent([extent[0] * ratio, extent[1] * ratio]);
              return this;
          };
      };
      c3_chart_internal_fn.getZoomDomain = function () {
          var $$ = this, config = $$.config, d3 = $$.d3,
              min = d3.min([$$.orgXDomain[0], config.zoom_x_min]),
              max = d3.max([$$.orgXDomain[1], config.zoom_x_max]);
          return [min, max];
      };
      c3_chart_internal_fn.updateZoom = function () {
          var $$ = this, z = $$.config.zoom_enabled ? $$.zoom : function () {};
          $$.main.select('.' + CLASS.zoomRect).call(z).on("dblclick.zoom", null);
          $$.main.selectAll('.' + CLASS.eventRect).call(z).on("dblclick.zoom", null);
      };
      c3_chart_internal_fn.redrawForZoom = function () {
          var $$ = this, d3 = $$.d3, config = $$.config, zoom = $$.zoom, x = $$.x;
          if (!config.zoom_enabled) {
              return;
          }
          if ($$.filterTargetsToShow($$.data.targets).length === 0) {
              return;
          }
          if (d3.event.sourceEvent.type === 'mousemove' && zoom.altDomain) {
              x.domain(zoom.altDomain);
              zoom.scale(x).updateScaleExtent();
              return;
          }
          if ($$.isCategorized() && x.orgDomain()[0] === $$.orgXDomain[0]) {
              x.domain([$$.orgXDomain[0] - 1e-10, x.orgDomain()[1]]);
          }
          $$.redraw({
              withTransition: false,
              withY: config.zoom_rescale,
              withSubchart: false,
              withEventRect: false,
              withDimension: false
          });
          if (d3.event.sourceEvent.type === 'mousemove') {
              $$.cancelClick = true;
          }
          config.zoom_onzoom.call($$.api, x.orgDomain());
      };
  
      c3_chart_internal_fn.generateColor = function () {
          var $$ = this, config = $$.config, d3 = $$.d3,
              colors = config.data_colors,
              pattern = notEmpty(config.color_pattern) ? config.color_pattern : d3.scale.category10().range(),
              callback = config.data_color,
              ids = [];
  
          return function (d) {
              var id = d.id || (d.data && d.data.id) || d, color;
  
              // if callback function is provided
              if (colors[id] instanceof Function) {
                  color = colors[id](d);
              }
              // if specified, choose that color
              else if (colors[id]) {
                  color = colors[id];
              }
              // if not specified, choose from pattern
              else {
                  if (ids.indexOf(id) < 0) { ids.push(id); }
                  color = pattern[ids.indexOf(id) % pattern.length];
                  colors[id] = color;
              }
              return callback instanceof Function ? callback(color, d) : color;
          };
      };
      c3_chart_internal_fn.generateLevelColor = function () {
          var $$ = this, config = $$.config,
              colors = config.color_pattern,
              threshold = config.color_threshold,
              asValue = threshold.unit === 'value',
              values = threshold.values && threshold.values.length ? threshold.values : [],
              max = threshold.max || 100;
          return notEmpty(config.color_threshold) ? function (value) {
              var i, v, color = colors[colors.length - 1];
              for (i = 0; i < values.length; i++) {
                  v = asValue ? value : (value * 100 / max);
                  if (v < values[i]) {
                      color = colors[i];
                      break;
                  }
              }
              return color;
          } : null;
      };
  
      c3_chart_internal_fn.getYFormat = function (forArc) {
          var $$ = this,
              formatForY = forArc && !$$.hasType('gauge') ? $$.defaultArcValueFormat : $$.yFormat,
              formatForY2 = forArc && !$$.hasType('gauge') ? $$.defaultArcValueFormat : $$.y2Format;
          return function (v, ratio, id) {
              var format = $$.axis.getId(id) === 'y2' ? formatForY2 : formatForY;
              return format.call($$, v, ratio);
          };
      };
      c3_chart_internal_fn.yFormat = function (v) {
          var $$ = this, config = $$.config,
              format = config.axis_y_tick_format ? config.axis_y_tick_format : $$.defaultValueFormat;
          return format(v);
      };
      c3_chart_internal_fn.y2Format = function (v) {
          var $$ = this, config = $$.config,
              format = config.axis_y2_tick_format ? config.axis_y2_tick_format : $$.defaultValueFormat;
          return format(v);
      };
      c3_chart_internal_fn.defaultValueFormat = function (v) {
          return isValue(v) ? +v : "";
      };
      c3_chart_internal_fn.defaultArcValueFormat = function (v, ratio) {
          return (ratio * 100).toFixed(1) + '%';
      };
      c3_chart_internal_fn.dataLabelFormat = function (targetId) {
          var $$ = this, data_labels = $$.config.data_labels,
              format, defaultFormat = function (v) { return isValue(v) ? +v : ""; };
          // find format according to axis id
          if (typeof data_labels.format === 'function') {
              format = data_labels.format;
          } else if (typeof data_labels.format === 'object') {
              if (data_labels.format[targetId]) {
                  format = data_labels.format[targetId] === true ? defaultFormat : data_labels.format[targetId];
              } else {
                  format = function () { return ''; };
              }
          } else {
              format = defaultFormat;
          }
          return format;
      };
  
      c3_chart_internal_fn.hasCaches = function (ids) {
          for (var i = 0; i < ids.length; i++) {
              if (! (ids[i] in this.cache)) { return false; }
          }
          return true;
      };
      c3_chart_internal_fn.addCache = function (id, target) {
          this.cache[id] = this.cloneTarget(target);
      };
      c3_chart_internal_fn.getCaches = function (ids) {
          var targets = [], i;
          for (i = 0; i < ids.length; i++) {
              if (ids[i] in this.cache) { targets.push(this.cloneTarget(this.cache[ids[i]])); }
          }
          return targets;
      };
  
      var CLASS = c3_chart_internal_fn.CLASS = {
          target: 'c3-target',
          chart: 'c3-chart',
          chartLine: 'c3-chart-line',
          chartLines: 'c3-chart-lines',
          chartBar: 'c3-chart-bar',
          chartBars: 'c3-chart-bars',
          chartText: 'c3-chart-text',
          chartTexts: 'c3-chart-texts',
          chartArc: 'c3-chart-arc',
          chartArcs: 'c3-chart-arcs',
          chartArcsTitle: 'c3-chart-arcs-title',
          chartArcsBackground: 'c3-chart-arcs-background',
          chartArcsGaugeUnit: 'c3-chart-arcs-gauge-unit',
          chartArcsGaugeMax: 'c3-chart-arcs-gauge-max',
          chartArcsGaugeMin: 'c3-chart-arcs-gauge-min',
          selectedCircle: 'c3-selected-circle',
          selectedCircles: 'c3-selected-circles',
          eventRect: 'c3-event-rect',
          eventRects: 'c3-event-rects',
          eventRectsSingle: 'c3-event-rects-single',
          eventRectsMultiple: 'c3-event-rects-multiple',
          zoomRect: 'c3-zoom-rect',
          brush: 'c3-brush',
          focused: 'c3-focused',
          defocused: 'c3-defocused',
          region: 'c3-region',
          regions: 'c3-regions',
          title: 'c3-title',
          tooltipContainer: 'c3-tooltip-container',
          tooltip: 'c3-tooltip',
          tooltipName: 'c3-tooltip-name',
          shape: 'c3-shape',
          shapes: 'c3-shapes',
          line: 'c3-line',
          lines: 'c3-lines',
          bar: 'c3-bar',
          bars: 'c3-bars',
          circle: 'c3-circle',
          circles: 'c3-circles',
          arc: 'c3-arc',
          arcs: 'c3-arcs',
          area: 'c3-area',
          areas: 'c3-areas',
          empty: 'c3-empty',
          text: 'c3-text',
          texts: 'c3-texts',
          gaugeValue: 'c3-gauge-value',
          grid: 'c3-grid',
          gridLines: 'c3-grid-lines',
          xgrid: 'c3-xgrid',
          xgrids: 'c3-xgrids',
          xgridLine: 'c3-xgrid-line',
          xgridLines: 'c3-xgrid-lines',
          xgridFocus: 'c3-xgrid-focus',
          ygrid: 'c3-ygrid',
          ygrids: 'c3-ygrids',
          ygridLine: 'c3-ygrid-line',
          ygridLines: 'c3-ygrid-lines',
          axis: 'c3-axis',
          axisX: 'c3-axis-x',
          axisXLabel: 'c3-axis-x-label',
          axisY: 'c3-axis-y',
          axisYLabel: 'c3-axis-y-label',
          axisY2: 'c3-axis-y2',
          axisY2Label: 'c3-axis-y2-label',
          legendBackground: 'c3-legend-background',
          legendItem: 'c3-legend-item',
          legendItemEvent: 'c3-legend-item-event',
          legendItemTile: 'c3-legend-item-tile',
          legendItemHidden: 'c3-legend-item-hidden',
          legendItemFocused: 'c3-legend-item-focused',
          dragarea: 'c3-dragarea',
          EXPANDED: '_expanded_',
          SELECTED: '_selected_',
          INCLUDED: '_included_'
      };
      c3_chart_internal_fn.generateClass = function (prefix, targetId) {
          return " " + prefix + " " + prefix + this.getTargetSelectorSuffix(targetId);
      };
      c3_chart_internal_fn.classText = function (d) {
          return this.generateClass(CLASS.text, d.index);
      };
      c3_chart_internal_fn.classTexts = function (d) {
          return this.generateClass(CLASS.texts, d.id);
      };
      c3_chart_internal_fn.classShape = function (d) {
          return this.generateClass(CLASS.shape, d.index);
      };
      c3_chart_internal_fn.classShapes = function (d) {
          return this.generateClass(CLASS.shapes, d.id);
      };
      c3_chart_internal_fn.classLine = function (d) {
          return this.classShape(d) + this.generateClass(CLASS.line, d.id);
      };
      c3_chart_internal_fn.classLines = function (d) {
          return this.classShapes(d) + this.generateClass(CLASS.lines, d.id);
      };
      c3_chart_internal_fn.classCircle = function (d) {
          return this.classShape(d) + this.generateClass(CLASS.circle, d.index);
      };
      c3_chart_internal_fn.classCircles = function (d) {
          return this.classShapes(d) + this.generateClass(CLASS.circles, d.id);
      };
      c3_chart_internal_fn.classBar = function (d) {
          return this.classShape(d) + this.generateClass(CLASS.bar, d.index);
      };
      c3_chart_internal_fn.classBars = function (d) {
          return this.classShapes(d) + this.generateClass(CLASS.bars, d.id);
      };
      c3_chart_internal_fn.classArc = function (d) {
          return this.classShape(d.data) + this.generateClass(CLASS.arc, d.data.id);
      };
      c3_chart_internal_fn.classArcs = function (d) {
          return this.classShapes(d.data) + this.generateClass(CLASS.arcs, d.data.id);
      };
      c3_chart_internal_fn.classArea = function (d) {
          return this.classShape(d) + this.generateClass(CLASS.area, d.id);
      };
      c3_chart_internal_fn.classAreas = function (d) {
          return this.classShapes(d) + this.generateClass(CLASS.areas, d.id);
      };
      c3_chart_internal_fn.classRegion = function (d, i) {
          return this.generateClass(CLASS.region, i) + ' ' + ('class' in d ? d['class'] : '');
      };
      c3_chart_internal_fn.classEvent = function (d) {
          return this.generateClass(CLASS.eventRect, d.index);
      };
      c3_chart_internal_fn.classTarget = function (id) {
          var $$ = this;
          var additionalClassSuffix = $$.config.data_classes[id], additionalClass = '';
          if (additionalClassSuffix) {
              additionalClass = ' ' + CLASS.target + '-' + additionalClassSuffix;
          }
          return $$.generateClass(CLASS.target, id) + additionalClass;
      };
      c3_chart_internal_fn.classFocus = function (d) {
          return this.classFocused(d) + this.classDefocused(d);
      };
      c3_chart_internal_fn.classFocused = function (d) {
          return ' ' + (this.focusedTargetIds.indexOf(d.id) >= 0 ? CLASS.focused : '');
      };
      c3_chart_internal_fn.classDefocused = function (d) {
          return ' ' + (this.defocusedTargetIds.indexOf(d.id) >= 0 ? CLASS.defocused : '');
      };
      c3_chart_internal_fn.classChartText = function (d) {
          return CLASS.chartText + this.classTarget(d.id);
      };
      c3_chart_internal_fn.classChartLine = function (d) {
          return CLASS.chartLine + this.classTarget(d.id);
      };
      c3_chart_internal_fn.classChartBar = function (d) {
          return CLASS.chartBar + this.classTarget(d.id);
      };
      c3_chart_internal_fn.classChartArc = function (d) {
          return CLASS.chartArc + this.classTarget(d.data.id);
      };
      c3_chart_internal_fn.getTargetSelectorSuffix = function (targetId) {
          return targetId || targetId === 0 ? ('-' + targetId).replace(/[\s?!@#$%^&*()_=+,.<>'":;\[\]\/|~`{}\\]/g, '-') : '';
      };
      c3_chart_internal_fn.selectorTarget = function (id, prefix) {
          return (prefix || '') + '.' + CLASS.target + this.getTargetSelectorSuffix(id);
      };
      c3_chart_internal_fn.selectorTargets = function (ids, prefix) {
          var $$ = this;
          ids = ids || [];
          return ids.length ? ids.map(function (id) { return $$.selectorTarget(id, prefix); }) : null;
      };
      c3_chart_internal_fn.selectorLegend = function (id) {
          return '.' + CLASS.legendItem + this.getTargetSelectorSuffix(id);
      };
      c3_chart_internal_fn.selectorLegends = function (ids) {
          var $$ = this;
          return ids && ids.length ? ids.map(function (id) { return $$.selectorLegend(id); }) : null;
      };
  
      var isValue = c3_chart_internal_fn.isValue = function (v) {
          return v || v === 0;
      },
          isFunction = c3_chart_internal_fn.isFunction = function (o) {
              return typeof o === 'function';
          },
          isString = c3_chart_internal_fn.isString = function (o) {
              return typeof o === 'string';
          },
          isUndefined = c3_chart_internal_fn.isUndefined = function (v) {
              return typeof v === 'undefined';
          },
          isDefined = c3_chart_internal_fn.isDefined = function (v) {
              return typeof v !== 'undefined';
          },
          ceil10 = c3_chart_internal_fn.ceil10 = function (v) {
              return Math.ceil(v / 10) * 10;
          },
          asHalfPixel = c3_chart_internal_fn.asHalfPixel = function (n) {
              return Math.ceil(n) + 0.5;
          },
          diffDomain = c3_chart_internal_fn.diffDomain = function (d) {
              return d[1] - d[0];
          },
          isEmpty = c3_chart_internal_fn.isEmpty = function (o) {
              return typeof o === 'undefined' || o === null || (isString(o) && o.length === 0) || (typeof o === 'object' && Object.keys(o).length === 0);
          },
          notEmpty = c3_chart_internal_fn.notEmpty = function (o) {
              return !c3_chart_internal_fn.isEmpty(o);
          },
          getOption = c3_chart_internal_fn.getOption = function (options, key, defaultValue) {
              return isDefined(options[key]) ? options[key] : defaultValue;
          },
          hasValue = c3_chart_internal_fn.hasValue = function (dict, value) {
              var found = false;
              Object.keys(dict).forEach(function (key) {
                  if (dict[key] === value) { found = true; }
              });
              return found;
          },
          getPathBox = c3_chart_internal_fn.getPathBox = function (path) {
              var box = path.getBoundingClientRect(),
                  items = [path.pathSegList.getItem(0), path.pathSegList.getItem(1)],
                  minX = items[0].x, minY = Math.min(items[0].y, items[1].y);
              return {x: minX, y: minY, width: box.width, height: box.height};
          };
  
      c3_chart_fn.focus = function (targetIds) {
          var $$ = this.internal, candidates;
  
          targetIds = $$.mapToTargetIds(targetIds);
          candidates = $$.svg.selectAll($$.selectorTargets(targetIds.filter($$.isTargetToShow, $$))),
  
          this.revert();
          this.defocus();
          candidates.classed(CLASS.focused, true).classed(CLASS.defocused, false);
          if ($$.hasArcType()) {
              $$.expandArc(targetIds);
          }
          $$.toggleFocusLegend(targetIds, true);
  
          $$.focusedTargetIds = targetIds;
          $$.defocusedTargetIds = $$.defocusedTargetIds.filter(function (id) {
              return targetIds.indexOf(id) < 0;
          });
      };
  
      c3_chart_fn.defocus = function (targetIds) {
          var $$ = this.internal, candidates;
  
          targetIds = $$.mapToTargetIds(targetIds);
          candidates = $$.svg.selectAll($$.selectorTargets(targetIds.filter($$.isTargetToShow, $$))),
  
          candidates.classed(CLASS.focused, false).classed(CLASS.defocused, true);
          if ($$.hasArcType()) {
              $$.unexpandArc(targetIds);
          }
          $$.toggleFocusLegend(targetIds, false);
  
          $$.focusedTargetIds = $$.focusedTargetIds.filter(function (id) {
              return targetIds.indexOf(id) < 0;
          });
          $$.defocusedTargetIds = targetIds;
      };
  
      c3_chart_fn.revert = function (targetIds) {
          var $$ = this.internal, candidates;
  
          targetIds = $$.mapToTargetIds(targetIds);
          candidates = $$.svg.selectAll($$.selectorTargets(targetIds)); // should be for all targets
  
          candidates.classed(CLASS.focused, false).classed(CLASS.defocused, false);
          if ($$.hasArcType()) {
              $$.unexpandArc(targetIds);
          }
          if ($$.config.legend_show) {
              $$.showLegend(targetIds.filter($$.isLegendToShow.bind($$)));
              $$.legend.selectAll($$.selectorLegends(targetIds))
                  .filter(function () {
                      return $$.d3.select(this).classed(CLASS.legendItemFocused);
                  })
                  .classed(CLASS.legendItemFocused, false);
          }
  
          $$.focusedTargetIds = [];
          $$.defocusedTargetIds = [];
      };
  
      c3_chart_fn.show = function (targetIds, options) {
          var $$ = this.internal, targets;
  
          targetIds = $$.mapToTargetIds(targetIds);
          options = options || {};
  
          $$.removeHiddenTargetIds(targetIds);
          targets = $$.svg.selectAll($$.selectorTargets(targetIds));
  
          targets.transition()
              .style('opacity', 1, 'important')
              .call($$.endall, function () {
                  targets.style('opacity', null).style('opacity', 1);
              });
  
          if (options.withLegend) {
              $$.showLegend(targetIds);
          }
  
          $$.redraw({withUpdateOrgXDomain: true, withUpdateXDomain: true, withLegend: true});
      };
  
      c3_chart_fn.hide = function (targetIds, options) {
          var $$ = this.internal, targets;
  
          targetIds = $$.mapToTargetIds(targetIds);
          options = options || {};
  
          $$.addHiddenTargetIds(targetIds);
          targets = $$.svg.selectAll($$.selectorTargets(targetIds));
  
          targets.transition()
              .style('opacity', 0, 'important')
              .call($$.endall, function () {
                  targets.style('opacity', null).style('opacity', 0);
              });
  
          if (options.withLegend) {
              $$.hideLegend(targetIds);
          }
  
          $$.redraw({withUpdateOrgXDomain: true, withUpdateXDomain: true, withLegend: true});
      };
  
      c3_chart_fn.toggle = function (targetIds, options) {
          var that = this, $$ = this.internal;
          $$.mapToTargetIds(targetIds).forEach(function (targetId) {
              $$.isTargetToShow(targetId) ? that.hide(targetId, options) : that.show(targetId, options);
          });
      };
  
      c3_chart_fn.zoom = function (domain) {
          var $$ = this.internal;
          if (domain) {
              if ($$.isTimeSeries()) {
                  domain = domain.map(function (x) { return $$.parseDate(x); });
              }
              $$.brush.extent(domain);
              $$.redraw({withUpdateXDomain: true, withY: $$.config.zoom_rescale});
              $$.config.zoom_onzoom.call(this, $$.x.orgDomain());
          }
          return $$.brush.extent();
      };
      c3_chart_fn.zoom.enable = function (enabled) {
          var $$ = this.internal;
          $$.config.zoom_enabled = enabled;
          $$.updateAndRedraw();
      };
      c3_chart_fn.unzoom = function () {
          var $$ = this.internal;
          $$.brush.clear().update();
          $$.redraw({withUpdateXDomain: true});
      };
  
      c3_chart_fn.zoom.max = function (max) {
          var $$ = this.internal, config = $$.config, d3 = $$.d3;
          if (max === 0 || max) {
              config.zoom_x_max = d3.max([$$.orgXDomain[1], max]);
          }
          else {
              return config.zoom_x_max;
          }
      };
  
      c3_chart_fn.zoom.min = function (min) {
          var $$ = this.internal, config = $$.config, d3 = $$.d3;
          if (min === 0 || min) {
              config.zoom_x_min = d3.min([$$.orgXDomain[0], min]);
          }
          else {
              return config.zoom_x_min;
          }
      };
  
      c3_chart_fn.zoom.range = function (range) {
          if (arguments.length) {
              if (isDefined(range.max)) { this.domain.max(range.max); }
              if (isDefined(range.min)) { this.domain.min(range.min); }
          } else {
              return {
                  max: this.domain.max(),
                  min: this.domain.min()
              };
          }
      };
  
      c3_chart_fn.load = function (args) {
          var $$ = this.internal, config = $$.config;
          // update xs if specified
          if (args.xs) {
              $$.addXs(args.xs);
          }
          // update classes if exists
          if ('classes' in args) {
              Object.keys(args.classes).forEach(function (id) {
                  config.data_classes[id] = args.classes[id];
              });
          }
          // update categories if exists
          if ('categories' in args && $$.isCategorized()) {
              config.axis_x_categories = args.categories;
          }
          // update axes if exists
          if ('axes' in args) {
              Object.keys(args.axes).forEach(function (id) {
                  config.data_axes[id] = args.axes[id];
              });
          }
          // update colors if exists
          if ('colors' in args) {
              Object.keys(args.colors).forEach(function (id) {
                  config.data_colors[id] = args.colors[id];
              });
          }
          // use cache if exists
          if ('cacheIds' in args && $$.hasCaches(args.cacheIds)) {
              $$.load($$.getCaches(args.cacheIds), args.done);
              return;
          }
          // unload if needed
          if ('unload' in args) {
              // TODO: do not unload if target will load (included in url/rows/columns)
              $$.unload($$.mapToTargetIds((typeof args.unload === 'boolean' && args.unload) ? null : args.unload), function () {
                  $$.loadFromArgs(args);
              });
          } else {
              $$.loadFromArgs(args);
          }
      };
  
      c3_chart_fn.unload = function (args) {
          var $$ = this.internal;
          args = args || {};
          if (args instanceof Array) {
              args = {ids: args};
          } else if (typeof args === 'string') {
              args = {ids: [args]};
          }
          $$.unload($$.mapToTargetIds(args.ids), function () {
              $$.redraw({withUpdateOrgXDomain: true, withUpdateXDomain: true, withLegend: true});
              if (args.done) { args.done(); }
          });
      };
  
      c3_chart_fn.flow = function (args) {
          var $$ = this.internal,
              targets, data, notfoundIds = [], orgDataCount = $$.getMaxDataCount(),
              dataCount, domain, baseTarget, baseValue, length = 0, tail = 0, diff, to;
  
          if (args.json) {
              data = $$.convertJsonToData(args.json, args.keys);
          }
          else if (args.rows) {
              data = $$.convertRowsToData(args.rows);
          }
          else if (args.columns) {
              data = $$.convertColumnsToData(args.columns);
          }
          else {
              return;
          }
          targets = $$.convertDataToTargets(data, true);
  
          // Update/Add data
          $$.data.targets.forEach(function (t) {
              var found = false, i, j;
              for (i = 0; i < targets.length; i++) {
                  if (t.id === targets[i].id) {
                      found = true;
  
                      if (t.values[t.values.length - 1]) {
                          tail = t.values[t.values.length - 1].index + 1;
                      }
                      length = targets[i].values.length;
  
                      for (j = 0; j < length; j++) {
                          targets[i].values[j].index = tail + j;
                          if (!$$.isTimeSeries()) {
                              targets[i].values[j].x = tail + j;
                          }
                      }
                      t.values = t.values.concat(targets[i].values);
  
                      targets.splice(i, 1);
                      break;
                  }
              }
              if (!found) { notfoundIds.push(t.id); }
          });
  
          // Append null for not found targets
          $$.data.targets.forEach(function (t) {
              var i, j;
              for (i = 0; i < notfoundIds.length; i++) {
                  if (t.id === notfoundIds[i]) {
                      tail = t.values[t.values.length - 1].index + 1;
                      for (j = 0; j < length; j++) {
                          t.values.push({
                              id: t.id,
                              index: tail + j,
                              x: $$.isTimeSeries() ? $$.getOtherTargetX(tail + j) : tail + j,
                              value: null
                          });
                      }
                  }
              }
          });
  
          // Generate null values for new target
          if ($$.data.targets.length) {
              targets.forEach(function (t) {
                  var i, missing = [];
                  for (i = $$.data.targets[0].values[0].index; i < tail; i++) {
                      missing.push({
                          id: t.id,
                          index: i,
                          x: $$.isTimeSeries() ? $$.getOtherTargetX(i) : i,
                          value: null
                      });
                  }
                  t.values.forEach(function (v) {
                      v.index += tail;
                      if (!$$.isTimeSeries()) {
                          v.x += tail;
                      }
                  });
                  t.values = missing.concat(t.values);
              });
          }
          $$.data.targets = $$.data.targets.concat(targets); // add remained
  
          // check data count because behavior needs to change when it's only one
          dataCount = $$.getMaxDataCount();
          baseTarget = $$.data.targets[0];
          baseValue = baseTarget.values[0];
  
          // Update length to flow if needed
          if (isDefined(args.to)) {
              length = 0;
              to = $$.isTimeSeries() ? $$.parseDate(args.to) : args.to;
              baseTarget.values.forEach(function (v) {
                  if (v.x < to) { length++; }
              });
          } else if (isDefined(args.length)) {
              length = args.length;
          }
  
          // If only one data, update the domain to flow from left edge of the chart
          if (!orgDataCount) {
              if ($$.isTimeSeries()) {
                  if (baseTarget.values.length > 1) {
                      diff = baseTarget.values[baseTarget.values.length - 1].x - baseValue.x;
                  } else {
                      diff = baseValue.x - $$.getXDomain($$.data.targets)[0];
                  }
              } else {
                  diff = 1;
              }
              domain = [baseValue.x - diff, baseValue.x];
              $$.updateXDomain(null, true, true, false, domain);
          } else if (orgDataCount === 1) {
              if ($$.isTimeSeries()) {
                  diff = (baseTarget.values[baseTarget.values.length - 1].x - baseValue.x) / 2;
                  domain = [new Date(+baseValue.x - diff), new Date(+baseValue.x + diff)];
                  $$.updateXDomain(null, true, true, false, domain);
              }
          }
  
          // Set targets
          $$.updateTargets($$.data.targets);
  
          // Redraw with new targets
          $$.redraw({
              flow: {
                  index: baseValue.index,
                  length: length,
                  duration: isValue(args.duration) ? args.duration : $$.config.transition_duration,
                  done: args.done,
                  orgDataCount: orgDataCount,
              },
              withLegend: true,
              withTransition: orgDataCount > 1,
              withTrimXDomain: false,
              withUpdateXAxis: true,
          });
      };
  
      c3_chart_internal_fn.generateFlow = function (args) {
          var $$ = this, config = $$.config, d3 = $$.d3;
  
          return function () {
              var targets = args.targets,
                  flow = args.flow,
                  drawBar = args.drawBar,
                  drawLine = args.drawLine,
                  drawArea = args.drawArea,
                  cx = args.cx,
                  cy = args.cy,
                  xv = args.xv,
                  xForText = args.xForText,
                  yForText = args.yForText,
                  duration = args.duration;
  
              var translateX, scaleX = 1, transform,
                  flowIndex = flow.index,
                  flowLength = flow.length,
                  flowStart = $$.getValueOnIndex($$.data.targets[0].values, flowIndex),
                  flowEnd = $$.getValueOnIndex($$.data.targets[0].values, flowIndex + flowLength),
                  orgDomain = $$.x.domain(), domain,
                  durationForFlow = flow.duration || duration,
                  done = flow.done || function () {},
                  wait = $$.generateWait();
  
              var xgrid = $$.xgrid || d3.selectAll([]),
                  xgridLines = $$.xgridLines || d3.selectAll([]),
                  mainRegion = $$.mainRegion || d3.selectAll([]),
                  mainText = $$.mainText || d3.selectAll([]),
                  mainBar = $$.mainBar || d3.selectAll([]),
                  mainLine = $$.mainLine || d3.selectAll([]),
                  mainArea = $$.mainArea || d3.selectAll([]),
                  mainCircle = $$.mainCircle || d3.selectAll([]);
  
              // set flag
              $$.flowing = true;
  
              // remove head data after rendered
              $$.data.targets.forEach(function (d) {
                  d.values.splice(0, flowLength);
              });
  
              // update x domain to generate axis elements for flow
              domain = $$.updateXDomain(targets, true, true);
              // update elements related to x scale
              if ($$.updateXGrid) { $$.updateXGrid(true); }
  
              // generate transform to flow
              if (!flow.orgDataCount) { // if empty
                  if ($$.data.targets[0].values.length !== 1) {
                      translateX = $$.x(orgDomain[0]) - $$.x(domain[0]);
                  } else {
                      if ($$.isTimeSeries()) {
                          flowStart = $$.getValueOnIndex($$.data.targets[0].values, 0);
                          flowEnd = $$.getValueOnIndex($$.data.targets[0].values, $$.data.targets[0].values.length - 1);
                          translateX = $$.x(flowStart.x) - $$.x(flowEnd.x);
                      } else {
                          translateX = diffDomain(domain) / 2;
                      }
                  }
              } else if (flow.orgDataCount === 1 || flowStart.x === flowEnd.x) {
                  translateX = $$.x(orgDomain[0]) - $$.x(domain[0]);
              } else {
                  if ($$.isTimeSeries()) {
                      translateX = ($$.x(orgDomain[0]) - $$.x(domain[0]));
                  } else {
                      translateX = ($$.x(flowStart.x) - $$.x(flowEnd.x));
                  }
              }
              scaleX = (diffDomain(orgDomain) / diffDomain(domain));
              transform = 'translate(' + translateX + ',0) scale(' + scaleX + ',1)';
  
              $$.hideXGridFocus();
  
              d3.transition().ease('linear').duration(durationForFlow).each(function () {
                  wait.add($$.axes.x.transition().call($$.xAxis));
                  wait.add(mainBar.transition().attr('transform', transform));
                  wait.add(mainLine.transition().attr('transform', transform));
                  wait.add(mainArea.transition().attr('transform', transform));
                  wait.add(mainCircle.transition().attr('transform', transform));
                  wait.add(mainText.transition().attr('transform', transform));
                  wait.add(mainRegion.filter($$.isRegionOnX).transition().attr('transform', transform));
                  wait.add(xgrid.transition().attr('transform', transform));
                  wait.add(xgridLines.transition().attr('transform', transform));
              })
              .call(wait, function () {
                  var i, shapes = [], texts = [], eventRects = [];
  
                  // remove flowed elements
                  if (flowLength) {
                      for (i = 0; i < flowLength; i++) {
                          shapes.push('.' + CLASS.shape + '-' + (flowIndex + i));
                          texts.push('.' + CLASS.text + '-' + (flowIndex + i));
                          eventRects.push('.' + CLASS.eventRect + '-' + (flowIndex + i));
                      }
                      $$.svg.selectAll('.' + CLASS.shapes).selectAll(shapes).remove();
                      $$.svg.selectAll('.' + CLASS.texts).selectAll(texts).remove();
                      $$.svg.selectAll('.' + CLASS.eventRects).selectAll(eventRects).remove();
                      $$.svg.select('.' + CLASS.xgrid).remove();
                  }
  
                  // draw again for removing flowed elements and reverting attr
                  xgrid
                      .attr('transform', null)
                      .attr($$.xgridAttr);
                  xgridLines
                      .attr('transform', null);
                  xgridLines.select('line')
                      .attr("x1", config.axis_rotated ? 0 : xv)
                      .attr("x2", config.axis_rotated ? $$.width : xv);
                  xgridLines.select('text')
                      .attr("x", config.axis_rotated ? $$.width : 0)
                      .attr("y", xv);
                  mainBar
                      .attr('transform', null)
                      .attr("d", drawBar);
                  mainLine
                      .attr('transform', null)
                      .attr("d", drawLine);
                  mainArea
                      .attr('transform', null)
                      .attr("d", drawArea);
                  mainCircle
                      .attr('transform', null)
                      .attr("cx", cx)
                      .attr("cy", cy);
                  mainText
                      .attr('transform', null)
                      .attr('x', xForText)
                      .attr('y', yForText)
                      .style('fill-opacity', $$.opacityForText.bind($$));
                  mainRegion
                      .attr('transform', null);
                  mainRegion.select('rect').filter($$.isRegionOnX)
                      .attr("x", $$.regionX.bind($$))
                      .attr("width", $$.regionWidth.bind($$));
  
                  if (config.interaction_enabled) {
                      $$.redrawEventRect();
                  }
  
                  // callback for end of flow
                  done();
  
                  $$.flowing = false;
              });
          };
      };
  
      c3_chart_fn.selected = function (targetId) {
          var $$ = this.internal, d3 = $$.d3;
          return d3.merge(
              $$.main.selectAll('.' + CLASS.shapes + $$.getTargetSelectorSuffix(targetId)).selectAll('.' + CLASS.shape)
                  .filter(function () { return d3.select(this).classed(CLASS.SELECTED); })
                  .map(function (d) { return d.map(function (d) { var data = d.__data__; return data.data ? data.data : data; }); })
          );
      };
      c3_chart_fn.select = function (ids, indices, resetOther) {
          var $$ = this.internal, d3 = $$.d3, config = $$.config;
          if (! config.data_selection_enabled) { return; }
          $$.main.selectAll('.' + CLASS.shapes).selectAll('.' + CLASS.shape).each(function (d, i) {
              var shape = d3.select(this), id = d.data ? d.data.id : d.id,
                  toggle = $$.getToggle(this, d).bind($$),
                  isTargetId = config.data_selection_grouped || !ids || ids.indexOf(id) >= 0,
                  isTargetIndex = !indices || indices.indexOf(i) >= 0,
                  isSelected = shape.classed(CLASS.SELECTED);
              // line/area selection not supported yet
              if (shape.classed(CLASS.line) || shape.classed(CLASS.area)) {
                  return;
              }
              if (isTargetId && isTargetIndex) {
                  if (config.data_selection_isselectable(d) && !isSelected) {
                      toggle(true, shape.classed(CLASS.SELECTED, true), d, i);
                  }
              } else if (isDefined(resetOther) && resetOther) {
                  if (isSelected) {
                      toggle(false, shape.classed(CLASS.SELECTED, false), d, i);
                  }
              }
          });
      };
      c3_chart_fn.unselect = function (ids, indices) {
          var $$ = this.internal, d3 = $$.d3, config = $$.config;
          if (! config.data_selection_enabled) { return; }
          $$.main.selectAll('.' + CLASS.shapes).selectAll('.' + CLASS.shape).each(function (d, i) {
              var shape = d3.select(this), id = d.data ? d.data.id : d.id,
                  toggle = $$.getToggle(this, d).bind($$),
                  isTargetId = config.data_selection_grouped || !ids || ids.indexOf(id) >= 0,
                  isTargetIndex = !indices || indices.indexOf(i) >= 0,
                  isSelected = shape.classed(CLASS.SELECTED);
              // line/area selection not supported yet
              if (shape.classed(CLASS.line) || shape.classed(CLASS.area)) {
                  return;
              }
              if (isTargetId && isTargetIndex) {
                  if (config.data_selection_isselectable(d)) {
                      if (isSelected) {
                          toggle(false, shape.classed(CLASS.SELECTED, false), d, i);
                      }
                  }
              }
          });
      };
  
      c3_chart_fn.transform = function (type, targetIds) {
          var $$ = this.internal,
              options = ['pie', 'donut'].indexOf(type) >= 0 ? {withTransform: true} : null;
          $$.transformTo(targetIds, type, options);
      };
  
      c3_chart_internal_fn.transformTo = function (targetIds, type, optionsForRedraw) {
          var $$ = this,
              withTransitionForAxis = !$$.hasArcType(),
              options = optionsForRedraw || {withTransitionForAxis: withTransitionForAxis};
          options.withTransitionForTransform = false;
          $$.transiting = false;
          $$.setTargetType(targetIds, type);
          $$.updateTargets($$.data.targets); // this is needed when transforming to arc
          $$.updateAndRedraw(options);
      };
  
      c3_chart_fn.groups = function (groups) {
          var $$ = this.internal, config = $$.config;
          if (isUndefined(groups)) { return config.data_groups; }
          config.data_groups = groups;
          $$.redraw();
          return config.data_groups;
      };
  
      c3_chart_fn.xgrids = function (grids) {
          var $$ = this.internal, config = $$.config;
          if (! grids) { return config.grid_x_lines; }
          config.grid_x_lines = grids;
          $$.redrawWithoutRescale();
          return config.grid_x_lines;
      };
      c3_chart_fn.xgrids.add = function (grids) {
          var $$ = this.internal;
          return this.xgrids($$.config.grid_x_lines.concat(grids ? grids : []));
      };
      c3_chart_fn.xgrids.remove = function (params) { // TODO: multiple
          var $$ = this.internal;
          $$.removeGridLines(params, true);
      };
  
      c3_chart_fn.ygrids = function (grids) {
          var $$ = this.internal, config = $$.config;
          if (! grids) { return config.grid_y_lines; }
          config.grid_y_lines = grids;
          $$.redrawWithoutRescale();
          return config.grid_y_lines;
      };
      c3_chart_fn.ygrids.add = function (grids) {
          var $$ = this.internal;
          return this.ygrids($$.config.grid_y_lines.concat(grids ? grids : []));
      };
      c3_chart_fn.ygrids.remove = function (params) { // TODO: multiple
          var $$ = this.internal;
          $$.removeGridLines(params, false);
      };
  
      c3_chart_fn.regions = function (regions) {
          var $$ = this.internal, config = $$.config;
          if (!regions) { return config.regions; }
          config.regions = regions;
          $$.redrawWithoutRescale();
          return config.regions;
      };
      c3_chart_fn.regions.add = function (regions) {
          var $$ = this.internal, config = $$.config;
          if (!regions) { return config.regions; }
          config.regions = config.regions.concat(regions);
          $$.redrawWithoutRescale();
          return config.regions;
      };
      c3_chart_fn.regions.remove = function (options) {
          var $$ = this.internal, config = $$.config,
              duration, classes, regions;
  
          options = options || {};
          duration = $$.getOption(options, "duration", config.transition_duration);
          classes = $$.getOption(options, "classes", [CLASS.region]);
  
          regions = $$.main.select('.' + CLASS.regions).selectAll(classes.map(function (c) { return '.' + c; }));
          (duration ? regions.transition().duration(duration) : regions)
              .style('opacity', 0)
              .remove();
  
          config.regions = config.regions.filter(function (region) {
              var found = false;
              if (!region['class']) {
                  return true;
              }
              region['class'].split(' ').forEach(function (c) {
                  if (classes.indexOf(c) >= 0) { found = true; }
              });
              return !found;
          });
  
          return config.regions;
      };
  
      c3_chart_fn.data = function (targetIds) {
          var targets = this.internal.data.targets;
          return typeof targetIds === 'undefined' ? targets : targets.filter(function (t) {
              return [].concat(targetIds).indexOf(t.id) >= 0;
          });
      };
      c3_chart_fn.data.shown = function (targetIds) {
          return this.internal.filterTargetsToShow(this.data(targetIds));
      };
      c3_chart_fn.data.values = function (targetId) {
          var targets, values = null;
          if (targetId) {
              targets = this.data(targetId);
              values = targets[0] ? targets[0].values.map(function (d) { return d.value; }) : null;
          }
          return values;
      };
      c3_chart_fn.data.names = function (names) {
          this.internal.clearLegendItemTextBoxCache();
          return this.internal.updateDataAttributes('names', names);
      };
      c3_chart_fn.data.colors = function (colors) {
          return this.internal.updateDataAttributes('colors', colors);
      };
      c3_chart_fn.data.axes = function (axes) {
          return this.internal.updateDataAttributes('axes', axes);
      };
  
      c3_chart_fn.category = function (i, category) {
          var $$ = this.internal, config = $$.config;
          if (arguments.length > 1) {
              config.axis_x_categories[i] = category;
              $$.redraw();
          }
          return config.axis_x_categories[i];
      };
      c3_chart_fn.categories = function (categories) {
          var $$ = this.internal, config = $$.config;
          if (!arguments.length) { return config.axis_x_categories; }
          config.axis_x_categories = categories;
          $$.redraw();
          return config.axis_x_categories;
      };
  
      // TODO: fix
      c3_chart_fn.color = function (id) {
          var $$ = this.internal;
          return $$.color(id); // more patterns
      };
  
      c3_chart_fn.x = function (x) {
          var $$ = this.internal;
          if (arguments.length) {
              $$.updateTargetX($$.data.targets, x);
              $$.redraw({withUpdateOrgXDomain: true, withUpdateXDomain: true});
          }
          return $$.data.xs;
      };
      c3_chart_fn.xs = function (xs) {
          var $$ = this.internal;
          if (arguments.length) {
              $$.updateTargetXs($$.data.targets, xs);
              $$.redraw({withUpdateOrgXDomain: true, withUpdateXDomain: true});
          }
          return $$.data.xs;
      };
  
      c3_chart_fn.axis = function () {};
      c3_chart_fn.axis.labels = function (labels) {
          var $$ = this.internal;
          if (arguments.length) {
              Object.keys(labels).forEach(function (axisId) {
                  $$.axis.setLabelText(axisId, labels[axisId]);
              });
              $$.axis.updateLabels();
          }
          // TODO: return some values?
      };
      c3_chart_fn.axis.max = function (max) {
          var $$ = this.internal, config = $$.config;
          if (arguments.length) {
              if (typeof max === 'object') {
                  if (isValue(max.x)) { config.axis_x_max = max.x; }
                  if (isValue(max.y)) { config.axis_y_max = max.y; }
                  if (isValue(max.y2)) { config.axis_y2_max = max.y2; }
              } else {
                  config.axis_y_max = config.axis_y2_max = max;
              }
              $$.redraw({withUpdateOrgXDomain: true, withUpdateXDomain: true});
          } else {
              return {
                  x: config.axis_x_max,
                  y: config.axis_y_max,
                  y2: config.axis_y2_max
              };
          }
      };
      c3_chart_fn.axis.min = function (min) {
          var $$ = this.internal, config = $$.config;
          if (arguments.length) {
              if (typeof min === 'object') {
                  if (isValue(min.x)) { config.axis_x_min = min.x; }
                  if (isValue(min.y)) { config.axis_y_min = min.y; }
                  if (isValue(min.y2)) { config.axis_y2_min = min.y2; }
              } else {
                  config.axis_y_min = config.axis_y2_min = min;
              }
              $$.redraw({withUpdateOrgXDomain: true, withUpdateXDomain: true});
          } else {
              return {
                  x: config.axis_x_min,
                  y: config.axis_y_min,
                  y2: config.axis_y2_min
              };
          }
      };
      c3_chart_fn.axis.range = function (range) {
          if (arguments.length) {
              if (isDefined(range.max)) { this.axis.max(range.max); }
              if (isDefined(range.min)) { this.axis.min(range.min); }
          } else {
              return {
                  max: this.axis.max(),
                  min: this.axis.min()
              };
          }
      };
  
      c3_chart_fn.legend = function () {};
      c3_chart_fn.legend.show = function (targetIds) {
          var $$ = this.internal;
          $$.showLegend($$.mapToTargetIds(targetIds));
          $$.updateAndRedraw({withLegend: true});
      };
      c3_chart_fn.legend.hide = function (targetIds) {
          var $$ = this.internal;
          $$.hideLegend($$.mapToTargetIds(targetIds));
          $$.updateAndRedraw({withLegend: true});
      };
  
      c3_chart_fn.resize = function (size) {
          var $$ = this.internal, config = $$.config;
          config.size_width = size ? size.width : null;
          config.size_height = size ? size.height : null;
          this.flush();
      };
  
      c3_chart_fn.flush = function () {
          var $$ = this.internal;
          $$.updateAndRedraw({withLegend: true, withTransition: false, withTransitionForTransform: false});
      };
  
      c3_chart_fn.destroy = function () {
          var $$ = this.internal;
  
          window.clearInterval($$.intervalForObserveInserted);
  
          if ($$.resizeTimeout !== undefined) {
              window.clearTimeout($$.resizeTimeout);
          }
  
          if (window.detachEvent) {
              window.detachEvent('onresize', $$.resizeFunction);
          } else if (window.removeEventListener) {
              window.removeEventListener('resize', $$.resizeFunction);
          } else {
              var wrapper = window.onresize;
              // check if no one else removed our wrapper and remove our resizeFunction from it
              if (wrapper && wrapper.add && wrapper.remove) {
                  wrapper.remove($$.resizeFunction);
              }
          }
  
          $$.selectChart.classed('c3', false).html("");
  
          // MEMO: this is needed because the reference of some elements will not be released, then memory leak will happen.
          Object.keys($$).forEach(function (key) {
              $$[key] = null;
          });
  
          return null;
      };
  
      c3_chart_fn.tooltip = function () {};
      c3_chart_fn.tooltip.show = function (args) {
          var $$ = this.internal, index, mouse;
  
          // determine mouse position on the chart
          if (args.mouse) {
              mouse = args.mouse;
          }
  
          // determine focus data
          if (args.data) {
              if ($$.isMultipleX()) {
                  // if multiple xs, target point will be determined by mouse
                  mouse = [$$.x(args.data.x), $$.getYScale(args.data.id)(args.data.value)];
                  index = null;
              } else {
                  // TODO: when tooltip_grouped = false
                  index = isValue(args.data.index) ? args.data.index : $$.getIndexByX(args.data.x);
              }
          }
          else if (typeof args.x !== 'undefined') {
              index = $$.getIndexByX(args.x);
          }
          else if (typeof args.index !== 'undefined') {
              index = args.index;
          }
  
          // emulate mouse events to show
          $$.dispatchEvent('mouseover', index, mouse);
          $$.dispatchEvent('mousemove', index, mouse);
  
          $$.config.tooltip_onshow.call($$, args.data);
      };
      c3_chart_fn.tooltip.hide = function () {
          // TODO: get target data by checking the state of focus
          this.internal.dispatchEvent('mouseout', 0);
  
          this.internal.config.tooltip_onhide.call(this);
      };
  
      // Features:
      // 1. category axis
      // 2. ceil values of translate/x/y to int for half pixel antialiasing
      // 3. multiline tick text
      var tickTextCharSize;
      function c3_axis(d3, params) {
          var scale = d3.scale.linear(), orient = "bottom", innerTickSize = 6, outerTickSize, tickPadding = 3, tickValues = null, tickFormat, tickArguments;
  
          var tickOffset = 0, tickCulling = true, tickCentered;
  
          params = params || {};
          outerTickSize = params.withOuterTick ? 6 : 0;
  
          function axisX(selection, x) {
              selection.attr("transform", function (d) {
                  return "translate(" + Math.ceil(x(d) + tickOffset) + ", 0)";
              });
          }
          function axisY(selection, y) {
              selection.attr("transform", function (d) {
                  return "translate(0," + Math.ceil(y(d)) + ")";
              });
          }
          function scaleExtent(domain) {
              var start = domain[0], stop = domain[domain.length - 1];
              return start < stop ? [ start, stop ] : [ stop, start ];
          }
          function generateTicks(scale) {
              var i, domain, ticks = [];
              if (scale.ticks) {
                  return scale.ticks.apply(scale, tickArguments);
              }
              domain = scale.domain();
              for (i = Math.ceil(domain[0]); i < domain[1]; i++) {
                  ticks.push(i);
              }
              if (ticks.length > 0 && ticks[0] > 0) {
                  ticks.unshift(ticks[0] - (ticks[1] - ticks[0]));
              }
              return ticks;
          }
          function copyScale() {
              var newScale = scale.copy(), domain;
              if (params.isCategory) {
                  domain = scale.domain();
                  newScale.domain([domain[0], domain[1] - 1]);
              }
              return newScale;
          }
          function textFormatted(v) {
              var formatted = tickFormat ? tickFormat(v) : v;
              return typeof formatted !== 'undefined' ? formatted : '';
          }
          function getSizeFor1Char(tick) {
              if (tickTextCharSize) {
                  return tickTextCharSize;
              }
              var size = {
                  h: 11.5,
                  w: 5.5
              };
              tick.select('text').text(textFormatted).each(function (d) {
                  var box = this.getBoundingClientRect(),
                      text = textFormatted(d),
                      h = box.height,
                      w = text ? (box.width / text.length) : undefined;
                  if (h && w) {
                      size.h = h;
                      size.w = w;
                  }
              }).text('');
              tickTextCharSize = size;
              return size;
          }
          function transitionise(selection) {
              return params.withoutTransition ? selection : d3.transition(selection);
          }
          function axis(g) {
              g.each(function () {
                  var g = axis.g = d3.select(this);
  
                  var scale0 = this.__chart__ || scale, scale1 = this.__chart__ = copyScale();
  
                  var ticks = tickValues ? tickValues : generateTicks(scale1),
                      tick = g.selectAll(".tick").data(ticks, scale1),
                      tickEnter = tick.enter().insert("g", ".domain").attr("class", "tick").style("opacity", 1e-6),
                      // MEMO: No exit transition. The reason is this transition affects max tick width calculation because old tick will be included in the ticks.
                      tickExit = tick.exit().remove(),
                      tickUpdate = transitionise(tick).style("opacity", 1),
                      tickTransform, tickX, tickY;
  
                  var range = scale.rangeExtent ? scale.rangeExtent() : scaleExtent(scale.range()),
                      path = g.selectAll(".domain").data([ 0 ]),
                      pathUpdate = (path.enter().append("path").attr("class", "domain"), transitionise(path));
                  tickEnter.append("line");
                  tickEnter.append("text");
  
                  var lineEnter = tickEnter.select("line"),
                      lineUpdate = tickUpdate.select("line"),
                      textEnter = tickEnter.select("text"),
                      textUpdate = tickUpdate.select("text");
  
                  if (params.isCategory) {
                      tickOffset = Math.ceil((scale1(1) - scale1(0)) / 2);
                      tickX = tickCentered ? 0 : tickOffset;
                      tickY = tickCentered ? tickOffset : 0;
                  } else {
                      tickOffset = tickX = 0;
                  }
  
                  var text, tspan, sizeFor1Char = getSizeFor1Char(g.select('.tick')), counts = [];
                  var tickLength = Math.max(innerTickSize, 0) + tickPadding,
                      isVertical = orient === 'left' || orient === 'right';
  
                  // this should be called only when category axis
                  function splitTickText(d, maxWidth) {
                      var tickText = textFormatted(d),
                          subtext, spaceIndex, textWidth, splitted = [];
  
                      if (Object.prototype.toString.call(tickText) === "[object Array]") {
                          return tickText;
                      }
  
                      if (!maxWidth || maxWidth <= 0) {
                          maxWidth = isVertical ? 95 : params.isCategory ? (Math.ceil(scale1(ticks[1]) - scale1(ticks[0])) - 12) : 110;
                      }
  
                      function split(splitted, text) {
                          spaceIndex = undefined;
                          for (var i = 1; i < text.length; i++) {
                              if (text.charAt(i) === ' ') {
                                  spaceIndex = i;
                              }
                              subtext = text.substr(0, i + 1);
                              textWidth = sizeFor1Char.w * subtext.length;
                              // if text width gets over tick width, split by space index or crrent index
                              if (maxWidth < textWidth) {
                                  return split(
                                      splitted.concat(text.substr(0, spaceIndex ? spaceIndex : i)),
                                      text.slice(spaceIndex ? spaceIndex + 1 : i)
                                  );
                              }
                          }
                          return splitted.concat(text);
                      }
  
                      return split(splitted, tickText + "");
                  }
  
                  function tspanDy(d, i) {
                      var dy = sizeFor1Char.h;
                      if (i === 0) {
                          if (orient === 'left' || orient === 'right') {
                              dy = -((counts[d.index] - 1) * (sizeFor1Char.h / 2) - 3);
                          } else {
                              dy = ".71em";
                          }
                      }
                      return dy;
                  }
  
                  function tickSize(d) {
                      var tickPosition = scale(d) + (tickCentered ? 0 : tickOffset);
                      return range[0] < tickPosition && tickPosition < range[1] ? innerTickSize : 0;
                  }
  
                  text = tick.select("text");
                  tspan = text.selectAll('tspan')
                      .data(function (d, i) {
                          var splitted = params.tickMultiline ? splitTickText(d, params.tickWidth) : [].concat(textFormatted(d));
                          counts[i] = splitted.length;
                          return splitted.map(function (s) {
                              return { index: i, splitted: s };
                          });
                      });
                  tspan.enter().append('tspan');
                  tspan.exit().remove();
                  tspan.text(function (d) { return d.splitted; });
  
                  var rotate = params.tickTextRotate;
  
                  function textAnchorForText(rotate) {
                      if (!rotate) {
                          return 'middle';
                      }
                      return rotate > 0 ? "start" : "end";
                  }
                  function textTransform(rotate) {
                      if (!rotate) {
                          return '';
                      }
                      return "rotate(" + rotate + ")";
                  }
                  function dxForText(rotate) {
                      if (!rotate) {
                          return 0;
                      }
                      return 8 * Math.sin(Math.PI * (rotate / 180));
                  }
                  function yForText(rotate) {
                      if (!rotate) {
                          return tickLength;
                      }
                      return 11.5 - 2.5 * (rotate / 15) * (rotate > 0 ? 1 : -1);
                  }
  
                  switch (orient) {
                  case "bottom":
                      {
                          tickTransform = axisX;
                          lineEnter.attr("y2", innerTickSize);
                          textEnter.attr("y", tickLength);
                          lineUpdate.attr("x1", tickX).attr("x2", tickX).attr("y2", tickSize);
                          textUpdate.attr("x", 0).attr("y", yForText(rotate))
                              .style("text-anchor", textAnchorForText(rotate))
                              .attr("transform", textTransform(rotate));
                          tspan.attr('x', 0).attr("dy", tspanDy).attr('dx', dxForText(rotate));
                          pathUpdate.attr("d", "M" + range[0] + "," + outerTickSize + "V0H" + range[1] + "V" + outerTickSize);
                          break;
                      }
                  case "top":
                      {
                          // TODO: rotated tick text
                          tickTransform = axisX;
                          lineEnter.attr("y2", -innerTickSize);
                          textEnter.attr("y", -tickLength);
                          lineUpdate.attr("x2", 0).attr("y2", -innerTickSize);
                          textUpdate.attr("x", 0).attr("y", -tickLength);
                          text.style("text-anchor", "middle");
                          tspan.attr('x', 0).attr("dy", "0em");
                          pathUpdate.attr("d", "M" + range[0] + "," + -outerTickSize + "V0H" + range[1] + "V" + -outerTickSize);
                          break;
                      }
                  case "left":
                      {
                          tickTransform = axisY;
                          lineEnter.attr("x2", -innerTickSize);
                          textEnter.attr("x", -tickLength);
                          lineUpdate.attr("x2", -innerTickSize).attr("y1", tickY).attr("y2", tickY);
                          textUpdate.attr("x", -tickLength).attr("y", tickOffset);
                          text.style("text-anchor", "end");
                          tspan.attr('x', -tickLength).attr("dy", tspanDy);
                          pathUpdate.attr("d", "M" + -outerTickSize + "," + range[0] + "H0V" + range[1] + "H" + -outerTickSize);
                          break;
                      }
                  case "right":
                      {
                          tickTransform = axisY;
                          lineEnter.attr("x2", innerTickSize);
                          textEnter.attr("x", tickLength);
                          lineUpdate.attr("x2", innerTickSize).attr("y2", 0);
                          textUpdate.attr("x", tickLength).attr("y", 0);
                          text.style("text-anchor", "start");
                          tspan.attr('x', tickLength).attr("dy", tspanDy);
                          pathUpdate.attr("d", "M" + outerTickSize + "," + range[0] + "H0V" + range[1] + "H" + outerTickSize);
                          break;
                      }
                  }
                  if (scale1.rangeBand) {
                      var x = scale1, dx = x.rangeBand() / 2;
                      scale0 = scale1 = function (d) {
                          return x(d) + dx;
                      };
                  } else if (scale0.rangeBand) {
                      scale0 = scale1;
                  } else {
                      tickExit.call(tickTransform, scale1);
                  }
                  tickEnter.call(tickTransform, scale0);
                  tickUpdate.call(tickTransform, scale1);
              });
          }
          axis.scale = function (x) {
              if (!arguments.length) { return scale; }
              scale = x;
              return axis;
          };
          axis.orient = function (x) {
              if (!arguments.length) { return orient; }
              orient = x in {top: 1, right: 1, bottom: 1, left: 1} ? x + "" : "bottom";
              return axis;
          };
          axis.tickFormat = function (format) {
              if (!arguments.length) { return tickFormat; }
              tickFormat = format;
              return axis;
          };
          axis.tickCentered = function (isCentered) {
              if (!arguments.length) { return tickCentered; }
              tickCentered = isCentered;
              return axis;
          };
          axis.tickOffset = function () {
              return tickOffset;
          };
          axis.tickInterval = function () {
              var interval, length;
              if (params.isCategory) {
                  interval = tickOffset * 2;
              }
              else {
                  length = axis.g.select('path.domain').node().getTotalLength() - outerTickSize * 2;
                  interval = length / axis.g.selectAll('line').size();
              }
              return interval === Infinity ? 0 : interval;
          };
          axis.ticks = function () {
              if (!arguments.length) { return tickArguments; }
              tickArguments = arguments;
              return axis;
          };
          axis.tickCulling = function (culling) {
              if (!arguments.length) { return tickCulling; }
              tickCulling = culling;
              return axis;
          };
          axis.tickValues = function (x) {
              if (typeof x === 'function') {
                  tickValues = function () {
                      return x(scale.domain());
                  };
              }
              else {
                  if (!arguments.length) { return tickValues; }
                  tickValues = x;
              }
              return axis;
          };
          return axis;
      }
  
      c3_chart_internal_fn.isSafari = function () {
          var ua = window.navigator.userAgent;
          return ua.indexOf('Safari') >= 0 && ua.indexOf('Chrome') < 0;
      };
      c3_chart_internal_fn.isChrome = function () {
          var ua = window.navigator.userAgent;
          return ua.indexOf('Chrome') >= 0;
      };
  
      // PhantomJS doesn't have support for Function.prototype.bind, which has caused confusion. Use
      // this polyfill to avoid the confusion.
      // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind#Polyfill
  
      if (!Function.prototype.bind) {
        Function.prototype.bind = function(oThis) {
          if (typeof this !== 'function') {
            // closest thing possible to the ECMAScript 5
            // internal IsCallable function
            throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
          }
  
          var aArgs   = Array.prototype.slice.call(arguments, 1),
              fToBind = this,
              fNOP    = function() {},
              fBound  = function() {
                return fToBind.apply(this instanceof fNOP ? this : oThis, aArgs.concat(Array.prototype.slice.call(arguments)));
              };
  
          fNOP.prototype = this.prototype;
          fBound.prototype = new fNOP();
  
          return fBound;
        };
      }
  
      if (typeof define === 'function' && define.amd) {
          define("c3", ["d3"], function () { return c3; });
      } else if ('undefined' !== typeof exports && 'undefined' !== typeof module) {
          module.exports = c3;
      } else {
          window.c3 = c3;
      }
  
  })(window);
  
  /*
   * Author: Alex Gibson
   * https://github.com/alexgibson/visibility.js
   * License: MIT license
   */
  
  (function(global, factory) {
      if (typeof define === 'function' && define.amd) {
          // AMD environment
          define(function() {
              return factory(global, global.document);
          });
      } else if (typeof module !== 'undefined' && module.exports) {
          // CommonJS environment
          module.exports = factory(global, global.document);
      } else {
          // Browser environment
          global.Visibility = factory(global, global.document);
      }
  } (typeof window !== 'undefined' ? window : this, function (w, d) {
  
      'use strict';
  
      function Visibility(options) {
  
          this.options = {
              onVisible: null,
              onHidden: null
          };
  
          //User defined options
          if (typeof options === 'object') {
  
              for (var i in options) {
                  if (options.hasOwnProperty(i)) {
                      this.options[i] = options[i];
                  }
              }
  
              //callback when page is hidden
              if (typeof this.options.onHidden === 'function') {
                  this.onHiddenCallback = this.options.onHidden;
              }
  
              //callback when page is visible
              if (typeof this.options.onVisible === 'function') {
                  this.onVisibleCallback = this.options.onVisible;
              }
          }
  
          //store a reference to our binding for visibilitychange event
          //this is needed for removeEventListener if destroy() is called
          this.change = this.bindContext(this, this.visibilityChange);
  
          //add an event listener for visibilitychange
          this.configListener('add');
      }
  
      Visibility.prototype.configListener = function (config) {
  
          var visProp, evtName;
  
          visProp = this.getHiddenProp(d);
  
          if (visProp) {
              evtName = visProp.replace(/[H|h]idden/, '') + 'visibilitychange';
  
              if (config === 'add') {
                  d.addEventListener(evtName, this.change, false);
              } else if (config === 'remove') {
                  d.removeEventListener(evtName, this.change, false);
              }
          }
      };
  
      Visibility.prototype.getHiddenProp = function (doc) {
  
          var prefixes = ['webkit', 'moz', 'ms', 'o'];
  
          // if 'hidden' is natively supported just return it
          if ('hidden' in doc) { return 'hidden'; }
  
          // otherwise loop over all the known prefixes until we find one
          for (var i = 0; i < prefixes.length; i += 1) {
              if ((prefixes[i] + 'Hidden') in doc) {
                  return prefixes[i] + 'Hidden';
              }
          }
  
          // otherwise it's not supported
          return null;
      };
  
      Visibility.prototype.isHidden = function () {
  
          var prop = this.getHiddenProp(d);
  
          if (!prop) { return false; }
  
          return d[prop];
      };
  
      Visibility.prototype.isSupported = function () {
  
          var prop = this.getHiddenProp(d);
  
          if (!prop) { return false; }
  
          return true;
      };
  
      Visibility.prototype.bindContext = function (context, handler) {
          return function () {
              return handler.call(context);
          };
      };
  
      Visibility.prototype.visibilityChange = function () {
  
          var hidden = this.isHidden();
  
          if (hidden && this.onHiddenCallback) {
              this.onHiddenCallback();
          } else if (!hidden && this.onVisibleCallback) {
              this.onVisibleCallback();
          }
      };
  
      Visibility.prototype.destroy = function () {
          this.configListener('remove');
          this.onHiddenCallback = null;
          this.onVisibleCallback = null;
      };
  
      return Visibility;
  
  }));
  
  "use strict";
  
  var eon = eon || {};
  eon.subsub = eon.subsub || subsub;
  eon.c = {
    create: function(options) {
  
      var self = this;
      var error = false;
  
      self.chart = false;
  
      self.pubnub = options.pubnub || PUBNUB || false;
  
      if(!self.pubnub) {
        error = "PubNub not found. See http://www.pubnub.com/docs/javascript/javascript-sdk.html#_where_do_i_get_the_code";
      }
  
      options.transform = options.transform || function(m){return m};
      options.channel = options.channel || false;
      options.generate = options.generate || {};
      if(!options.generate.data) {
        options.generate.data = {
          columns: null
        };
      }
      options.flow = options.flow || false;
      if(options.flow) { 
        if(typeof(options.flow) == "boolean") {
          options.flow = {};
        }
        options.flow.length = options.flow.length || 0;
      }
      options.limit = options.limit || 10;
      options.history = options.history || false;
  
      options.rate = options.rate || 1000;
  
      options.message = options.message || function(){};
      options.connect = options.connect || function(){};
  
      options.xcolumn = options.xcolumn || false;
  
      if(options.xcolumn) {
  
        if(!options.generate.axis) {
          options.generate.axis = {}
        }
  
        // assume js date
        if(!options.generate.axis.x) {
  
          options.generate.axis.x = {
            type: 'timeseries',
            tick: {
                format: '%Y-%m-%d %H:%M:%S'
            }
          }
  
        }
         
      }
  
      if(!options.channel) {
        error = "No channel supplied.";
      }
  
      var all_messages = [];
      var page = function() {
  
        all_messages = [];
        var i = 0;
  
        var getAllMessages = function(timetoken) {
           self.pubnub.history({
            count: options.limit,
            channel: options.channel,
            start: timetoken,
             callback: function(payload) {
  
               var msgs = payload[0];
               var start = payload[1];
               var end = payload[2];
  
               if (msgs !== undefined && msgs.length) {
  
                 msgs.reverse();
  
                i = 0;
                 while(i < msgs.length) {
                   all_messages.push(msgs[[i]]);
                   i++;
                 }
  
               }
  
               if (msgs.length && all_messages.length < options.limit) {
                 getAllMessages(start);
               } else {
  
                var data = [];
  
                 i = 0;
                 while(i < all_messages.length) {
  
                  var columns = all_messages[i].columns;
  
                   for(var j in columns) {
  
                      if(i === 0) {
                        data[j] = [];
                        data[j].push(columns[j][0]);
                      }
  
                      data[j].push(columns[j][1]);
  
                   }
  
                   i++;
  
                 }
  
                 // ready to go
                 data.reverse();
                 self.chart.load({columns: data});
  
               }
  
             }
           });
         };
  
         getAllMessages();
  
      };
  
      var buffer = [];
      var needsTrim = function() {
  
        buffer = self.chart.data();
  
        var i = 0;
  
        while(i < buffer.length) {
  
          if(buffer[i].values.length > options.limit) {
            var trimLength = buffer[i].values.length - 1 - options.limit;
            return trimLength;
          }
          i++;
  
        }
  
        return false;
  
      };
  
  
      var lastData = [];
      var lastX = null;
      var dataStore = [];
  
      var mapMessage = function(message) {
  
        var i = 0;
  
        // if we have data already
        if(lastData.length) {
  
          // loop through the new message
          while(i < message.columns.length) {
  
            var j = 0;
            var found = false;
  
            // and compare it against the old message
            while(j < lastData.length) {
  
              // if it's x, then see if the new one is larger
              if(
                message.columns[i][0] == options.xcolumn &&
                lastData[j][0] == options.xcolumn
              ) {
  
                if(message.columns[i][1] > lastData[j][1]) {
                  lastData[j][1] = message.columns[i][1];
                }
  
                // if they have the same key, overwrite the buffer              }
              }
  
              if(lastData[j][0] == message.columns[i][0]) {
                lastData[j][1] = message.columns[i][1];
                found = true;
              }
  
              j++;
  
            }
  
            if(!found) {
              lastData[j] = message.columns[i];
            }
  
            i++;
  
          }
  
        } else {
          lastData = message.columns;
        }
  
      };
  
      var updateInterval = false;
  
      var kill = function() {
      
        if(['donut', 'pie', 'gauge'].indexOf(options.generate.data.type) == -1) {
          self.chart.destroy();
        }
  
        delete self.chart;
      
      };
  
      var boot = function() {
  
        if(options.xcolumn) {
          options.generate.data.x = options.xcolumn; 
        }
  
        options.generate.data.columns = dataStore;
  
        if(dataStore.length && dataStore[0].length - 1 > options.limit) {
          dataStore = [];
        }
  
        self.chart = c3.generate(options.generate);
  
      };
  
      var reboot = function() {
        kill();
        boot();
      };
  
      Visibility.change(function (e, state) {
        reboot();
      });
  
      var init = function() {
  
        if(options.history) {
          page();
        }
  
        subsub.subscribe(self.pubnub, options.channel, options.connect, function(message, env, channel) {
  
          var message = options.transform(message);
  
          options.message(message, env, channel);
          mapMessage(message);
  
        });
  
        var recursive = function(){
  
          var newx = false;
          var i = 0;
  
          if(!dataStore.length || !options.xcolumn) {
            newx = true;
          }
  
          // find out if this x value is different from the last plotted
          while(i < lastData.length) {
  
            if(lastData[i][0] == options.xcolumn) {
  
              var j = 0;
  
              while(j < dataStore.length) {
  
                if(dataStore[j][0] == options.xcolumn &&
                  dataStore[j][dataStore[j].length - 1] !== lastData[i][1]) {
                  newx = true;
                }
  
                j++;
              }
  
  
            }
  
            i++;
          }
  
          if(newx && lastData.length) {
  
            if(options.flow) {
  
              var trimLength = needsTrim();
  
              if((buffer.length && !buffer[0].values.length) || trimLength > 1) {
                reboot();
              } else {
  
                if(trimLength)  {
                  options.flow.length = 1;
                }
  
                options.flow.columns = lastData;
                self.chart.flow(options.flow);
  
              }
  
            } else {
  
              self.chart.load({
                columns: lastData
              });
  
            }
  
            var i = 0;
            if(!dataStore.length) {
              dataStore = JSON.parse(JSON.stringify(lastData));
            } else {
  
              while(i < lastData.length) {
  
                // if this is a new key, add the id
                if(typeof dataStore[i] == "undefined") {
                  dataStore[i] = [lastData[i][0]];
                }
  
                dataStore[i].push(lastData[i][1]);
  
                if(dataStore[i].length > options.limit) {
                  dataStore[i].splice(1,1);
                }
  
                i++;
              }
  
            }
  
          }
  
          setTimeout(function(){
            recursive();
          }, options.rate);
  
        };
        recursive();
  
        return self;
  
      };
  
      if(error) {
        console.error("EON: " + error);
      } else {
        init();
        boot();
  
      }
  
      return self.chart;
  
    },
    flatten: function(ob) {
  
      var toReturn = {};
      
      for (var i in ob) {
        if (!ob.hasOwnProperty(i)) continue;
        
        if ((typeof ob[i]) == 'object') {
          var flatObject = eon.c.flatten(ob[i]);
          for (var x in flatObject) {
            if (!flatObject.hasOwnProperty(x)) continue;
            
            toReturn[i + '.' + x] = flatObject[x];
          }
        } else {
          toReturn[i] = ob[i];
        }
      }
      
      return toReturn;
  
    }
  };
  eon.chart = function(o) {
    return new eon.c.create(o);
  };
  
  !function t(e,i,n){function o(a,r){if(!i[a]){if(!e[a]){var l="function"==typeof require&&require;if(!r&&l)return l(a,!0);if(s)return s(a,!0);var h=new Error("Cannot find module '"+a+"'");throw h.code="MODULE_NOT_FOUND",h}var u=i[a]={exports:{}};e[a][0].call(u.exports,function(t){var i=e[a][1][t];return o(i?i:t)},u,u.exports,t,e,i,n)}return i[a].exports}for(var s="function"==typeof require&&require,a=0;a<n.length;a++)o(n[a]);return o}({1:[function(t,e){function i(t,e,i){function n(t){return t>=200&&300>t||304===t}function o(){void 0===r.status||n(r.status)?e.call(r,null,r):e.call(r,r,null)}var s=!1;if("undefined"==typeof window.XMLHttpRequest)return e(Error("Browser not supported"));if("undefined"==typeof i){var a=t.match(/^\s*https?:\/\/[^\/]*/);i=a&&a[0]!==location.protocol+"//"+location.domain+(location.port?":"+location.port:"")}var r=new window.XMLHttpRequest;if(i&&!("withCredentials"in r)){r=new window.XDomainRequest;var l=e;e=function(){if(s)l.apply(this,arguments);else{var t=this,e=arguments;setTimeout(function(){l.apply(t,e)},0)}}}return"onload"in r?r.onload=o:r.onreadystatechange=function(){4===r.readyState&&o()},r.onerror=function(t){e.call(this,t||!0,null),e=function(){}},r.onprogress=function(){},r.ontimeout=function(t){e.call(this,t,null),e=function(){}},r.onabort=function(t){e.call(this,t,null),e=function(){}},r.open("GET",t,!0),r.send(null),s=!0,r}"undefined"!=typeof e&&(e.exports=i)},{}],2:[function(t,e){!function(t,i,n){var o=t.L,s={};s.version="0.7.2","object"==typeof e&&"object"==typeof e.exports?e.exports=s:"function"==typeof define&&define.amd&&define(s),s.noConflict=function(){return t.L=o,this},t.L=s,s.Util={extend:function(t){var e,i,n,o,s=Array.prototype.slice.call(arguments,1);for(i=0,n=s.length;n>i;i++){o=s[i]||{};for(e in o)o.hasOwnProperty(e)&&(t[e]=o[e])}return t},bind:function(t,e){var i=arguments.length>2?Array.prototype.slice.call(arguments,2):null;return function(){return t.apply(e,i||arguments)}},stamp:function(){var t=0,e="_leaflet_id";return function(i){return i[e]=i[e]||++t,i[e]}}(),invokeEach:function(t,e,i){var n,o;if("object"==typeof t){o=Array.prototype.slice.call(arguments,3);for(n in t)e.apply(i,[n,t[n]].concat(o));return!0}return!1},limitExecByInterval:function(t,e,i){var n,o;return function s(){var a=arguments;return n?(o=!0,void 0):(n=!0,setTimeout(function(){n=!1,o&&(s.apply(i,a),o=!1)},e),t.apply(i,a),void 0)}},falseFn:function(){return!1},formatNum:function(t,e){var i=Math.pow(10,e||5);return Math.round(t*i)/i},trim:function(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")},splitWords:function(t){return s.Util.trim(t).split(/\s+/)},setOptions:function(t,e){return t.options=s.extend({},t.options,e),t.options},getParamString:function(t,e,i){var n=[];for(var o in t)n.push(encodeURIComponent(i?o.toUpperCase():o)+"="+encodeURIComponent(t[o]));return(e&&-1!==e.indexOf("?")?"&":"?")+n.join("&")},template:function(t,e){return t.replace(/\{ *([\w_]+) *\}/g,function(t,i){var o=e[i];if(o===n)throw new Error("No value provided for variable "+t);return"function"==typeof o&&(o=o(e)),o})},isArray:Array.isArray||function(t){return"[object Array]"===Object.prototype.toString.call(t)},emptyImageUrl:"data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs="},function(){function e(e){var i,n,o=["webkit","moz","o","ms"];for(i=0;i<o.length&&!n;i++)n=t[o[i]+e];return n}function i(e){var i=+new Date,o=Math.max(0,16-(i-n));return n=i+o,t.setTimeout(e,o)}var n=0,o=t.requestAnimationFrame||e("RequestAnimationFrame")||i,a=t.cancelAnimationFrame||e("CancelAnimationFrame")||e("CancelRequestAnimationFrame")||function(e){t.clearTimeout(e)};s.Util.requestAnimFrame=function(e,n,a,r){return e=s.bind(e,n),a&&o===i?(e(),void 0):o.call(t,e,r)},s.Util.cancelAnimFrame=function(e){e&&a.call(t,e)}}(),s.extend=s.Util.extend,s.bind=s.Util.bind,s.stamp=s.Util.stamp,s.setOptions=s.Util.setOptions,s.Class=function(){},s.Class.extend=function(t){var e=function(){this.initialize&&this.initialize.apply(this,arguments),this._initHooks&&this.callInitHooks()},i=function(){};i.prototype=this.prototype;var n=new i;n.constructor=e,e.prototype=n;for(var o in this)this.hasOwnProperty(o)&&"prototype"!==o&&(e[o]=this[o]);t.statics&&(s.extend(e,t.statics),delete t.statics),t.includes&&(s.Util.extend.apply(null,[n].concat(t.includes)),delete t.includes),t.options&&n.options&&(t.options=s.extend({},n.options,t.options)),s.extend(n,t),n._initHooks=[];var a=this;return e.__super__=a.prototype,n.callInitHooks=function(){if(!this._initHooksCalled){a.prototype.callInitHooks&&a.prototype.callInitHooks.call(this),this._initHooksCalled=!0;for(var t=0,e=n._initHooks.length;e>t;t++)n._initHooks[t].call(this)}},e},s.Class.include=function(t){s.extend(this.prototype,t)},s.Class.mergeOptions=function(t){s.extend(this.prototype.options,t)},s.Class.addInitHook=function(t){var e=Array.prototype.slice.call(arguments,1),i="function"==typeof t?t:function(){this[t].apply(this,e)};this.prototype._initHooks=this.prototype._initHooks||[],this.prototype._initHooks.push(i)};var a="_leaflet_events";s.Mixin={},s.Mixin.Events={addEventListener:function(t,e,i){if(s.Util.invokeEach(t,this.addEventListener,this,e,i))return this;var n,o,r,l,h,u,c,p=this[a]=this[a]||{},d=i&&i!==this&&s.stamp(i);for(t=s.Util.splitWords(t),n=0,o=t.length;o>n;n++)r={action:e,context:i||this},l=t[n],d?(h=l+"_idx",u=h+"_len",c=p[h]=p[h]||{},c[d]||(c[d]=[],p[u]=(p[u]||0)+1),c[d].push(r)):(p[l]=p[l]||[],p[l].push(r));return this},hasEventListeners:function(t){var e=this[a];return!!e&&(t in e&&e[t].length>0||t+"_idx"in e&&e[t+"_idx_len"]>0)},removeEventListener:function(t,e,i){if(!this[a])return this;if(!t)return this.clearAllEventListeners();if(s.Util.invokeEach(t,this.removeEventListener,this,e,i))return this;var n,o,r,l,h,u,c,p,d,m=this[a],f=i&&i!==this&&s.stamp(i);for(t=s.Util.splitWords(t),n=0,o=t.length;o>n;n++)if(r=t[n],u=r+"_idx",c=u+"_len",p=m[u],e){if(l=f&&p?p[f]:m[r]){for(h=l.length-1;h>=0;h--)l[h].action!==e||i&&l[h].context!==i||(d=l.splice(h,1),d[0].action=s.Util.falseFn);i&&p&&0===l.length&&(delete p[f],m[c]--)}}else delete m[r],delete m[u],delete m[c];return this},clearAllEventListeners:function(){return delete this[a],this},fireEvent:function(t,e){if(!this.hasEventListeners(t))return this;var i,n,o,r,l,h=s.Util.extend({},e,{type:t,target:this}),u=this[a];if(u[t])for(i=u[t].slice(),n=0,o=i.length;o>n;n++)i[n].action.call(i[n].context,h);r=u[t+"_idx"];for(l in r)if(i=r[l].slice())for(n=0,o=i.length;o>n;n++)i[n].action.call(i[n].context,h);return this},addOneTimeEventListener:function(t,e,i){if(s.Util.invokeEach(t,this.addOneTimeEventListener,this,e,i))return this;var n=s.bind(function(){this.removeEventListener(t,e,i).removeEventListener(t,n,i)},this);return this.addEventListener(t,e,i).addEventListener(t,n,i)}},s.Mixin.Events.on=s.Mixin.Events.addEventListener,s.Mixin.Events.off=s.Mixin.Events.removeEventListener,s.Mixin.Events.once=s.Mixin.Events.addOneTimeEventListener,s.Mixin.Events.fire=s.Mixin.Events.fireEvent,function(){var e="ActiveXObject"in t,o=e&&!i.addEventListener,a=navigator.userAgent.toLowerCase(),r=-1!==a.indexOf("webkit"),l=-1!==a.indexOf("chrome"),h=-1!==a.indexOf("phantom"),u=-1!==a.indexOf("android"),c=-1!==a.search("android [23]"),p=-1!==a.indexOf("gecko"),d=typeof orientation!=n+"",m=t.navigator&&t.navigator.msPointerEnabled&&t.navigator.msMaxTouchPoints&&!t.PointerEvent,f=t.PointerEvent&&t.navigator.pointerEnabled&&t.navigator.maxTouchPoints||m,_="devicePixelRatio"in t&&t.devicePixelRatio>1||"matchMedia"in t&&t.matchMedia("(min-resolution:144dpi)")&&t.matchMedia("(min-resolution:144dpi)").matches,g=i.documentElement,v=e&&"transition"in g.style,y="WebKitCSSMatrix"in t&&"m11"in new t.WebKitCSSMatrix&&!c,L="MozPerspective"in g.style,b="OTransition"in g.style,T=!t.L_DISABLE_3D&&(v||y||L||b)&&!h,P=!t.L_NO_TOUCH&&!h&&function(){var t="ontouchstart";if(f||t in g)return!0;var e=i.createElement("div"),n=!1;return e.setAttribute?(e.setAttribute(t,"return;"),"function"==typeof e[t]&&(n=!0),e.removeAttribute(t),e=null,n):!1}();s.Browser={ie:e,ielt9:o,webkit:r,gecko:p&&!r&&!t.opera&&!e,android:u,android23:c,chrome:l,ie3d:v,webkit3d:y,gecko3d:L,opera3d:b,any3d:T,mobile:d,mobileWebkit:d&&r,mobileWebkit3d:d&&y,mobileOpera:d&&t.opera,touch:P,msPointer:m,pointer:f,retina:_}}(),s.Point=function(t,e,i){this.x=i?Math.round(t):t,this.y=i?Math.round(e):e},s.Point.prototype={clone:function(){return new s.Point(this.x,this.y)},add:function(t){return this.clone()._add(s.point(t))},_add:function(t){return this.x+=t.x,this.y+=t.y,this},subtract:function(t){return this.clone()._subtract(s.point(t))},_subtract:function(t){return this.x-=t.x,this.y-=t.y,this},divideBy:function(t){return this.clone()._divideBy(t)},_divideBy:function(t){return this.x/=t,this.y/=t,this},multiplyBy:function(t){return this.clone()._multiplyBy(t)},_multiplyBy:function(t){return this.x*=t,this.y*=t,this},round:function(){return this.clone()._round()},_round:function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this},floor:function(){return this.clone()._floor()},_floor:function(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this},distanceTo:function(t){t=s.point(t);var e=t.x-this.x,i=t.y-this.y;return Math.sqrt(e*e+i*i)},equals:function(t){return t=s.point(t),t.x===this.x&&t.y===this.y},contains:function(t){return t=s.point(t),Math.abs(t.x)<=Math.abs(this.x)&&Math.abs(t.y)<=Math.abs(this.y)},toString:function(){return"Point("+s.Util.formatNum(this.x)+", "+s.Util.formatNum(this.y)+")"}},s.point=function(t,e,i){return t instanceof s.Point?t:s.Util.isArray(t)?new s.Point(t[0],t[1]):t===n||null===t?t:new s.Point(t,e,i)},s.Bounds=function(t,e){if(t)for(var i=e?[t,e]:t,n=0,o=i.length;o>n;n++)this.extend(i[n])},s.Bounds.prototype={extend:function(t){return t=s.point(t),this.min||this.max?(this.min.x=Math.min(t.x,this.min.x),this.max.x=Math.max(t.x,this.max.x),this.min.y=Math.min(t.y,this.min.y),this.max.y=Math.max(t.y,this.max.y)):(this.min=t.clone(),this.max=t.clone()),this},getCenter:function(t){return new s.Point((this.min.x+this.max.x)/2,(this.min.y+this.max.y)/2,t)},getBottomLeft:function(){return new s.Point(this.min.x,this.max.y)},getTopRight:function(){return new s.Point(this.max.x,this.min.y)},getSize:function(){return this.max.subtract(this.min)},contains:function(t){var e,i;return t="number"==typeof t[0]||t instanceof s.Point?s.point(t):s.bounds(t),t instanceof s.Bounds?(e=t.min,i=t.max):e=i=t,e.x>=this.min.x&&i.x<=this.max.x&&e.y>=this.min.y&&i.y<=this.max.y},intersects:function(t){t=s.bounds(t);var e=this.min,i=this.max,n=t.min,o=t.max,a=o.x>=e.x&&n.x<=i.x,r=o.y>=e.y&&n.y<=i.y;return a&&r},isValid:function(){return!(!this.min||!this.max)}},s.bounds=function(t,e){return!t||t instanceof s.Bounds?t:new s.Bounds(t,e)},s.Transformation=function(t,e,i,n){this._a=t,this._b=e,this._c=i,this._d=n},s.Transformation.prototype={transform:function(t,e){return this._transform(t.clone(),e)},_transform:function(t,e){return e=e||1,t.x=e*(this._a*t.x+this._b),t.y=e*(this._c*t.y+this._d),t},untransform:function(t,e){return e=e||1,new s.Point((t.x/e-this._b)/this._a,(t.y/e-this._d)/this._c)}},s.DomUtil={get:function(t){return"string"==typeof t?i.getElementById(t):t},getStyle:function(t,e){var n=t.style[e];if(!n&&t.currentStyle&&(n=t.currentStyle[e]),(!n||"auto"===n)&&i.defaultView){var o=i.defaultView.getComputedStyle(t,null);n=o?o[e]:null}return"auto"===n?null:n},getViewportOffset:function(t){var e,n=0,o=0,a=t,r=i.body,l=i.documentElement;do{if(n+=a.offsetTop||0,o+=a.offsetLeft||0,n+=parseInt(s.DomUtil.getStyle(a,"borderTopWidth"),10)||0,o+=parseInt(s.DomUtil.getStyle(a,"borderLeftWidth"),10)||0,e=s.DomUtil.getStyle(a,"position"),a.offsetParent===r&&"absolute"===e)break;if("fixed"===e){n+=r.scrollTop||l.scrollTop||0,o+=r.scrollLeft||l.scrollLeft||0;break}if("relative"===e&&!a.offsetLeft){var h=s.DomUtil.getStyle(a,"width"),u=s.DomUtil.getStyle(a,"max-width"),c=a.getBoundingClientRect();("none"!==h||"none"!==u)&&(o+=c.left+a.clientLeft),n+=c.top+(r.scrollTop||l.scrollTop||0);break}a=a.offsetParent}while(a);a=t;do{if(a===r)break;n-=a.scrollTop||0,o-=a.scrollLeft||0,a=a.parentNode}while(a);return new s.Point(o,n)},documentIsLtr:function(){return s.DomUtil._docIsLtrCached||(s.DomUtil._docIsLtrCached=!0,s.DomUtil._docIsLtr="ltr"===s.DomUtil.getStyle(i.body,"direction")),s.DomUtil._docIsLtr},create:function(t,e,n){var o=i.createElement(t);return o.className=e,n&&n.appendChild(o),o},hasClass:function(t,e){if(t.classList!==n)return t.classList.contains(e);var i=s.DomUtil._getClass(t);return i.length>0&&new RegExp("(^|\\s)"+e+"(\\s|$)").test(i)},addClass:function(t,e){if(t.classList!==n)for(var i=s.Util.splitWords(e),o=0,a=i.length;a>o;o++)t.classList.add(i[o]);else if(!s.DomUtil.hasClass(t,e)){var r=s.DomUtil._getClass(t);s.DomUtil._setClass(t,(r?r+" ":"")+e)}},removeClass:function(t,e){t.classList!==n?t.classList.remove(e):s.DomUtil._setClass(t,s.Util.trim((" "+s.DomUtil._getClass(t)+" ").replace(" "+e+" "," ")))},_setClass:function(t,e){t.className.baseVal===n?t.className=e:t.className.baseVal=e},_getClass:function(t){return t.className.baseVal===n?t.className:t.className.baseVal},setOpacity:function(t,e){if("opacity"in t.style)t.style.opacity=e;else if("filter"in t.style){var i=!1,n="DXImageTransform.Microsoft.Alpha";try{i=t.filters.item(n)}catch(o){if(1===e)return}e=Math.round(100*e),i?(i.Enabled=100!==e,i.Opacity=e):t.style.filter+=" progid:"+n+"(opacity="+e+")"}},testProp:function(t){for(var e=i.documentElement.style,n=0;n<t.length;n++)if(t[n]in e)return t[n];return!1},getTranslateString:function(t){var e=s.Browser.webkit3d,i="translate"+(e?"3d":"")+"(",n=(e?",0":"")+")";return i+t.x+"px,"+t.y+"px"+n},getScaleString:function(t,e){var i=s.DomUtil.getTranslateString(e.add(e.multiplyBy(-1*t))),n=" scale("+t+") ";return i+n},setPosition:function(t,e,i){t._leaflet_pos=e,!i&&s.Browser.any3d?t.style[s.DomUtil.TRANSFORM]=s.DomUtil.getTranslateString(e):(t.style.left=e.x+"px",t.style.top=e.y+"px")},getPosition:function(t){return t._leaflet_pos}},s.DomUtil.TRANSFORM=s.DomUtil.testProp(["transform","WebkitTransform","OTransform","MozTransform","msTransform"]),s.DomUtil.TRANSITION=s.DomUtil.testProp(["webkitTransition","transition","OTransition","MozTransition","msTransition"]),s.DomUtil.TRANSITION_END="webkitTransition"===s.DomUtil.TRANSITION||"OTransition"===s.DomUtil.TRANSITION?s.DomUtil.TRANSITION+"End":"transitionend",function(){if("onselectstart"in i)s.extend(s.DomUtil,{disableTextSelection:function(){s.DomEvent.on(t,"selectstart",s.DomEvent.preventDefault)},enableTextSelection:function(){s.DomEvent.off(t,"selectstart",s.DomEvent.preventDefault)}});else{var e=s.DomUtil.testProp(["userSelect","WebkitUserSelect","OUserSelect","MozUserSelect","msUserSelect"]);s.extend(s.DomUtil,{disableTextSelection:function(){if(e){var t=i.documentElement.style;this._userSelect=t[e],t[e]="none"}},enableTextSelection:function(){e&&(i.documentElement.style[e]=this._userSelect,delete this._userSelect)}})}s.extend(s.DomUtil,{disableImageDrag:function(){s.DomEvent.on(t,"dragstart",s.DomEvent.preventDefault)},enableImageDrag:function(){s.DomEvent.off(t,"dragstart",s.DomEvent.preventDefault)}})}(),s.LatLng=function(t,e,i){if(t=parseFloat(t),e=parseFloat(e),isNaN(t)||isNaN(e))throw new Error("Invalid LatLng object: ("+t+", "+e+")");this.lat=t,this.lng=e,i!==n&&(this.alt=parseFloat(i))},s.extend(s.LatLng,{DEG_TO_RAD:Math.PI/180,RAD_TO_DEG:180/Math.PI,MAX_MARGIN:1e-9}),s.LatLng.prototype={equals:function(t){if(!t)return!1;t=s.latLng(t);var e=Math.max(Math.abs(this.lat-t.lat),Math.abs(this.lng-t.lng));return e<=s.LatLng.MAX_MARGIN},toString:function(t){return"LatLng("+s.Util.formatNum(this.lat,t)+", "+s.Util.formatNum(this.lng,t)+")"},distanceTo:function(t){t=s.latLng(t);var e=6378137,i=s.LatLng.DEG_TO_RAD,n=(t.lat-this.lat)*i,o=(t.lng-this.lng)*i,a=this.lat*i,r=t.lat*i,l=Math.sin(n/2),h=Math.sin(o/2),u=l*l+h*h*Math.cos(a)*Math.cos(r);return 2*e*Math.atan2(Math.sqrt(u),Math.sqrt(1-u))},wrap:function(t,e){var i=this.lng;return t=t||-180,e=e||180,i=(i+e)%(e-t)+(t>i||i===e?e:t),new s.LatLng(this.lat,i)}},s.latLng=function(t,e){return t instanceof s.LatLng?t:s.Util.isArray(t)?"number"==typeof t[0]||"string"==typeof t[0]?new s.LatLng(t[0],t[1],t[2]):null:t===n||null===t?t:"object"==typeof t&&"lat"in t?new s.LatLng(t.lat,"lng"in t?t.lng:t.lon):e===n?null:new s.LatLng(t,e)},s.LatLngBounds=function(t,e){if(t)for(var i=e?[t,e]:t,n=0,o=i.length;o>n;n++)this.extend(i[n])},s.LatLngBounds.prototype={extend:function(t){if(!t)return this;var e=s.latLng(t);return t=null!==e?e:s.latLngBounds(t),t instanceof s.LatLng?this._southWest||this._northEast?(this._southWest.lat=Math.min(t.lat,this._southWest.lat),this._southWest.lng=Math.min(t.lng,this._southWest.lng),this._northEast.lat=Math.max(t.lat,this._northEast.lat),this._northEast.lng=Math.max(t.lng,this._northEast.lng)):(this._southWest=new s.LatLng(t.lat,t.lng),this._northEast=new s.LatLng(t.lat,t.lng)):t instanceof s.LatLngBounds&&(this.extend(t._southWest),this.extend(t._northEast)),this},pad:function(t){var e=this._southWest,i=this._northEast,n=Math.abs(e.lat-i.lat)*t,o=Math.abs(e.lng-i.lng)*t;return new s.LatLngBounds(new s.LatLng(e.lat-n,e.lng-o),new s.LatLng(i.lat+n,i.lng+o))},getCenter:function(){return new s.LatLng((this._southWest.lat+this._northEast.lat)/2,(this._southWest.lng+this._northEast.lng)/2)},getSouthWest:function(){return this._southWest},getNorthEast:function(){return this._northEast},getNorthWest:function(){return new s.LatLng(this.getNorth(),this.getWest())},getSouthEast:function(){return new s.LatLng(this.getSouth(),this.getEast())},getWest:function(){return this._southWest.lng},getSouth:function(){return this._southWest.lat},getEast:function(){return this._northEast.lng},getNorth:function(){return this._northEast.lat},contains:function(t){t="number"==typeof t[0]||t instanceof s.LatLng?s.latLng(t):s.latLngBounds(t);var e,i,n=this._southWest,o=this._northEast;return t instanceof s.LatLngBounds?(e=t.getSouthWest(),i=t.getNorthEast()):e=i=t,e.lat>=n.lat&&i.lat<=o.lat&&e.lng>=n.lng&&i.lng<=o.lng},intersects:function(t){t=s.latLngBounds(t);var e=this._southWest,i=this._northEast,n=t.getSouthWest(),o=t.getNorthEast(),a=o.lat>=e.lat&&n.lat<=i.lat,r=o.lng>=e.lng&&n.lng<=i.lng;return a&&r},toBBoxString:function(){return[this.getWest(),this.getSouth(),this.getEast(),this.getNorth()].join(",")},equals:function(t){return t?(t=s.latLngBounds(t),this._southWest.equals(t.getSouthWest())&&this._northEast.equals(t.getNorthEast())):!1},isValid:function(){return!(!this._southWest||!this._northEast)}},s.latLngBounds=function(t,e){return!t||t instanceof s.LatLngBounds?t:new s.LatLngBounds(t,e)},s.Projection={},s.Projection.SphericalMercator={MAX_LATITUDE:85.0511287798,project:function(t){var e=s.LatLng.DEG_TO_RAD,i=this.MAX_LATITUDE,n=Math.max(Math.min(i,t.lat),-i),o=t.lng*e,a=n*e;return a=Math.log(Math.tan(Math.PI/4+a/2)),new s.Point(o,a)},unproject:function(t){var e=s.LatLng.RAD_TO_DEG,i=t.x*e,n=(2*Math.atan(Math.exp(t.y))-Math.PI/2)*e;return new s.LatLng(n,i)}},s.Projection.LonLat={project:function(t){return new s.Point(t.lng,t.lat)},unproject:function(t){return new s.LatLng(t.y,t.x)}},s.CRS={latLngToPoint:function(t,e){var i=this.projection.project(t),n=this.scale(e);return this.transformation._transform(i,n)},pointToLatLng:function(t,e){var i=this.scale(e),n=this.transformation.untransform(t,i);return this.projection.unproject(n)},project:function(t){return this.projection.project(t)},scale:function(t){return 256*Math.pow(2,t)},getSize:function(t){var e=this.scale(t);return s.point(e,e)}},s.CRS.Simple=s.extend({},s.CRS,{projection:s.Projection.LonLat,transformation:new s.Transformation(1,0,-1,0),scale:function(t){return Math.pow(2,t)}}),s.CRS.EPSG3857=s.extend({},s.CRS,{code:"EPSG:3857",projection:s.Projection.SphericalMercator,transformation:new s.Transformation(.5/Math.PI,.5,-.5/Math.PI,.5),project:function(t){var e=this.projection.project(t),i=6378137;return e.multiplyBy(i)}}),s.CRS.EPSG900913=s.extend({},s.CRS.EPSG3857,{code:"EPSG:900913"}),s.CRS.EPSG4326=s.extend({},s.CRS,{code:"EPSG:4326",projection:s.Projection.LonLat,transformation:new s.Transformation(1/360,.5,-1/360,.5)}),s.Map=s.Class.extend({includes:s.Mixin.Events,options:{crs:s.CRS.EPSG3857,fadeAnimation:s.DomUtil.TRANSITION&&!s.Browser.android23,trackResize:!0,markerZoomAnimation:s.DomUtil.TRANSITION&&s.Browser.any3d},initialize:function(t,e){e=s.setOptions(this,e),this._initContainer(t),this._initLayout(),this._onResize=s.bind(this._onResize,this),this._initEvents(),e.maxBounds&&this.setMaxBounds(e.maxBounds),e.center&&e.zoom!==n&&this.setView(s.latLng(e.center),e.zoom,{reset:!0}),this._handlers=[],this._layers={},this._zoomBoundLayers={},this._tileLayersNum=0,this.callInitHooks(),this._addLayers(e.layers)},setView:function(t,e){return e=e===n?this.getZoom():e,this._resetView(s.latLng(t),this._limitZoom(e)),this},setZoom:function(t,e){return this._loaded?this.setView(this.getCenter(),t,{zoom:e}):(this._zoom=this._limitZoom(t),this)},zoomIn:function(t,e){return this.setZoom(this._zoom+(t||1),e)},zoomOut:function(t,e){return this.setZoom(this._zoom-(t||1),e)},setZoomAround:function(t,e,i){var n=this.getZoomScale(e),o=this.getSize().divideBy(2),a=t instanceof s.Point?t:this.latLngToContainerPoint(t),r=a.subtract(o).multiplyBy(1-1/n),l=this.containerPointToLatLng(o.add(r));return this.setView(l,e,{zoom:i})},fitBounds:function(t,e){e=e||{},t=t.getBounds?t.getBounds():s.latLngBounds(t);var i=s.point(e.paddingTopLeft||e.padding||[0,0]),n=s.point(e.paddingBottomRight||e.padding||[0,0]),o=this.getBoundsZoom(t,!1,i.add(n)),a=n.subtract(i).divideBy(2),r=this.project(t.getSouthWest(),o),l=this.project(t.getNorthEast(),o),h=this.unproject(r.add(l).divideBy(2).add(a),o);return o=e&&e.maxZoom?Math.min(e.maxZoom,o):o,this.setView(h,o,e)},fitWorld:function(t){return this.fitBounds([[-90,-180],[90,180]],t)},panTo:function(t,e){return this.setView(t,this._zoom,{pan:e})},panBy:function(t){return this.fire("movestart"),this._rawPanBy(s.point(t)),this.fire("move"),this.fire("moveend")},setMaxBounds:function(t){return t=s.latLngBounds(t),this.options.maxBounds=t,t?(this._loaded&&this._panInsideMaxBounds(),this.on("moveend",this._panInsideMaxBounds,this)):this.off("moveend",this._panInsideMaxBounds,this)},panInsideBounds:function(t,e){var i=this.getCenter(),n=this._limitCenter(i,this._zoom,t);return i.equals(n)?this:this.panTo(n,e)},addLayer:function(t){var e=s.stamp(t);return this._layers[e]?this:(this._layers[e]=t,!t.options||isNaN(t.options.maxZoom)&&isNaN(t.options.minZoom)||(this._zoomBoundLayers[e]=t,this._updateZoomLevels()),this.options.zoomAnimation&&s.TileLayer&&t instanceof s.TileLayer&&(this._tileLayersNum++,this._tileLayersToLoad++,t.on("load",this._onTileLayerLoad,this)),this._loaded&&this._layerAdd(t),this)},removeLayer:function(t){var e=s.stamp(t);return this._layers[e]?(this._loaded&&t.onRemove(this),delete this._layers[e],this._loaded&&this.fire("layerremove",{layer:t}),this._zoomBoundLayers[e]&&(delete this._zoomBoundLayers[e],this._updateZoomLevels()),this.options.zoomAnimation&&s.TileLayer&&t instanceof s.TileLayer&&(this._tileLayersNum--,this._tileLayersToLoad--,t.off("load",this._onTileLayerLoad,this)),this):this},hasLayer:function(t){return t?s.stamp(t)in this._layers:!1},eachLayer:function(t,e){for(var i in this._layers)t.call(e,this._layers[i]);return this},invalidateSize:function(t){if(!this._loaded)return this;t=s.extend({animate:!1,pan:!0},t===!0?{animate:!0}:t);var e=this.getSize();this._sizeChanged=!0,this._initialCenter=null;var i=this.getSize(),n=e.divideBy(2).round(),o=i.divideBy(2).round(),a=n.subtract(o);return a.x||a.y?(t.animate&&t.pan?this.panBy(a):(t.pan&&this._rawPanBy(a),this.fire("move"),t.debounceMoveend?(clearTimeout(this._sizeTimer),this._sizeTimer=setTimeout(s.bind(this.fire,this,"moveend"),200)):this.fire("moveend")),this.fire("resize",{oldSize:e,newSize:i})):this},addHandler:function(t,e){if(!e)return this;var i=this[t]=new e(this);return this._handlers.push(i),this.options[t]&&i.enable(),this},remove:function(){this._loaded&&this.fire("unload"),this._initEvents("off");try{delete this._container._leaflet}catch(t){this._container._leaflet=n}return this._clearPanes(),this._clearControlPos&&this._clearControlPos(),this._clearHandlers(),this},getCenter:function(){return this._checkIfLoaded(),this._initialCenter&&!this._moved()?this._initialCenter:this.layerPointToLatLng(this._getCenterLayerPoint())},getZoom:function(){return this._zoom},getBounds:function(){var t=this.getPixelBounds(),e=this.unproject(t.getBottomLeft()),i=this.unproject(t.getTopRight());return new s.LatLngBounds(e,i)},getMinZoom:function(){return this.options.minZoom===n?this._layersMinZoom===n?0:this._layersMinZoom:this.options.minZoom},getMaxZoom:function(){return this.options.maxZoom===n?this._layersMaxZoom===n?1/0:this._layersMaxZoom:this.options.maxZoom},getBoundsZoom:function(t,e,i){t=s.latLngBounds(t);var n,o=this.getMinZoom()-(e?1:0),a=this.getMaxZoom(),r=this.getSize(),l=t.getNorthWest(),h=t.getSouthEast(),u=!0;i=s.point(i||[0,0]);do o++,n=this.project(h,o).subtract(this.project(l,o)).add(i),u=e?n.x<r.x||n.y<r.y:r.contains(n);while(u&&a>=o);return u&&e?null:e?o:o-1},getSize:function(){return(!this._size||this._sizeChanged)&&(this._size=new s.Point(this._container.clientWidth,this._container.clientHeight),this._sizeChanged=!1),this._size.clone()},getPixelBounds:function(){var t=this._getTopLeftPoint();return new s.Bounds(t,t.add(this.getSize()))},getPixelOrigin:function(){return this._checkIfLoaded(),this._initialTopLeftPoint},getPanes:function(){return this._panes},getContainer:function(){return this._container},getZoomScale:function(t){var e=this.options.crs;return e.scale(t)/e.scale(this._zoom)},getScaleZoom:function(t){return this._zoom+Math.log(t)/Math.LN2},project:function(t,e){return e=e===n?this._zoom:e,this.options.crs.latLngToPoint(s.latLng(t),e)},unproject:function(t,e){return e=e===n?this._zoom:e,this.options.crs.pointToLatLng(s.point(t),e)},layerPointToLatLng:function(t){var e=s.point(t).add(this.getPixelOrigin());return this.unproject(e)},latLngToLayerPoint:function(t){var e=this.project(s.latLng(t))._round();return e._subtract(this.getPixelOrigin())},containerPointToLayerPoint:function(t){return s.point(t).subtract(this._getMapPanePos())},layerPointToContainerPoint:function(t){return s.point(t).add(this._getMapPanePos())},containerPointToLatLng:function(t){var e=this.containerPointToLayerPoint(s.point(t));return this.layerPointToLatLng(e)},latLngToContainerPoint:function(t){return this.layerPointToContainerPoint(this.latLngToLayerPoint(s.latLng(t)))},mouseEventToContainerPoint:function(t){return s.DomEvent.getMousePosition(t,this._container)},mouseEventToLayerPoint:function(t){return this.containerPointToLayerPoint(this.mouseEventToContainerPoint(t))},mouseEventToLatLng:function(t){return this.layerPointToLatLng(this.mouseEventToLayerPoint(t))},_initContainer:function(t){var e=this._container=s.DomUtil.get(t);if(!e)throw new Error("Map container not found.");if(e._leaflet)throw new Error("Map container is already initialized.");e._leaflet=!0},_initLayout:function(){var t=this._container;s.DomUtil.addClass(t,"leaflet-container"+(s.Browser.touch?" leaflet-touch":"")+(s.Browser.retina?" leaflet-retina":"")+(s.Browser.ielt9?" leaflet-oldie":"")+(this.options.fadeAnimation?" leaflet-fade-anim":""));var e=s.DomUtil.getStyle(t,"position");"absolute"!==e&&"relative"!==e&&"fixed"!==e&&(t.style.position="relative"),this._initPanes(),this._initControlPos&&this._initControlPos()},_initPanes:function(){var t=this._panes={};this._mapPane=t.mapPane=this._createPane("leaflet-map-pane",this._container),this._tilePane=t.tilePane=this._createPane("leaflet-tile-pane",this._mapPane),t.objectsPane=this._createPane("leaflet-objects-pane",this._mapPane),t.shadowPane=this._createPane("leaflet-shadow-pane"),t.overlayPane=this._createPane("leaflet-overlay-pane"),t.markerPane=this._createPane("leaflet-marker-pane"),t.popupPane=this._createPane("leaflet-popup-pane");var e=" leaflet-zoom-hide";this.options.markerZoomAnimation||(s.DomUtil.addClass(t.markerPane,e),s.DomUtil.addClass(t.shadowPane,e),s.DomUtil.addClass(t.popupPane,e))},_createPane:function(t,e){return s.DomUtil.create("div",t,e||this._panes.objectsPane)},_clearPanes:function(){this._container.removeChild(this._mapPane)},_addLayers:function(t){t=t?s.Util.isArray(t)?t:[t]:[];for(var e=0,i=t.length;i>e;e++)this.addLayer(t[e])},_resetView:function(t,e,i,n){var o=this._zoom!==e;n||(this.fire("movestart"),o&&this.fire("zoomstart")),this._zoom=e,this._initialCenter=t,this._initialTopLeftPoint=this._getNewTopLeftPoint(t),i?this._initialTopLeftPoint._add(this._getMapPanePos()):s.DomUtil.setPosition(this._mapPane,new s.Point(0,0)),this._tileLayersToLoad=this._tileLayersNum;var a=!this._loaded;this._loaded=!0,this.fire("viewreset",{hard:!i}),a&&(this.fire("load"),this.eachLayer(this._layerAdd,this)),this.fire("move"),(o||n)&&this.fire("zoomend"),this.fire("moveend",{hard:!i})},_rawPanBy:function(t){s.DomUtil.setPosition(this._mapPane,this._getMapPanePos().subtract(t))},_getZoomSpan:function(){return this.getMaxZoom()-this.getMinZoom()},_updateZoomLevels:function(){var t,e=1/0,i=-1/0,o=this._getZoomSpan();for(t in this._zoomBoundLayers){var s=this._zoomBoundLayers[t];isNaN(s.options.minZoom)||(e=Math.min(e,s.options.minZoom)),isNaN(s.options.maxZoom)||(i=Math.max(i,s.options.maxZoom))}t===n?this._layersMaxZoom=this._layersMinZoom=n:(this._layersMaxZoom=i,this._layersMinZoom=e),o!==this._getZoomSpan()&&this.fire("zoomlevelschange")},_panInsideMaxBounds:function(){this.panInsideBounds(this.options.maxBounds)},_checkIfLoaded:function(){if(!this._loaded)throw new Error("Set map center and zoom first.")},_initEvents:function(e){if(s.DomEvent){e=e||"on",s.DomEvent[e](this._container,"click",this._onMouseClick,this);var i,n,o=["dblclick","mousedown","mouseup","mouseenter","mouseleave","mousemove","contextmenu"];for(i=0,n=o.length;n>i;i++)s.DomEvent[e](this._container,o[i],this._fireMouseEvent,this);this.options.trackResize&&s.DomEvent[e](t,"resize",this._onResize,this)}},_onResize:function(){s.Util.cancelAnimFrame(this._resizeRequest),this._resizeRequest=s.Util.requestAnimFrame(function(){this.invalidateSize({debounceMoveend:!0})},this,!1,this._container)},_onMouseClick:function(t){!this._loaded||!t._simulated&&(this.dragging&&this.dragging.moved()||this.boxZoom&&this.boxZoom.moved())||s.DomEvent._skipped(t)||(this.fire("preclick"),this._fireMouseEvent(t))},_fireMouseEvent:function(t){if(this._loaded&&!s.DomEvent._skipped(t)){var e=t.type;if(e="mouseenter"===e?"mouseover":"mouseleave"===e?"mouseout":e,this.hasEventListeners(e)){"contextmenu"===e&&s.DomEvent.preventDefault(t);var i=this.mouseEventToContainerPoint(t),n=this.containerPointToLayerPoint(i),o=this.layerPointToLatLng(n);this.fire(e,{latlng:o,layerPoint:n,containerPoint:i,originalEvent:t})}}},_onTileLayerLoad:function(){this._tileLayersToLoad--,this._tileLayersNum&&!this._tileLayersToLoad&&this.fire("tilelayersload")},_clearHandlers:function(){for(var t=0,e=this._handlers.length;e>t;t++)this._handlers[t].disable()},whenReady:function(t,e){return this._loaded?t.call(e||this,this):this.on("load",t,e),this},_layerAdd:function(t){t.onAdd(this),this.fire("layeradd",{layer:t})},_getMapPanePos:function(){return s.DomUtil.getPosition(this._mapPane)},_moved:function(){var t=this._getMapPanePos();return t&&!t.equals([0,0])},_getTopLeftPoint:function(){return this.getPixelOrigin().subtract(this._getMapPanePos())},_getNewTopLeftPoint:function(t,e){var i=this.getSize()._divideBy(2);return this.project(t,e)._subtract(i)._round()},_latLngToNewLayerPoint:function(t,e,i){var n=this._getNewTopLeftPoint(i,e).add(this._getMapPanePos());return this.project(t,e)._subtract(n)},_getCenterLayerPoint:function(){return this.containerPointToLayerPoint(this.getSize()._divideBy(2))},_getCenterOffset:function(t){return this.latLngToLayerPoint(t).subtract(this._getCenterLayerPoint())
  },_limitCenter:function(t,e,i){if(!i)return t;var n=this.project(t,e),o=this.getSize().divideBy(2),a=new s.Bounds(n.subtract(o),n.add(o)),r=this._getBoundsOffset(a,i,e);return this.unproject(n.add(r),e)},_limitOffset:function(t,e){if(!e)return t;var i=this.getPixelBounds(),n=new s.Bounds(i.min.add(t),i.max.add(t));return t.add(this._getBoundsOffset(n,e))},_getBoundsOffset:function(t,e,i){var n=this.project(e.getNorthWest(),i).subtract(t.min),o=this.project(e.getSouthEast(),i).subtract(t.max),a=this._rebound(n.x,-o.x),r=this._rebound(n.y,-o.y);return new s.Point(a,r)},_rebound:function(t,e){return t+e>0?Math.round(t-e)/2:Math.max(0,Math.ceil(t))-Math.max(0,Math.floor(e))},_limitZoom:function(t){var e=this.getMinZoom(),i=this.getMaxZoom();return Math.max(e,Math.min(i,t))}}),s.map=function(t,e){return new s.Map(t,e)},s.Projection.Mercator={MAX_LATITUDE:85.0840591556,R_MINOR:6356752.314245179,R_MAJOR:6378137,project:function(t){var e=s.LatLng.DEG_TO_RAD,i=this.MAX_LATITUDE,n=Math.max(Math.min(i,t.lat),-i),o=this.R_MAJOR,a=this.R_MINOR,r=t.lng*e*o,l=n*e,h=a/o,u=Math.sqrt(1-h*h),c=u*Math.sin(l);c=Math.pow((1-c)/(1+c),.5*u);var p=Math.tan(.5*(.5*Math.PI-l))/c;return l=-o*Math.log(p),new s.Point(r,l)},unproject:function(t){for(var e,i=s.LatLng.RAD_TO_DEG,n=this.R_MAJOR,o=this.R_MINOR,a=t.x*i/n,r=o/n,l=Math.sqrt(1-r*r),h=Math.exp(-t.y/n),u=Math.PI/2-2*Math.atan(h),c=15,p=1e-7,d=c,m=.1;Math.abs(m)>p&&--d>0;)e=l*Math.sin(u),m=Math.PI/2-2*Math.atan(h*Math.pow((1-e)/(1+e),.5*l))-u,u+=m;return new s.LatLng(u*i,a)}},s.CRS.EPSG3395=s.extend({},s.CRS,{code:"EPSG:3395",projection:s.Projection.Mercator,transformation:function(){var t=s.Projection.Mercator,e=t.R_MAJOR,i=.5/(Math.PI*e);return new s.Transformation(i,.5,-i,.5)}()}),s.TileLayer=s.Class.extend({includes:s.Mixin.Events,options:{minZoom:0,maxZoom:18,tileSize:256,subdomains:"abc",errorTileUrl:"",attribution:"",zoomOffset:0,opacity:1,unloadInvisibleTiles:s.Browser.mobile,updateWhenIdle:s.Browser.mobile},initialize:function(t,e){e=s.setOptions(this,e),e.detectRetina&&s.Browser.retina&&e.maxZoom>0&&(e.tileSize=Math.floor(e.tileSize/2),e.zoomOffset++,e.minZoom>0&&e.minZoom--,this.options.maxZoom--),e.bounds&&(e.bounds=s.latLngBounds(e.bounds)),this._url=t;var i=this.options.subdomains;"string"==typeof i&&(this.options.subdomains=i.split(""))},onAdd:function(t){this._map=t,this._animated=t._zoomAnimated,this._initContainer(),t.on({viewreset:this._reset,moveend:this._update},this),this._animated&&t.on({zoomanim:this._animateZoom,zoomend:this._endZoomAnim},this),this.options.updateWhenIdle||(this._limitedUpdate=s.Util.limitExecByInterval(this._update,150,this),t.on("move",this._limitedUpdate,this)),this._reset(),this._update()},addTo:function(t){return t.addLayer(this),this},onRemove:function(t){this._container.parentNode.removeChild(this._container),t.off({viewreset:this._reset,moveend:this._update},this),this._animated&&t.off({zoomanim:this._animateZoom,zoomend:this._endZoomAnim},this),this.options.updateWhenIdle||t.off("move",this._limitedUpdate,this),this._container=null,this._map=null},bringToFront:function(){var t=this._map._panes.tilePane;return this._container&&(t.appendChild(this._container),this._setAutoZIndex(t,Math.max)),this},bringToBack:function(){var t=this._map._panes.tilePane;return this._container&&(t.insertBefore(this._container,t.firstChild),this._setAutoZIndex(t,Math.min)),this},getAttribution:function(){return this.options.attribution},getContainer:function(){return this._container},setOpacity:function(t){return this.options.opacity=t,this._map&&this._updateOpacity(),this},setZIndex:function(t){return this.options.zIndex=t,this._updateZIndex(),this},setUrl:function(t,e){return this._url=t,e||this.redraw(),this},redraw:function(){return this._map&&(this._reset({hard:!0}),this._update()),this},_updateZIndex:function(){this._container&&this.options.zIndex!==n&&(this._container.style.zIndex=this.options.zIndex)},_setAutoZIndex:function(t,e){var i,n,o,s=t.children,a=-e(1/0,-1/0);for(n=0,o=s.length;o>n;n++)s[n]!==this._container&&(i=parseInt(s[n].style.zIndex,10),isNaN(i)||(a=e(a,i)));this.options.zIndex=this._container.style.zIndex=(isFinite(a)?a:0)+e(1,-1)},_updateOpacity:function(){var t,e=this._tiles;if(s.Browser.ielt9)for(t in e)s.DomUtil.setOpacity(e[t],this.options.opacity);else s.DomUtil.setOpacity(this._container,this.options.opacity)},_initContainer:function(){var t=this._map._panes.tilePane;if(!this._container){if(this._container=s.DomUtil.create("div","leaflet-layer"),this._updateZIndex(),this._animated){var e="leaflet-tile-container";this._bgBuffer=s.DomUtil.create("div",e,this._container),this._tileContainer=s.DomUtil.create("div",e,this._container)}else this._tileContainer=this._container;t.appendChild(this._container),this.options.opacity<1&&this._updateOpacity()}},_reset:function(t){for(var e in this._tiles)this.fire("tileunload",{tile:this._tiles[e]});this._tiles={},this._tilesToLoad=0,this.options.reuseTiles&&(this._unusedTiles=[]),this._tileContainer.innerHTML="",this._animated&&t&&t.hard&&this._clearBgBuffer(),this._initContainer()},_getTileSize:function(){var t=this._map,e=t.getZoom()+this.options.zoomOffset,i=this.options.maxNativeZoom,n=this.options.tileSize;return i&&e>i&&(n=Math.round(t.getZoomScale(e)/t.getZoomScale(i)*n)),n},_update:function(){if(this._map){var t=this._map,e=t.getPixelBounds(),i=t.getZoom(),n=this._getTileSize();if(!(i>this.options.maxZoom||i<this.options.minZoom)){var o=s.bounds(e.min.divideBy(n)._floor(),e.max.divideBy(n)._floor());this._addTilesFromCenterOut(o),(this.options.unloadInvisibleTiles||this.options.reuseTiles)&&this._removeOtherTiles(o)}}},_addTilesFromCenterOut:function(t){var e,n,o,a=[],r=t.getCenter();for(e=t.min.y;e<=t.max.y;e++)for(n=t.min.x;n<=t.max.x;n++)o=new s.Point(n,e),this._tileShouldBeLoaded(o)&&a.push(o);var l=a.length;if(0!==l){a.sort(function(t,e){return t.distanceTo(r)-e.distanceTo(r)});var h=i.createDocumentFragment();for(this._tilesToLoad||this.fire("loading"),this._tilesToLoad+=l,n=0;l>n;n++)this._addTile(a[n],h);this._tileContainer.appendChild(h)}},_tileShouldBeLoaded:function(t){if(t.x+":"+t.y in this._tiles)return!1;var e=this.options;if(!e.continuousWorld){var i=this._getWrapTileNum();if(e.noWrap&&(t.x<0||t.x>=i.x)||t.y<0||t.y>=i.y)return!1}if(e.bounds){var n=e.tileSize,o=t.multiplyBy(n),s=o.add([n,n]),a=this._map.unproject(o),r=this._map.unproject(s);if(e.continuousWorld||e.noWrap||(a=a.wrap(),r=r.wrap()),!e.bounds.intersects([a,r]))return!1}return!0},_removeOtherTiles:function(t){var e,i,n,o;for(o in this._tiles)e=o.split(":"),i=parseInt(e[0],10),n=parseInt(e[1],10),(i<t.min.x||i>t.max.x||n<t.min.y||n>t.max.y)&&this._removeTile(o)},_removeTile:function(t){var e=this._tiles[t];this.fire("tileunload",{tile:e,url:e.src}),this.options.reuseTiles?(s.DomUtil.removeClass(e,"leaflet-tile-loaded"),this._unusedTiles.push(e)):e.parentNode===this._tileContainer&&this._tileContainer.removeChild(e),s.Browser.android||(e.onload=null,e.src=s.Util.emptyImageUrl),delete this._tiles[t]},_addTile:function(t,e){var i=this._getTilePos(t),n=this._getTile();s.DomUtil.setPosition(n,i,s.Browser.chrome),this._tiles[t.x+":"+t.y]=n,this._loadTile(n,t),n.parentNode!==this._tileContainer&&e.appendChild(n)},_getZoomForUrl:function(){var t=this.options,e=this._map.getZoom();return t.zoomReverse&&(e=t.maxZoom-e),e+=t.zoomOffset,t.maxNativeZoom?Math.min(e,t.maxNativeZoom):e},_getTilePos:function(t){var e=this._map.getPixelOrigin(),i=this._getTileSize();return t.multiplyBy(i).subtract(e)},getTileUrl:function(t){return s.Util.template(this._url,s.extend({s:this._getSubdomain(t),z:t.z,x:t.x,y:t.y},this.options))},_getWrapTileNum:function(){var t=this._map.options.crs,e=t.getSize(this._map.getZoom());return e.divideBy(this._getTileSize())._floor()},_adjustTilePoint:function(t){var e=this._getWrapTileNum();this.options.continuousWorld||this.options.noWrap||(t.x=(t.x%e.x+e.x)%e.x),this.options.tms&&(t.y=e.y-t.y-1),t.z=this._getZoomForUrl()},_getSubdomain:function(t){var e=Math.abs(t.x+t.y)%this.options.subdomains.length;return this.options.subdomains[e]},_getTile:function(){if(this.options.reuseTiles&&this._unusedTiles.length>0){var t=this._unusedTiles.pop();return this._resetTile(t),t}return this._createTile()},_resetTile:function(){},_createTile:function(){var t=s.DomUtil.create("img","leaflet-tile");return t.style.width=t.style.height=this._getTileSize()+"px",t.galleryimg="no",t.onselectstart=t.onmousemove=s.Util.falseFn,s.Browser.ielt9&&this.options.opacity!==n&&s.DomUtil.setOpacity(t,this.options.opacity),s.Browser.mobileWebkit3d&&(t.style.WebkitBackfaceVisibility="hidden"),t},_loadTile:function(t,e){t._layer=this,t.onload=this._tileOnLoad,t.onerror=this._tileOnError,this._adjustTilePoint(e),t.src=this.getTileUrl(e),this.fire("tileloadstart",{tile:t,url:t.src})},_tileLoaded:function(){this._tilesToLoad--,this._animated&&s.DomUtil.addClass(this._tileContainer,"leaflet-zoom-animated"),this._tilesToLoad||(this.fire("load"),this._animated&&(clearTimeout(this._clearBgBufferTimer),this._clearBgBufferTimer=setTimeout(s.bind(this._clearBgBuffer,this),500)))},_tileOnLoad:function(){var t=this._layer;this.src!==s.Util.emptyImageUrl&&(s.DomUtil.addClass(this,"leaflet-tile-loaded"),t.fire("tileload",{tile:this,url:this.src})),t._tileLoaded()},_tileOnError:function(){var t=this._layer;t.fire("tileerror",{tile:this,url:this.src});var e=t.options.errorTileUrl;e&&(this.src=e),t._tileLoaded()}}),s.tileLayer=function(t,e){return new s.TileLayer(t,e)},s.TileLayer.WMS=s.TileLayer.extend({defaultWmsParams:{service:"WMS",request:"GetMap",version:"1.1.1",layers:"",styles:"",format:"image/jpeg",transparent:!1},initialize:function(t,e){this._url=t;var i=s.extend({},this.defaultWmsParams),n=e.tileSize||this.options.tileSize;i.width=i.height=e.detectRetina&&s.Browser.retina?2*n:n;for(var o in e)this.options.hasOwnProperty(o)||"crs"===o||(i[o]=e[o]);this.wmsParams=i,s.setOptions(this,e)},onAdd:function(t){this._crs=this.options.crs||t.options.crs,this._wmsVersion=parseFloat(this.wmsParams.version);var e=this._wmsVersion>=1.3?"crs":"srs";this.wmsParams[e]=this._crs.code,s.TileLayer.prototype.onAdd.call(this,t)},getTileUrl:function(t){var e=this._map,i=this.options.tileSize,n=t.multiplyBy(i),o=n.add([i,i]),a=this._crs.project(e.unproject(n,t.z)),r=this._crs.project(e.unproject(o,t.z)),l=this._wmsVersion>=1.3&&this._crs===s.CRS.EPSG4326?[r.y,a.x,a.y,r.x].join(","):[a.x,r.y,r.x,a.y].join(","),h=s.Util.template(this._url,{s:this._getSubdomain(t)});return h+s.Util.getParamString(this.wmsParams,h,!0)+"&BBOX="+l},setParams:function(t,e){return s.extend(this.wmsParams,t),e||this.redraw(),this}}),s.tileLayer.wms=function(t,e){return new s.TileLayer.WMS(t,e)},s.TileLayer.Canvas=s.TileLayer.extend({options:{async:!1},initialize:function(t){s.setOptions(this,t)},redraw:function(){this._map&&(this._reset({hard:!0}),this._update());for(var t in this._tiles)this._redrawTile(this._tiles[t]);return this},_redrawTile:function(t){this.drawTile(t,t._tilePoint,this._map._zoom)},_createTile:function(){var t=s.DomUtil.create("canvas","leaflet-tile");return t.width=t.height=this.options.tileSize,t.onselectstart=t.onmousemove=s.Util.falseFn,t},_loadTile:function(t,e){t._layer=this,t._tilePoint=e,this._redrawTile(t),this.options.async||this.tileDrawn(t)},drawTile:function(){},tileDrawn:function(t){this._tileOnLoad.call(t)}}),s.tileLayer.canvas=function(t){return new s.TileLayer.Canvas(t)},s.ImageOverlay=s.Class.extend({includes:s.Mixin.Events,options:{opacity:1},initialize:function(t,e,i){this._url=t,this._bounds=s.latLngBounds(e),s.setOptions(this,i)},onAdd:function(t){this._map=t,this._image||this._initImage(),t._panes.overlayPane.appendChild(this._image),t.on("viewreset",this._reset,this),t.options.zoomAnimation&&s.Browser.any3d&&t.on("zoomanim",this._animateZoom,this),this._reset()},onRemove:function(t){t.getPanes().overlayPane.removeChild(this._image),t.off("viewreset",this._reset,this),t.options.zoomAnimation&&t.off("zoomanim",this._animateZoom,this)},addTo:function(t){return t.addLayer(this),this},setOpacity:function(t){return this.options.opacity=t,this._updateOpacity(),this},bringToFront:function(){return this._image&&this._map._panes.overlayPane.appendChild(this._image),this},bringToBack:function(){var t=this._map._panes.overlayPane;return this._image&&t.insertBefore(this._image,t.firstChild),this},setUrl:function(t){this._url=t,this._image.src=this._url},getAttribution:function(){return this.options.attribution},_initImage:function(){this._image=s.DomUtil.create("img","leaflet-image-layer"),this._map.options.zoomAnimation&&s.Browser.any3d?s.DomUtil.addClass(this._image,"leaflet-zoom-animated"):s.DomUtil.addClass(this._image,"leaflet-zoom-hide"),this._updateOpacity(),s.extend(this._image,{galleryimg:"no",onselectstart:s.Util.falseFn,onmousemove:s.Util.falseFn,onload:s.bind(this._onImageLoad,this),src:this._url})},_animateZoom:function(t){var e=this._map,i=this._image,n=e.getZoomScale(t.zoom),o=this._bounds.getNorthWest(),a=this._bounds.getSouthEast(),r=e._latLngToNewLayerPoint(o,t.zoom,t.center),l=e._latLngToNewLayerPoint(a,t.zoom,t.center)._subtract(r),h=r._add(l._multiplyBy(.5*(1-1/n)));i.style[s.DomUtil.TRANSFORM]=s.DomUtil.getTranslateString(h)+" scale("+n+") "},_reset:function(){var t=this._image,e=this._map.latLngToLayerPoint(this._bounds.getNorthWest()),i=this._map.latLngToLayerPoint(this._bounds.getSouthEast())._subtract(e);s.DomUtil.setPosition(t,e),t.style.width=i.x+"px",t.style.height=i.y+"px"},_onImageLoad:function(){this.fire("load")},_updateOpacity:function(){s.DomUtil.setOpacity(this._image,this.options.opacity)}}),s.imageOverlay=function(t,e,i){return new s.ImageOverlay(t,e,i)},s.Icon=s.Class.extend({options:{className:""},initialize:function(t){s.setOptions(this,t)},createIcon:function(t){return this._createIcon("icon",t)},createShadow:function(t){return this._createIcon("shadow",t)},_createIcon:function(t,e){var i=this._getIconUrl(t);if(!i){if("icon"===t)throw new Error("iconUrl not set in Icon options (see the docs).");return null}var n;return n=e&&"IMG"===e.tagName?this._createImg(i,e):this._createImg(i),this._setIconStyles(n,t),n},_setIconStyles:function(t,e){var i,n=this.options,o=s.point(n[e+"Size"]);i="shadow"===e?s.point(n.shadowAnchor||n.iconAnchor):s.point(n.iconAnchor),!i&&o&&(i=o.divideBy(2,!0)),t.className="leaflet-marker-"+e+" "+n.className,i&&(t.style.marginLeft=-i.x+"px",t.style.marginTop=-i.y+"px"),o&&(t.style.width=o.x+"px",t.style.height=o.y+"px")},_createImg:function(t,e){return e=e||i.createElement("img"),e.src=t,e},_getIconUrl:function(t){return s.Browser.retina&&this.options[t+"RetinaUrl"]?this.options[t+"RetinaUrl"]:this.options[t+"Url"]}}),s.icon=function(t){return new s.Icon(t)},s.Icon.Default=s.Icon.extend({options:{iconSize:[25,41],iconAnchor:[12,41],popupAnchor:[1,-34],shadowSize:[41,41]},_getIconUrl:function(t){var e=t+"Url";if(this.options[e])return this.options[e];s.Browser.retina&&"icon"===t&&(t+="-2x");var i=s.Icon.Default.imagePath;if(!i)throw new Error("Couldn't autodetect L.Icon.Default.imagePath, set it manually.");return i+"/marker-"+t+".png"}}),s.Icon.Default.imagePath=function(){var t,e,n,o,s,a=i.getElementsByTagName("script"),r=/[\/^]leaflet[\-\._]?([\w\-\._]*)\.js\??/;for(t=0,e=a.length;e>t;t++)if(n=a[t].src,o=n.match(r))return s=n.split(r)[0],(s?s+"/":"")+"images"}(),s.Marker=s.Class.extend({includes:s.Mixin.Events,options:{icon:new s.Icon.Default,title:"",alt:"",clickable:!0,draggable:!1,keyboard:!0,zIndexOffset:0,opacity:1,riseOnHover:!1,riseOffset:250},initialize:function(t,e){s.setOptions(this,e),this._latlng=s.latLng(t)},onAdd:function(t){this._map=t,t.on("viewreset",this.update,this),this._initIcon(),this.update(),this.fire("add"),t.options.zoomAnimation&&t.options.markerZoomAnimation&&t.on("zoomanim",this._animateZoom,this)},addTo:function(t){return t.addLayer(this),this},onRemove:function(t){this.dragging&&this.dragging.disable(),this._removeIcon(),this._removeShadow(),this.fire("remove"),t.off({viewreset:this.update,zoomanim:this._animateZoom},this),this._map=null},getLatLng:function(){return this._latlng},setLatLng:function(t){return this._latlng=s.latLng(t),this.update(),this.fire("move",{latlng:this._latlng})},setZIndexOffset:function(t){return this.options.zIndexOffset=t,this.update(),this},setIcon:function(t){return this.options.icon=t,this._map&&(this._initIcon(),this.update()),this._popup&&this.bindPopup(this._popup),this},update:function(){if(this._icon){var t=this._map.latLngToLayerPoint(this._latlng).round();this._setPos(t)}return this},_initIcon:function(){var t=this.options,e=this._map,i=e.options.zoomAnimation&&e.options.markerZoomAnimation,n=i?"leaflet-zoom-animated":"leaflet-zoom-hide",o=t.icon.createIcon(this._icon),a=!1;o!==this._icon&&(this._icon&&this._removeIcon(),a=!0,t.title&&(o.title=t.title),t.alt&&(o.alt=t.alt)),s.DomUtil.addClass(o,n),t.keyboard&&(o.tabIndex="0"),this._icon=o,this._initInteraction(),t.riseOnHover&&s.DomEvent.on(o,"mouseover",this._bringToFront,this).on(o,"mouseout",this._resetZIndex,this);var r=t.icon.createShadow(this._shadow),l=!1;r!==this._shadow&&(this._removeShadow(),l=!0),r&&s.DomUtil.addClass(r,n),this._shadow=r,t.opacity<1&&this._updateOpacity();var h=this._map._panes;a&&h.markerPane.appendChild(this._icon),r&&l&&h.shadowPane.appendChild(this._shadow)},_removeIcon:function(){this.options.riseOnHover&&s.DomEvent.off(this._icon,"mouseover",this._bringToFront).off(this._icon,"mouseout",this._resetZIndex),this._map._panes.markerPane.removeChild(this._icon),this._icon=null},_removeShadow:function(){this._shadow&&this._map._panes.shadowPane.removeChild(this._shadow),this._shadow=null},_setPos:function(t){s.DomUtil.setPosition(this._icon,t),this._shadow&&s.DomUtil.setPosition(this._shadow,t),this._zIndex=t.y+this.options.zIndexOffset,this._resetZIndex()},_updateZIndex:function(t){this._icon.style.zIndex=this._zIndex+t},_animateZoom:function(t){var e=this._map._latLngToNewLayerPoint(this._latlng,t.zoom,t.center).round();this._setPos(e)},_initInteraction:function(){if(this.options.clickable){var t=this._icon,e=["dblclick","mousedown","mouseover","mouseout","contextmenu"];s.DomUtil.addClass(t,"leaflet-clickable"),s.DomEvent.on(t,"click",this._onMouseClick,this),s.DomEvent.on(t,"keypress",this._onKeyPress,this);for(var i=0;i<e.length;i++)s.DomEvent.on(t,e[i],this._fireMouseEvent,this);s.Handler.MarkerDrag&&(this.dragging=new s.Handler.MarkerDrag(this),this.options.draggable&&this.dragging.enable())}},_onMouseClick:function(t){var e=this.dragging&&this.dragging.moved();(this.hasEventListeners(t.type)||e)&&s.DomEvent.stopPropagation(t),e||(this.dragging&&this.dragging._enabled||!this._map.dragging||!this._map.dragging.moved())&&this.fire(t.type,{originalEvent:t,latlng:this._latlng})},_onKeyPress:function(t){13===t.keyCode&&this.fire("click",{originalEvent:t,latlng:this._latlng})},_fireMouseEvent:function(t){this.fire(t.type,{originalEvent:t,latlng:this._latlng}),"contextmenu"===t.type&&this.hasEventListeners(t.type)&&s.DomEvent.preventDefault(t),"mousedown"!==t.type?s.DomEvent.stopPropagation(t):s.DomEvent.preventDefault(t)},setOpacity:function(t){return this.options.opacity=t,this._map&&this._updateOpacity(),this},_updateOpacity:function(){s.DomUtil.setOpacity(this._icon,this.options.opacity),this._shadow&&s.DomUtil.setOpacity(this._shadow,this.options.opacity)},_bringToFront:function(){this._updateZIndex(this.options.riseOffset)},_resetZIndex:function(){this._updateZIndex(0)}}),s.marker=function(t,e){return new s.Marker(t,e)},s.DivIcon=s.Icon.extend({options:{iconSize:[12,12],className:"leaflet-div-icon",html:!1},createIcon:function(t){var e=t&&"DIV"===t.tagName?t:i.createElement("div"),n=this.options;return e.innerHTML=n.html!==!1?n.html:"",n.bgPos&&(e.style.backgroundPosition=-n.bgPos.x+"px "+-n.bgPos.y+"px"),this._setIconStyles(e,"icon"),e},createShadow:function(){return null}}),s.divIcon=function(t){return new s.DivIcon(t)},s.Map.mergeOptions({closePopupOnClick:!0}),s.Popup=s.Class.extend({includes:s.Mixin.Events,options:{minWidth:50,maxWidth:300,autoPan:!0,closeButton:!0,offset:[0,7],autoPanPadding:[5,5],keepInView:!1,className:"",zoomAnimation:!0},initialize:function(t,e){s.setOptions(this,t),this._source=e,this._animated=s.Browser.any3d&&this.options.zoomAnimation,this._isOpen=!1},onAdd:function(t){this._map=t,this._container||this._initLayout();var e=t.options.fadeAnimation;e&&s.DomUtil.setOpacity(this._container,0),t._panes.popupPane.appendChild(this._container),t.on(this._getEvents(),this),this.update(),e&&s.DomUtil.setOpacity(this._container,1),this.fire("open"),t.fire("popupopen",{popup:this}),this._source&&this._source.fire("popupopen",{popup:this})},addTo:function(t){return t.addLayer(this),this},openOn:function(t){return t.openPopup(this),this},onRemove:function(t){t._panes.popupPane.removeChild(this._container),s.Util.falseFn(this._container.offsetWidth),t.off(this._getEvents(),this),t.options.fadeAnimation&&s.DomUtil.setOpacity(this._container,0),this._map=null,this.fire("close"),t.fire("popupclose",{popup:this}),this._source&&this._source.fire("popupclose",{popup:this})},getLatLng:function(){return this._latlng},setLatLng:function(t){return this._latlng=s.latLng(t),this._map&&(this._updatePosition(),this._adjustPan()),this},getContent:function(){return this._content},setContent:function(t){return this._content=t,this.update(),this},update:function(){this._map&&(this._container.style.visibility="hidden",this._updateContent(),this._updateLayout(),this._updatePosition(),this._container.style.visibility="",this._adjustPan())},_getEvents:function(){var t={viewreset:this._updatePosition};return this._animated&&(t.zoomanim=this._zoomAnimation),("closeOnClick"in this.options?this.options.closeOnClick:this._map.options.closePopupOnClick)&&(t.preclick=this._close),this.options.keepInView&&(t.moveend=this._adjustPan),t},_close:function(){this._map&&this._map.closePopup(this)},_initLayout:function(){var t,e="leaflet-popup",i=e+" "+this.options.className+" leaflet-zoom-"+(this._animated?"animated":"hide"),n=this._container=s.DomUtil.create("div",i);this.options.closeButton&&(t=this._closeButton=s.DomUtil.create("a",e+"-close-button",n),t.href="#close",t.innerHTML="&#215;",s.DomEvent.disableClickPropagation(t),s.DomEvent.on(t,"click",this._onCloseButtonClick,this));var o=this._wrapper=s.DomUtil.create("div",e+"-content-wrapper",n);s.DomEvent.disableClickPropagation(o),this._contentNode=s.DomUtil.create("div",e+"-content",o),s.DomEvent.disableScrollPropagation(this._contentNode),s.DomEvent.on(o,"contextmenu",s.DomEvent.stopPropagation),this._tipContainer=s.DomUtil.create("div",e+"-tip-container",n),this._tip=s.DomUtil.create("div",e+"-tip",this._tipContainer)},_updateContent:function(){if(this._content){if("string"==typeof this._content)this._contentNode.innerHTML=this._content;else{for(;this._contentNode.hasChildNodes();)this._contentNode.removeChild(this._contentNode.firstChild);this._contentNode.appendChild(this._content)}this.fire("contentupdate")}},_updateLayout:function(){var t=this._contentNode,e=t.style;e.width="",e.whiteSpace="nowrap";var i=t.offsetWidth;i=Math.min(i,this.options.maxWidth),i=Math.max(i,this.options.minWidth),e.width=i+1+"px",e.whiteSpace="",e.height="";var n=t.offsetHeight,o=this.options.maxHeight,a="leaflet-popup-scrolled";o&&n>o?(e.height=o+"px",s.DomUtil.addClass(t,a)):s.DomUtil.removeClass(t,a),this._containerWidth=this._container.offsetWidth},_updatePosition:function(){if(this._map){var t=this._map.latLngToLayerPoint(this._latlng),e=this._animated,i=s.point(this.options.offset);e&&s.DomUtil.setPosition(this._container,t),this._containerBottom=-i.y-(e?0:t.y),this._containerLeft=-Math.round(this._containerWidth/2)+i.x+(e?0:t.x),this._container.style.bottom=this._containerBottom+"px",this._container.style.left=this._containerLeft+"px"}},_zoomAnimation:function(t){var e=this._map._latLngToNewLayerPoint(this._latlng,t.zoom,t.center);s.DomUtil.setPosition(this._container,e)},_adjustPan:function(){if(this.options.autoPan){var t=this._map,e=this._container.offsetHeight,i=this._containerWidth,n=new s.Point(this._containerLeft,-e-this._containerBottom);this._animated&&n._add(s.DomUtil.getPosition(this._container));var o=t.layerPointToContainerPoint(n),a=s.point(this.options.autoPanPadding),r=s.point(this.options.autoPanPaddingTopLeft||a),l=s.point(this.options.autoPanPaddingBottomRight||a),h=t.getSize(),u=0,c=0;o.x+i+l.x>h.x&&(u=o.x+i-h.x+l.x),o.x-u-r.x<0&&(u=o.x-r.x),o.y+e+l.y>h.y&&(c=o.y+e-h.y+l.y),o.y-c-r.y<0&&(c=o.y-r.y),(u||c)&&t.fire("autopanstart").panBy([u,c])}},_onCloseButtonClick:function(t){this._close(),s.DomEvent.stop(t)}}),s.popup=function(t,e){return new s.Popup(t,e)},s.Map.include({openPopup:function(t,e,i){if(this.closePopup(),!(t instanceof s.Popup)){var n=t;t=new s.Popup(i).setLatLng(e).setContent(n)}return t._isOpen=!0,this._popup=t,this.addLayer(t)},closePopup:function(t){return t&&t!==this._popup||(t=this._popup,this._popup=null),t&&(this.removeLayer(t),t._isOpen=!1),this}}),s.Marker.include({openPopup:function(){return this._popup&&this._map&&!this._map.hasLayer(this._popup)&&(this._popup.setLatLng(this._latlng),this._map.openPopup(this._popup)),this},closePopup:function(){return this._popup&&this._popup._close(),this},togglePopup:function(){return this._popup&&(this._popup._isOpen?this.closePopup():this.openPopup()),this},bindPopup:function(t,e){var i=s.point(this.options.icon.options.popupAnchor||[0,0]);return i=i.add(s.Popup.prototype.options.offset),e&&e.offset&&(i=i.add(e.offset)),e=s.extend({offset:i},e),this._popupHandlersAdded||(this.on("click",this.togglePopup,this).on("remove",this.closePopup,this).on("move",this._movePopup,this),this._popupHandlersAdded=!0),t instanceof s.Popup?(s.setOptions(t,e),this._popup=t):this._popup=new s.Popup(e,this).setContent(t),this},setPopupContent:function(t){return this._popup&&this._popup.setContent(t),this},unbindPopup:function(){return this._popup&&(this._popup=null,this.off("click",this.togglePopup,this).off("remove",this.closePopup,this).off("move",this._movePopup,this),this._popupHandlersAdded=!1),this},getPopup:function(){return this._popup},_movePopup:function(t){this._popup.setLatLng(t.latlng)}}),s.LayerGroup=s.Class.extend({initialize:function(t){this._layers={};var e,i;if(t)for(e=0,i=t.length;i>e;e++)this.addLayer(t[e])},addLayer:function(t){var e=this.getLayerId(t);return this._layers[e]=t,this._map&&this._map.addLayer(t),this},removeLayer:function(t){var e=t in this._layers?t:this.getLayerId(t);return this._map&&this._layers[e]&&this._map.removeLayer(this._layers[e]),delete this._layers[e],this},hasLayer:function(t){return t?t in this._layers||this.getLayerId(t)in this._layers:!1},clearLayers:function(){return this.eachLayer(this.removeLayer,this),this},invoke:function(t){var e,i,n=Array.prototype.slice.call(arguments,1);for(e in this._layers)i=this._layers[e],i[t]&&i[t].apply(i,n);return this},onAdd:function(t){this._map=t,this.eachLayer(t.addLayer,t)},onRemove:function(t){this.eachLayer(t.removeLayer,t),this._map=null},addTo:function(t){return t.addLayer(this),this},eachLayer:function(t,e){for(var i in this._layers)t.call(e,this._layers[i]);return this},getLayer:function(t){return this._layers[t]},getLayers:function(){var t=[];for(var e in this._layers)t.push(this._layers[e]);return t},setZIndex:function(t){return this.invoke("setZIndex",t)},getLayerId:function(t){return s.stamp(t)}}),s.layerGroup=function(t){return new s.LayerGroup(t)},s.FeatureGroup=s.LayerGroup.extend({includes:s.Mixin.Events,statics:{EVENTS:"click dblclick mouseover mouseout mousemove contextmenu popupopen popupclose"},addLayer:function(t){return this.hasLayer(t)?this:("on"in t&&t.on(s.FeatureGroup.EVENTS,this._propagateEvent,this),s.LayerGroup.prototype.addLayer.call(this,t),this._popupContent&&t.bindPopup&&t.bindPopup(this._popupContent,this._popupOptions),this.fire("layeradd",{layer:t}))},removeLayer:function(t){return this.hasLayer(t)?(t in this._layers&&(t=this._layers[t]),t.off(s.FeatureGroup.EVENTS,this._propagateEvent,this),s.LayerGroup.prototype.removeLayer.call(this,t),this._popupContent&&this.invoke("unbindPopup"),this.fire("layerremove",{layer:t})):this},bindPopup:function(t,e){return this._popupContent=t,this._popupOptions=e,this.invoke("bindPopup",t,e)},openPopup:function(t){for(var e in this._layers){this._layers[e].openPopup(t);break}return this},setStyle:function(t){return this.invoke("setStyle",t)},bringToFront:function(){return this.invoke("bringToFront")},bringToBack:function(){return this.invoke("bringToBack")},getBounds:function(){var t=new s.LatLngBounds;return this.eachLayer(function(e){t.extend(e instanceof s.Marker?e.getLatLng():e.getBounds())}),t},_propagateEvent:function(t){t=s.extend({layer:t.target,target:this},t),this.fire(t.type,t)}}),s.featureGroup=function(t){return new s.FeatureGroup(t)},s.Path=s.Class.extend({includes:[s.Mixin.Events],statics:{CLIP_PADDING:function(){var e=s.Browser.mobile?1280:2e3,i=(e/Math.max(t.outerWidth,t.outerHeight)-1)/2;return Math.max(0,Math.min(.5,i))}()},options:{stroke:!0,color:"#0033ff",dashArray:null,lineCap:null,lineJoin:null,weight:5,opacity:.5,fill:!1,fillColor:null,fillOpacity:.2,clickable:!0},initialize:function(t){s.setOptions(this,t)},onAdd:function(t){this._map=t,this._container||(this._initElements(),this._initEvents()),this.projectLatlngs(),this._updatePath(),this._container&&this._map._pathRoot.appendChild(this._container),this.fire("add"),t.on({viewreset:this.projectLatlngs,moveend:this._updatePath},this)},addTo:function(t){return t.addLayer(this),this},onRemove:function(t){t._pathRoot.removeChild(this._container),this.fire("remove"),this._map=null,s.Browser.vml&&(this._container=null,this._stroke=null,this._fill=null),t.off({viewreset:this.projectLatlngs,moveend:this._updatePath},this)},projectLatlngs:function(){},setStyle:function(t){return s.setOptions(this,t),this._container&&this._updateStyle(),this},redraw:function(){return this._map&&(this.projectLatlngs(),this._updatePath()),this}}),s.Map.include({_updatePathViewport:function(){var t=s.Path.CLIP_PADDING,e=this.getSize(),i=s.DomUtil.getPosition(this._mapPane),n=i.multiplyBy(-1)._subtract(e.multiplyBy(t)._round()),o=n.add(e.multiplyBy(1+2*t)._round());this._pathViewport=new s.Bounds(n,o)}}),s.Path.SVG_NS="http://www.w3.org/2000/svg",s.Browser.svg=!(!i.createElementNS||!i.createElementNS(s.Path.SVG_NS,"svg").createSVGRect),s.Path=s.Path.extend({statics:{SVG:s.Browser.svg},bringToFront:function(){var t=this._map._pathRoot,e=this._container;return e&&t.lastChild!==e&&t.appendChild(e),this},bringToBack:function(){var t=this._map._pathRoot,e=this._container,i=t.firstChild;return e&&i!==e&&t.insertBefore(e,i),this},getPathString:function(){},_createElement:function(t){return i.createElementNS(s.Path.SVG_NS,t)},_initElements:function(){this._map._initPathRoot(),this._initPath(),this._initStyle()},_initPath:function(){this._container=this._createElement("g"),this._path=this._createElement("path"),this.options.className&&s.DomUtil.addClass(this._path,this.options.className),this._container.appendChild(this._path)},_initStyle:function(){this.options.stroke&&(this._path.setAttribute("stroke-linejoin","round"),this._path.setAttribute("stroke-linecap","round")),this.options.fill&&this._path.setAttribute("fill-rule","evenodd"),this.options.pointerEvents&&this._path.setAttribute("pointer-events",this.options.pointerEvents),this.options.clickable||this.options.pointerEvents||this._path.setAttribute("pointer-events","none"),this._updateStyle()},_updateStyle:function(){this.options.stroke?(this._path.setAttribute("stroke",this.options.color),this._path.setAttribute("stroke-opacity",this.options.opacity),this._path.setAttribute("stroke-width",this.options.weight),this.options.dashArray?this._path.setAttribute("stroke-dasharray",this.options.dashArray):this._path.removeAttribute("stroke-dasharray"),this.options.lineCap&&this._path.setAttribute("stroke-linecap",this.options.lineCap),this.options.lineJoin&&this._path.setAttribute("stroke-linejoin",this.options.lineJoin)):this._path.setAttribute("stroke","none"),this.options.fill?(this._path.setAttribute("fill",this.options.fillColor||this.options.color),this._path.setAttribute("fill-opacity",this.options.fillOpacity)):this._path.setAttribute("fill","none")
  },_updatePath:function(){var t=this.getPathString();t||(t="M0 0"),this._path.setAttribute("d",t)},_initEvents:function(){if(this.options.clickable){(s.Browser.svg||!s.Browser.vml)&&s.DomUtil.addClass(this._path,"leaflet-clickable"),s.DomEvent.on(this._container,"click",this._onMouseClick,this);for(var t=["dblclick","mousedown","mouseover","mouseout","mousemove","contextmenu"],e=0;e<t.length;e++)s.DomEvent.on(this._container,t[e],this._fireMouseEvent,this)}},_onMouseClick:function(t){this._map.dragging&&this._map.dragging.moved()||this._fireMouseEvent(t)},_fireMouseEvent:function(t){if(this.hasEventListeners(t.type)){var e=this._map,i=e.mouseEventToContainerPoint(t),n=e.containerPointToLayerPoint(i),o=e.layerPointToLatLng(n);this.fire(t.type,{latlng:o,layerPoint:n,containerPoint:i,originalEvent:t}),"contextmenu"===t.type&&s.DomEvent.preventDefault(t),"mousemove"!==t.type&&s.DomEvent.stopPropagation(t)}}}),s.Map.include({_initPathRoot:function(){this._pathRoot||(this._pathRoot=s.Path.prototype._createElement("svg"),this._panes.overlayPane.appendChild(this._pathRoot),this.options.zoomAnimation&&s.Browser.any3d?(s.DomUtil.addClass(this._pathRoot,"leaflet-zoom-animated"),this.on({zoomanim:this._animatePathZoom,zoomend:this._endPathZoom})):s.DomUtil.addClass(this._pathRoot,"leaflet-zoom-hide"),this.on("moveend",this._updateSvgViewport),this._updateSvgViewport())},_animatePathZoom:function(t){var e=this.getZoomScale(t.zoom),i=this._getCenterOffset(t.center)._multiplyBy(-e)._add(this._pathViewport.min);this._pathRoot.style[s.DomUtil.TRANSFORM]=s.DomUtil.getTranslateString(i)+" scale("+e+") ",this._pathZooming=!0},_endPathZoom:function(){this._pathZooming=!1},_updateSvgViewport:function(){if(!this._pathZooming){this._updatePathViewport();var t=this._pathViewport,e=t.min,i=t.max,n=i.x-e.x,o=i.y-e.y,a=this._pathRoot,r=this._panes.overlayPane;s.Browser.mobileWebkit&&r.removeChild(a),s.DomUtil.setPosition(a,e),a.setAttribute("width",n),a.setAttribute("height",o),a.setAttribute("viewBox",[e.x,e.y,n,o].join(" ")),s.Browser.mobileWebkit&&r.appendChild(a)}}}),s.Path.include({bindPopup:function(t,e){return t instanceof s.Popup?this._popup=t:((!this._popup||e)&&(this._popup=new s.Popup(e,this)),this._popup.setContent(t)),this._popupHandlersAdded||(this.on("click",this._openPopup,this).on("remove",this.closePopup,this),this._popupHandlersAdded=!0),this},unbindPopup:function(){return this._popup&&(this._popup=null,this.off("click",this._openPopup).off("remove",this.closePopup),this._popupHandlersAdded=!1),this},openPopup:function(t){return this._popup&&(t=t||this._latlng||this._latlngs[Math.floor(this._latlngs.length/2)],this._openPopup({latlng:t})),this},closePopup:function(){return this._popup&&this._popup._close(),this},_openPopup:function(t){this._popup.setLatLng(t.latlng),this._map.openPopup(this._popup)}}),s.Browser.vml=!s.Browser.svg&&function(){try{var t=i.createElement("div");t.innerHTML='<v:shape adj="1"/>';var e=t.firstChild;return e.style.behavior="url(#default#VML)",e&&"object"==typeof e.adj}catch(n){return!1}}(),s.Path=s.Browser.svg||!s.Browser.vml?s.Path:s.Path.extend({statics:{VML:!0,CLIP_PADDING:.02},_createElement:function(){try{return i.namespaces.add("lvml","urn:schemas-microsoft-com:vml"),function(t){return i.createElement("<lvml:"+t+' class="lvml">')}}catch(t){return function(t){return i.createElement("<"+t+' xmlns="urn:schemas-microsoft.com:vml" class="lvml">')}}}(),_initPath:function(){var t=this._container=this._createElement("shape");s.DomUtil.addClass(t,"leaflet-vml-shape"+(this.options.className?" "+this.options.className:"")),this.options.clickable&&s.DomUtil.addClass(t,"leaflet-clickable"),t.coordsize="1 1",this._path=this._createElement("path"),t.appendChild(this._path),this._map._pathRoot.appendChild(t)},_initStyle:function(){this._updateStyle()},_updateStyle:function(){var t=this._stroke,e=this._fill,i=this.options,n=this._container;n.stroked=i.stroke,n.filled=i.fill,i.stroke?(t||(t=this._stroke=this._createElement("stroke"),t.endcap="round",n.appendChild(t)),t.weight=i.weight+"px",t.color=i.color,t.opacity=i.opacity,t.dashStyle=i.dashArray?s.Util.isArray(i.dashArray)?i.dashArray.join(" "):i.dashArray.replace(/( *, *)/g," "):"",i.lineCap&&(t.endcap=i.lineCap.replace("butt","flat")),i.lineJoin&&(t.joinstyle=i.lineJoin)):t&&(n.removeChild(t),this._stroke=null),i.fill?(e||(e=this._fill=this._createElement("fill"),n.appendChild(e)),e.color=i.fillColor||i.color,e.opacity=i.fillOpacity):e&&(n.removeChild(e),this._fill=null)},_updatePath:function(){var t=this._container.style;t.display="none",this._path.v=this.getPathString()+" ",t.display=""}}),s.Map.include(s.Browser.svg||!s.Browser.vml?{}:{_initPathRoot:function(){if(!this._pathRoot){var t=this._pathRoot=i.createElement("div");t.className="leaflet-vml-container",this._panes.overlayPane.appendChild(t),this.on("moveend",this._updatePathViewport),this._updatePathViewport()}}}),s.Browser.canvas=function(){return!!i.createElement("canvas").getContext}(),s.Path=s.Path.SVG&&!t.L_PREFER_CANVAS||!s.Browser.canvas?s.Path:s.Path.extend({statics:{CANVAS:!0,SVG:!1},redraw:function(){return this._map&&(this.projectLatlngs(),this._requestUpdate()),this},setStyle:function(t){return s.setOptions(this,t),this._map&&(this._updateStyle(),this._requestUpdate()),this},onRemove:function(t){t.off("viewreset",this.projectLatlngs,this).off("moveend",this._updatePath,this),this.options.clickable&&(this._map.off("click",this._onClick,this),this._map.off("mousemove",this._onMouseMove,this)),this._requestUpdate(),this.fire("remove"),this._map=null},_requestUpdate:function(){this._map&&!s.Path._updateRequest&&(s.Path._updateRequest=s.Util.requestAnimFrame(this._fireMapMoveEnd,this._map))},_fireMapMoveEnd:function(){s.Path._updateRequest=null,this.fire("moveend")},_initElements:function(){this._map._initPathRoot(),this._ctx=this._map._canvasCtx},_updateStyle:function(){var t=this.options;t.stroke&&(this._ctx.lineWidth=t.weight,this._ctx.strokeStyle=t.color),t.fill&&(this._ctx.fillStyle=t.fillColor||t.color)},_drawPath:function(){var t,e,i,n,o,a;for(this._ctx.beginPath(),t=0,i=this._parts.length;i>t;t++){for(e=0,n=this._parts[t].length;n>e;e++)o=this._parts[t][e],a=(0===e?"move":"line")+"To",this._ctx[a](o.x,o.y);this instanceof s.Polygon&&this._ctx.closePath()}},_checkIfEmpty:function(){return!this._parts.length},_updatePath:function(){if(!this._checkIfEmpty()){var t=this._ctx,e=this.options;this._drawPath(),t.save(),this._updateStyle(),e.fill&&(t.globalAlpha=e.fillOpacity,t.fill()),e.stroke&&(t.globalAlpha=e.opacity,t.stroke()),t.restore()}},_initEvents:function(){this.options.clickable&&(this._map.on("mousemove",this._onMouseMove,this),this._map.on("click",this._onClick,this))},_onClick:function(t){this._containsPoint(t.layerPoint)&&this.fire("click",t)},_onMouseMove:function(t){this._map&&!this._map._animatingZoom&&(this._containsPoint(t.layerPoint)?(this._ctx.canvas.style.cursor="pointer",this._mouseInside=!0,this.fire("mouseover",t)):this._mouseInside&&(this._ctx.canvas.style.cursor="",this._mouseInside=!1,this.fire("mouseout",t)))}}),s.Map.include(s.Path.SVG&&!t.L_PREFER_CANVAS||!s.Browser.canvas?{}:{_initPathRoot:function(){var t,e=this._pathRoot;e||(e=this._pathRoot=i.createElement("canvas"),e.style.position="absolute",t=this._canvasCtx=e.getContext("2d"),t.lineCap="round",t.lineJoin="round",this._panes.overlayPane.appendChild(e),this.options.zoomAnimation&&(this._pathRoot.className="leaflet-zoom-animated",this.on("zoomanim",this._animatePathZoom),this.on("zoomend",this._endPathZoom)),this.on("moveend",this._updateCanvasViewport),this._updateCanvasViewport())},_updateCanvasViewport:function(){if(!this._pathZooming){this._updatePathViewport();var t=this._pathViewport,e=t.min,i=t.max.subtract(e),n=this._pathRoot;s.DomUtil.setPosition(n,e),n.width=i.x,n.height=i.y,n.getContext("2d").translate(-e.x,-e.y)}}}),s.LineUtil={simplify:function(t,e){if(!e||!t.length)return t.slice();var i=e*e;return t=this._reducePoints(t,i),t=this._simplifyDP(t,i)},pointToSegmentDistance:function(t,e,i){return Math.sqrt(this._sqClosestPointOnSegment(t,e,i,!0))},closestPointOnSegment:function(t,e,i){return this._sqClosestPointOnSegment(t,e,i)},_simplifyDP:function(t,e){var i=t.length,o=typeof Uint8Array!=n+""?Uint8Array:Array,s=new o(i);s[0]=s[i-1]=1,this._simplifyDPStep(t,s,e,0,i-1);var a,r=[];for(a=0;i>a;a++)s[a]&&r.push(t[a]);return r},_simplifyDPStep:function(t,e,i,n,o){var s,a,r,l=0;for(a=n+1;o-1>=a;a++)r=this._sqClosestPointOnSegment(t[a],t[n],t[o],!0),r>l&&(s=a,l=r);l>i&&(e[s]=1,this._simplifyDPStep(t,e,i,n,s),this._simplifyDPStep(t,e,i,s,o))},_reducePoints:function(t,e){for(var i=[t[0]],n=1,o=0,s=t.length;s>n;n++)this._sqDist(t[n],t[o])>e&&(i.push(t[n]),o=n);return s-1>o&&i.push(t[s-1]),i},clipSegment:function(t,e,i,n){var o,s,a,r=n?this._lastCode:this._getBitCode(t,i),l=this._getBitCode(e,i);for(this._lastCode=l;;){if(!(r|l))return[t,e];if(r&l)return!1;o=r||l,s=this._getEdgeIntersection(t,e,o,i),a=this._getBitCode(s,i),o===r?(t=s,r=a):(e=s,l=a)}},_getEdgeIntersection:function(t,e,i,n){var o=e.x-t.x,a=e.y-t.y,r=n.min,l=n.max;return 8&i?new s.Point(t.x+o*(l.y-t.y)/a,l.y):4&i?new s.Point(t.x+o*(r.y-t.y)/a,r.y):2&i?new s.Point(l.x,t.y+a*(l.x-t.x)/o):1&i?new s.Point(r.x,t.y+a*(r.x-t.x)/o):void 0},_getBitCode:function(t,e){var i=0;return t.x<e.min.x?i|=1:t.x>e.max.x&&(i|=2),t.y<e.min.y?i|=4:t.y>e.max.y&&(i|=8),i},_sqDist:function(t,e){var i=e.x-t.x,n=e.y-t.y;return i*i+n*n},_sqClosestPointOnSegment:function(t,e,i,n){var o,a=e.x,r=e.y,l=i.x-a,h=i.y-r,u=l*l+h*h;return u>0&&(o=((t.x-a)*l+(t.y-r)*h)/u,o>1?(a=i.x,r=i.y):o>0&&(a+=l*o,r+=h*o)),l=t.x-a,h=t.y-r,n?l*l+h*h:new s.Point(a,r)}},s.Polyline=s.Path.extend({initialize:function(t,e){s.Path.prototype.initialize.call(this,e),this._latlngs=this._convertLatLngs(t)},options:{smoothFactor:1,noClip:!1},projectLatlngs:function(){this._originalPoints=[];for(var t=0,e=this._latlngs.length;e>t;t++)this._originalPoints[t]=this._map.latLngToLayerPoint(this._latlngs[t])},getPathString:function(){for(var t=0,e=this._parts.length,i="";e>t;t++)i+=this._getPathPartStr(this._parts[t]);return i},getLatLngs:function(){return this._latlngs},setLatLngs:function(t){return this._latlngs=this._convertLatLngs(t),this.redraw()},addLatLng:function(t){return this._latlngs.push(s.latLng(t)),this.redraw()},spliceLatLngs:function(){var t=[].splice.apply(this._latlngs,arguments);return this._convertLatLngs(this._latlngs,!0),this.redraw(),t},closestLayerPoint:function(t){for(var e,i,n=1/0,o=this._parts,a=null,r=0,l=o.length;l>r;r++)for(var h=o[r],u=1,c=h.length;c>u;u++){e=h[u-1],i=h[u];var p=s.LineUtil._sqClosestPointOnSegment(t,e,i,!0);n>p&&(n=p,a=s.LineUtil._sqClosestPointOnSegment(t,e,i))}return a&&(a.distance=Math.sqrt(n)),a},getBounds:function(){return new s.LatLngBounds(this.getLatLngs())},_convertLatLngs:function(t,e){var i,n,o=e?t:[];for(i=0,n=t.length;n>i;i++){if(s.Util.isArray(t[i])&&"number"!=typeof t[i][0])return;o[i]=s.latLng(t[i])}return o},_initEvents:function(){s.Path.prototype._initEvents.call(this)},_getPathPartStr:function(t){for(var e,i=s.Path.VML,n=0,o=t.length,a="";o>n;n++)e=t[n],i&&e._round(),a+=(n?"L":"M")+e.x+" "+e.y;return a},_clipPoints:function(){var t,e,i,n=this._originalPoints,o=n.length;if(this.options.noClip)return this._parts=[n],void 0;this._parts=[];var a=this._parts,r=this._map._pathViewport,l=s.LineUtil;for(t=0,e=0;o-1>t;t++)i=l.clipSegment(n[t],n[t+1],r,t),i&&(a[e]=a[e]||[],a[e].push(i[0]),(i[1]!==n[t+1]||t===o-2)&&(a[e].push(i[1]),e++))},_simplifyPoints:function(){for(var t=this._parts,e=s.LineUtil,i=0,n=t.length;n>i;i++)t[i]=e.simplify(t[i],this.options.smoothFactor)},_updatePath:function(){this._map&&(this._clipPoints(),this._simplifyPoints(),s.Path.prototype._updatePath.call(this))}}),s.polyline=function(t,e){return new s.Polyline(t,e)},s.PolyUtil={},s.PolyUtil.clipPolygon=function(t,e){var i,n,o,a,r,l,h,u,c,p=[1,4,2,8],d=s.LineUtil;for(n=0,h=t.length;h>n;n++)t[n]._code=d._getBitCode(t[n],e);for(a=0;4>a;a++){for(u=p[a],i=[],n=0,h=t.length,o=h-1;h>n;o=n++)r=t[n],l=t[o],r._code&u?l._code&u||(c=d._getEdgeIntersection(l,r,u,e),c._code=d._getBitCode(c,e),i.push(c)):(l._code&u&&(c=d._getEdgeIntersection(l,r,u,e),c._code=d._getBitCode(c,e),i.push(c)),i.push(r));t=i}return t},s.Polygon=s.Polyline.extend({options:{fill:!0},initialize:function(t,e){s.Polyline.prototype.initialize.call(this,t,e),this._initWithHoles(t)},_initWithHoles:function(t){var e,i,n;if(t&&s.Util.isArray(t[0])&&"number"!=typeof t[0][0])for(this._latlngs=this._convertLatLngs(t[0]),this._holes=t.slice(1),e=0,i=this._holes.length;i>e;e++)n=this._holes[e]=this._convertLatLngs(this._holes[e]),n[0].equals(n[n.length-1])&&n.pop();t=this._latlngs,t.length>=2&&t[0].equals(t[t.length-1])&&t.pop()},projectLatlngs:function(){if(s.Polyline.prototype.projectLatlngs.call(this),this._holePoints=[],this._holes){var t,e,i,n;for(t=0,i=this._holes.length;i>t;t++)for(this._holePoints[t]=[],e=0,n=this._holes[t].length;n>e;e++)this._holePoints[t][e]=this._map.latLngToLayerPoint(this._holes[t][e])}},setLatLngs:function(t){return t&&s.Util.isArray(t[0])&&"number"!=typeof t[0][0]?(this._initWithHoles(t),this.redraw()):s.Polyline.prototype.setLatLngs.call(this,t)},_clipPoints:function(){var t=this._originalPoints,e=[];if(this._parts=[t].concat(this._holePoints),!this.options.noClip){for(var i=0,n=this._parts.length;n>i;i++){var o=s.PolyUtil.clipPolygon(this._parts[i],this._map._pathViewport);o.length&&e.push(o)}this._parts=e}},_getPathPartStr:function(t){var e=s.Polyline.prototype._getPathPartStr.call(this,t);return e+(s.Browser.svg?"z":"x")}}),s.polygon=function(t,e){return new s.Polygon(t,e)},function(){function t(t){return s.FeatureGroup.extend({initialize:function(t,e){this._layers={},this._options=e,this.setLatLngs(t)},setLatLngs:function(e){var i=0,n=e.length;for(this.eachLayer(function(t){n>i?t.setLatLngs(e[i++]):this.removeLayer(t)},this);n>i;)this.addLayer(new t(e[i++],this._options));return this},getLatLngs:function(){var t=[];return this.eachLayer(function(e){t.push(e.getLatLngs())}),t}})}s.MultiPolyline=t(s.Polyline),s.MultiPolygon=t(s.Polygon),s.multiPolyline=function(t,e){return new s.MultiPolyline(t,e)},s.multiPolygon=function(t,e){return new s.MultiPolygon(t,e)}}(),s.Rectangle=s.Polygon.extend({initialize:function(t,e){s.Polygon.prototype.initialize.call(this,this._boundsToLatLngs(t),e)},setBounds:function(t){this.setLatLngs(this._boundsToLatLngs(t))},_boundsToLatLngs:function(t){return t=s.latLngBounds(t),[t.getSouthWest(),t.getNorthWest(),t.getNorthEast(),t.getSouthEast()]}}),s.rectangle=function(t,e){return new s.Rectangle(t,e)},s.Circle=s.Path.extend({initialize:function(t,e,i){s.Path.prototype.initialize.call(this,i),this._latlng=s.latLng(t),this._mRadius=e},options:{fill:!0},setLatLng:function(t){return this._latlng=s.latLng(t),this.redraw()},setRadius:function(t){return this._mRadius=t,this.redraw()},projectLatlngs:function(){var t=this._getLngRadius(),e=this._latlng,i=this._map.latLngToLayerPoint([e.lat,e.lng-t]);this._point=this._map.latLngToLayerPoint(e),this._radius=Math.max(this._point.x-i.x,1)},getBounds:function(){var t=this._getLngRadius(),e=this._mRadius/40075017*360,i=this._latlng;return new s.LatLngBounds([i.lat-e,i.lng-t],[i.lat+e,i.lng+t])},getLatLng:function(){return this._latlng},getPathString:function(){var t=this._point,e=this._radius;return this._checkIfEmpty()?"":s.Browser.svg?"M"+t.x+","+(t.y-e)+"A"+e+","+e+",0,1,1,"+(t.x-.1)+","+(t.y-e)+" z":(t._round(),e=Math.round(e),"AL "+t.x+","+t.y+" "+e+","+e+" 0,23592600")},getRadius:function(){return this._mRadius},_getLatRadius:function(){return this._mRadius/40075017*360},_getLngRadius:function(){return this._getLatRadius()/Math.cos(s.LatLng.DEG_TO_RAD*this._latlng.lat)},_checkIfEmpty:function(){if(!this._map)return!1;var t=this._map._pathViewport,e=this._radius,i=this._point;return i.x-e>t.max.x||i.y-e>t.max.y||i.x+e<t.min.x||i.y+e<t.min.y}}),s.circle=function(t,e,i){return new s.Circle(t,e,i)},s.CircleMarker=s.Circle.extend({options:{radius:10,weight:2},initialize:function(t,e){s.Circle.prototype.initialize.call(this,t,null,e),this._radius=this.options.radius},projectLatlngs:function(){this._point=this._map.latLngToLayerPoint(this._latlng)},_updateStyle:function(){s.Circle.prototype._updateStyle.call(this),this.setRadius(this.options.radius)},setLatLng:function(t){return s.Circle.prototype.setLatLng.call(this,t),this._popup&&this._popup._isOpen&&this._popup.setLatLng(t),this},setRadius:function(t){return this.options.radius=this._radius=t,this.redraw()},getRadius:function(){return this._radius}}),s.circleMarker=function(t,e){return new s.CircleMarker(t,e)},s.Polyline.include(s.Path.CANVAS?{_containsPoint:function(t,e){var i,n,o,a,r,l,h,u=this.options.weight/2;for(s.Browser.touch&&(u+=10),i=0,a=this._parts.length;a>i;i++)for(h=this._parts[i],n=0,r=h.length,o=r-1;r>n;o=n++)if((e||0!==n)&&(l=s.LineUtil.pointToSegmentDistance(t,h[o],h[n]),u>=l))return!0;return!1}}:{}),s.Polygon.include(s.Path.CANVAS?{_containsPoint:function(t){var e,i,n,o,a,r,l,h,u=!1;if(s.Polyline.prototype._containsPoint.call(this,t,!0))return!0;for(o=0,l=this._parts.length;l>o;o++)for(e=this._parts[o],a=0,h=e.length,r=h-1;h>a;r=a++)i=e[a],n=e[r],i.y>t.y!=n.y>t.y&&t.x<(n.x-i.x)*(t.y-i.y)/(n.y-i.y)+i.x&&(u=!u);return u}}:{}),s.Circle.include(s.Path.CANVAS?{_drawPath:function(){var t=this._point;this._ctx.beginPath(),this._ctx.arc(t.x,t.y,this._radius,0,2*Math.PI,!1)},_containsPoint:function(t){var e=this._point,i=this.options.stroke?this.options.weight/2:0;return t.distanceTo(e)<=this._radius+i}}:{}),s.CircleMarker.include(s.Path.CANVAS?{_updateStyle:function(){s.Path.prototype._updateStyle.call(this)}}:{}),s.GeoJSON=s.FeatureGroup.extend({initialize:function(t,e){s.setOptions(this,e),this._layers={},t&&this.addData(t)},addData:function(t){var e,i,n,o=s.Util.isArray(t)?t:t.features;if(o){for(e=0,i=o.length;i>e;e++)n=o[e],(n.geometries||n.geometry||n.features||n.coordinates)&&this.addData(o[e]);return this}var a=this.options;if(!a.filter||a.filter(t)){var r=s.GeoJSON.geometryToLayer(t,a.pointToLayer,a.coordsToLatLng,a);return r.feature=s.GeoJSON.asFeature(t),r.defaultOptions=r.options,this.resetStyle(r),a.onEachFeature&&a.onEachFeature(t,r),this.addLayer(r)}},resetStyle:function(t){var e=this.options.style;e&&(s.Util.extend(t.options,t.defaultOptions),this._setLayerStyle(t,e))},setStyle:function(t){this.eachLayer(function(e){this._setLayerStyle(e,t)},this)},_setLayerStyle:function(t,e){"function"==typeof e&&(e=e(t.feature)),t.setStyle&&t.setStyle(e)}}),s.extend(s.GeoJSON,{geometryToLayer:function(t,e,i,n){var o,a,r,l,h="Feature"===t.type?t.geometry:t,u=h.coordinates,c=[];switch(i=i||this.coordsToLatLng,h.type){case"Point":return o=i(u),e?e(t,o):new s.Marker(o);case"MultiPoint":for(r=0,l=u.length;l>r;r++)o=i(u[r]),c.push(e?e(t,o):new s.Marker(o));return new s.FeatureGroup(c);case"LineString":return a=this.coordsToLatLngs(u,0,i),new s.Polyline(a,n);case"Polygon":if(2===u.length&&!u[1].length)throw new Error("Invalid GeoJSON object.");return a=this.coordsToLatLngs(u,1,i),new s.Polygon(a,n);case"MultiLineString":return a=this.coordsToLatLngs(u,1,i),new s.MultiPolyline(a,n);case"MultiPolygon":return a=this.coordsToLatLngs(u,2,i),new s.MultiPolygon(a,n);case"GeometryCollection":for(r=0,l=h.geometries.length;l>r;r++)c.push(this.geometryToLayer({geometry:h.geometries[r],type:"Feature",properties:t.properties},e,i,n));return new s.FeatureGroup(c);default:throw new Error("Invalid GeoJSON object.")}},coordsToLatLng:function(t){return new s.LatLng(t[1],t[0],t[2])},coordsToLatLngs:function(t,e,i){var n,o,s,a=[];for(o=0,s=t.length;s>o;o++)n=e?this.coordsToLatLngs(t[o],e-1,i):(i||this.coordsToLatLng)(t[o]),a.push(n);return a},latLngToCoords:function(t){var e=[t.lng,t.lat];return t.alt!==n&&e.push(t.alt),e},latLngsToCoords:function(t){for(var e=[],i=0,n=t.length;n>i;i++)e.push(s.GeoJSON.latLngToCoords(t[i]));return e},getFeature:function(t,e){return t.feature?s.extend({},t.feature,{geometry:e}):s.GeoJSON.asFeature(e)},asFeature:function(t){return"Feature"===t.type?t:{type:"Feature",properties:{},geometry:t}}});var r={toGeoJSON:function(){return s.GeoJSON.getFeature(this,{type:"Point",coordinates:s.GeoJSON.latLngToCoords(this.getLatLng())})}};s.Marker.include(r),s.Circle.include(r),s.CircleMarker.include(r),s.Polyline.include({toGeoJSON:function(){return s.GeoJSON.getFeature(this,{type:"LineString",coordinates:s.GeoJSON.latLngsToCoords(this.getLatLngs())})}}),s.Polygon.include({toGeoJSON:function(){var t,e,i,n=[s.GeoJSON.latLngsToCoords(this.getLatLngs())];if(n[0].push(n[0][0]),this._holes)for(t=0,e=this._holes.length;e>t;t++)i=s.GeoJSON.latLngsToCoords(this._holes[t]),i.push(i[0]),n.push(i);return s.GeoJSON.getFeature(this,{type:"Polygon",coordinates:n})}}),function(){function t(t){return function(){var e=[];return this.eachLayer(function(t){e.push(t.toGeoJSON().geometry.coordinates)}),s.GeoJSON.getFeature(this,{type:t,coordinates:e})}}s.MultiPolyline.include({toGeoJSON:t("MultiLineString")}),s.MultiPolygon.include({toGeoJSON:t("MultiPolygon")}),s.LayerGroup.include({toGeoJSON:function(){var e,i=this.feature&&this.feature.geometry,n=[];if(i&&"MultiPoint"===i.type)return t("MultiPoint").call(this);var o=i&&"GeometryCollection"===i.type;return this.eachLayer(function(t){t.toGeoJSON&&(e=t.toGeoJSON(),n.push(o?e.geometry:s.GeoJSON.asFeature(e)))}),o?s.GeoJSON.getFeature(this,{geometries:n,type:"GeometryCollection"}):{type:"FeatureCollection",features:n}}})}(),s.geoJson=function(t,e){return new s.GeoJSON(t,e)},s.DomEvent={addListener:function(t,e,i,n){var o,a,r,l=s.stamp(i),h="_leaflet_"+e+l;return t[h]?this:(o=function(e){return i.call(n||t,e||s.DomEvent._getEvent())},s.Browser.pointer&&0===e.indexOf("touch")?this.addPointerListener(t,e,o,l):(s.Browser.touch&&"dblclick"===e&&this.addDoubleTapListener&&this.addDoubleTapListener(t,o,l),"addEventListener"in t?"mousewheel"===e?(t.addEventListener("DOMMouseScroll",o,!1),t.addEventListener(e,o,!1)):"mouseenter"===e||"mouseleave"===e?(a=o,r="mouseenter"===e?"mouseover":"mouseout",o=function(e){return s.DomEvent._checkMouse(t,e)?a(e):void 0},t.addEventListener(r,o,!1)):"click"===e&&s.Browser.android?(a=o,o=function(t){return s.DomEvent._filterClick(t,a)},t.addEventListener(e,o,!1)):t.addEventListener(e,o,!1):"attachEvent"in t&&t.attachEvent("on"+e,o),t[h]=o,this))},removeListener:function(t,e,i){var n=s.stamp(i),o="_leaflet_"+e+n,a=t[o];return a?(s.Browser.pointer&&0===e.indexOf("touch")?this.removePointerListener(t,e,n):s.Browser.touch&&"dblclick"===e&&this.removeDoubleTapListener?this.removeDoubleTapListener(t,n):"removeEventListener"in t?"mousewheel"===e?(t.removeEventListener("DOMMouseScroll",a,!1),t.removeEventListener(e,a,!1)):"mouseenter"===e||"mouseleave"===e?t.removeEventListener("mouseenter"===e?"mouseover":"mouseout",a,!1):t.removeEventListener(e,a,!1):"detachEvent"in t&&t.detachEvent("on"+e,a),t[o]=null,this):this},stopPropagation:function(t){return t.stopPropagation?t.stopPropagation():t.cancelBubble=!0,s.DomEvent._skipped(t),this},disableScrollPropagation:function(t){var e=s.DomEvent.stopPropagation;return s.DomEvent.on(t,"mousewheel",e).on(t,"MozMousePixelScroll",e)},disableClickPropagation:function(t){for(var e=s.DomEvent.stopPropagation,i=s.Draggable.START.length-1;i>=0;i--)s.DomEvent.on(t,s.Draggable.START[i],e);return s.DomEvent.on(t,"click",s.DomEvent._fakeStop).on(t,"dblclick",e)},preventDefault:function(t){return t.preventDefault?t.preventDefault():t.returnValue=!1,this},stop:function(t){return s.DomEvent.preventDefault(t).stopPropagation(t)},getMousePosition:function(t,e){if(!e)return new s.Point(t.clientX,t.clientY);var i=e.getBoundingClientRect();return new s.Point(t.clientX-i.left-e.clientLeft,t.clientY-i.top-e.clientTop)},getWheelDelta:function(t){var e=0;return t.wheelDelta&&(e=t.wheelDelta/120),t.detail&&(e=-t.detail/3),e},_skipEvents:{},_fakeStop:function(t){s.DomEvent._skipEvents[t.type]=!0},_skipped:function(t){var e=this._skipEvents[t.type];return this._skipEvents[t.type]=!1,e},_checkMouse:function(t,e){var i=e.relatedTarget;if(!i)return!0;try{for(;i&&i!==t;)i=i.parentNode}catch(n){return!1}return i!==t},_getEvent:function(){var e=t.event;if(!e)for(var i=arguments.callee.caller;i&&(e=i.arguments[0],!e||t.Event!==e.constructor);)i=i.caller;return e},_filterClick:function(t,e){var i=t.timeStamp||t.originalEvent.timeStamp,n=s.DomEvent._lastClick&&i-s.DomEvent._lastClick;return n&&n>100&&500>n||t.target._simulatedClick&&!t._simulated?(s.DomEvent.stop(t),void 0):(s.DomEvent._lastClick=i,e(t))}},s.DomEvent.on=s.DomEvent.addListener,s.DomEvent.off=s.DomEvent.removeListener,s.Draggable=s.Class.extend({includes:s.Mixin.Events,statics:{START:s.Browser.touch?["touchstart","mousedown"]:["mousedown"],END:{mousedown:"mouseup",touchstart:"touchend",pointerdown:"touchend",MSPointerDown:"touchend"},MOVE:{mousedown:"mousemove",touchstart:"touchmove",pointerdown:"touchmove",MSPointerDown:"touchmove"}},initialize:function(t,e){this._element=t,this._dragStartTarget=e||t},enable:function(){if(!this._enabled){for(var t=s.Draggable.START.length-1;t>=0;t--)s.DomEvent.on(this._dragStartTarget,s.Draggable.START[t],this._onDown,this);this._enabled=!0}},disable:function(){if(this._enabled){for(var t=s.Draggable.START.length-1;t>=0;t--)s.DomEvent.off(this._dragStartTarget,s.Draggable.START[t],this._onDown,this);this._enabled=!1,this._moved=!1}},_onDown:function(t){if(this._moved=!1,!(t.shiftKey||1!==t.which&&1!==t.button&&!t.touches||(s.DomEvent.stopPropagation(t),s.Draggable._disabled||(s.DomUtil.disableImageDrag(),s.DomUtil.disableTextSelection(),this._moving)))){var e=t.touches?t.touches[0]:t;this._startPoint=new s.Point(e.clientX,e.clientY),this._startPos=this._newPos=s.DomUtil.getPosition(this._element),s.DomEvent.on(i,s.Draggable.MOVE[t.type],this._onMove,this).on(i,s.Draggable.END[t.type],this._onUp,this)}},_onMove:function(t){if(t.touches&&t.touches.length>1)return this._moved=!0,void 0;var e=t.touches&&1===t.touches.length?t.touches[0]:t,n=new s.Point(e.clientX,e.clientY),o=n.subtract(this._startPoint);(o.x||o.y)&&(s.Browser.touch&&Math.abs(o.x)+Math.abs(o.y)<3||(s.DomEvent.preventDefault(t),this._moved||(this.fire("dragstart"),this._moved=!0,this._startPos=s.DomUtil.getPosition(this._element).subtract(o),s.DomUtil.addClass(i.body,"leaflet-dragging"),this._lastTarget=t.target||t.srcElement,s.DomUtil.addClass(this._lastTarget,"leaflet-drag-target")),this._newPos=this._startPos.add(o),this._moving=!0,s.Util.cancelAnimFrame(this._animRequest),this._animRequest=s.Util.requestAnimFrame(this._updatePosition,this,!0,this._dragStartTarget)))},_updatePosition:function(){this.fire("predrag"),s.DomUtil.setPosition(this._element,this._newPos),this.fire("drag")},_onUp:function(){s.DomUtil.removeClass(i.body,"leaflet-dragging"),this._lastTarget&&(s.DomUtil.removeClass(this._lastTarget,"leaflet-drag-target"),this._lastTarget=null);for(var t in s.Draggable.MOVE)s.DomEvent.off(i,s.Draggable.MOVE[t],this._onMove).off(i,s.Draggable.END[t],this._onUp);s.DomUtil.enableImageDrag(),s.DomUtil.enableTextSelection(),this._moved&&this._moving&&(s.Util.cancelAnimFrame(this._animRequest),this.fire("dragend",{distance:this._newPos.distanceTo(this._startPos)})),this._moving=!1}}),s.Handler=s.Class.extend({initialize:function(t){this._map=t},enable:function(){this._enabled||(this._enabled=!0,this.addHooks())},disable:function(){this._enabled&&(this._enabled=!1,this.removeHooks())},enabled:function(){return!!this._enabled}}),s.Map.mergeOptions({dragging:!0,inertia:!s.Browser.android23,inertiaDeceleration:3400,inertiaMaxSpeed:1/0,inertiaThreshold:s.Browser.touch?32:18,easeLinearity:.25,worldCopyJump:!1}),s.Map.Drag=s.Handler.extend({addHooks:function(){if(!this._draggable){var t=this._map;this._draggable=new s.Draggable(t._mapPane,t._container),this._draggable.on({dragstart:this._onDragStart,drag:this._onDrag,dragend:this._onDragEnd},this),t.options.worldCopyJump&&(this._draggable.on("predrag",this._onPreDrag,this),t.on("viewreset",this._onViewReset,this),t.whenReady(this._onViewReset,this))}this._draggable.enable()},removeHooks:function(){this._draggable.disable()},moved:function(){return this._draggable&&this._draggable._moved},_onDragStart:function(){var t=this._map;t._panAnim&&t._panAnim.stop(),t.fire("movestart").fire("dragstart"),t.options.inertia&&(this._positions=[],this._times=[])},_onDrag:function(){if(this._map.options.inertia){var t=this._lastTime=+new Date,e=this._lastPos=this._draggable._newPos;this._positions.push(e),this._times.push(t),t-this._times[0]>200&&(this._positions.shift(),this._times.shift())}this._map.fire("move").fire("drag")},_onViewReset:function(){var t=this._map.getSize()._divideBy(2),e=this._map.latLngToLayerPoint([0,0]);this._initialWorldOffset=e.subtract(t).x,this._worldWidth=this._map.project([0,180]).x},_onPreDrag:function(){var t=this._worldWidth,e=Math.round(t/2),i=this._initialWorldOffset,n=this._draggable._newPos.x,o=(n-e+i)%t+e-i,s=(n+e+i)%t-e-i,a=Math.abs(o+i)<Math.abs(s+i)?o:s;this._draggable._newPos.x=a},_onDragEnd:function(t){var e=this._map,i=e.options,n=+new Date-this._lastTime,o=!i.inertia||n>i.inertiaThreshold||!this._positions[0];if(e.fire("dragend",t),o)e.fire("moveend");else{var a=this._lastPos.subtract(this._positions[0]),r=(this._lastTime+n-this._times[0])/1e3,l=i.easeLinearity,h=a.multiplyBy(l/r),u=h.distanceTo([0,0]),c=Math.min(i.inertiaMaxSpeed,u),p=h.multiplyBy(c/u),d=c/(i.inertiaDeceleration*l),m=p.multiplyBy(-d/2).round();m.x&&m.y?(m=e._limitOffset(m,e.options.maxBounds),s.Util.requestAnimFrame(function(){e.panBy(m,{duration:d,easeLinearity:l,noMoveStart:!0})})):e.fire("moveend")}}}),s.Map.addInitHook("addHandler","dragging",s.Map.Drag),s.Map.mergeOptions({doubleClickZoom:!0}),s.Map.DoubleClickZoom=s.Handler.extend({addHooks:function(){this._map.on("dblclick",this._onDoubleClick,this)},removeHooks:function(){this._map.off("dblclick",this._onDoubleClick,this)},_onDoubleClick:function(t){var e=this._map,i=e.getZoom()+(t.originalEvent.shiftKey?-1:1);"center"===e.options.doubleClickZoom?e.setZoom(i):e.setZoomAround(t.containerPoint,i)}}),s.Map.addInitHook("addHandler","doubleClickZoom",s.Map.DoubleClickZoom),s.Map.mergeOptions({scrollWheelZoom:!0}),s.Map.ScrollWheelZoom=s.Handler.extend({addHooks:function(){s.DomEvent.on(this._map._container,"mousewheel",this._onWheelScroll,this),s.DomEvent.on(this._map._container,"MozMousePixelScroll",s.DomEvent.preventDefault),this._delta=0},removeHooks:function(){s.DomEvent.off(this._map._container,"mousewheel",this._onWheelScroll),s.DomEvent.off(this._map._container,"MozMousePixelScroll",s.DomEvent.preventDefault)},_onWheelScroll:function(t){var e=s.DomEvent.getWheelDelta(t);this._delta+=e,this._lastMousePos=this._map.mouseEventToContainerPoint(t),this._startTime||(this._startTime=+new Date);var i=Math.max(40-(+new Date-this._startTime),0);clearTimeout(this._timer),this._timer=setTimeout(s.bind(this._performZoom,this),i),s.DomEvent.preventDefault(t),s.DomEvent.stopPropagation(t)},_performZoom:function(){var t=this._map,e=this._delta,i=t.getZoom();e=e>0?Math.ceil(e):Math.floor(e),e=Math.max(Math.min(e,4),-4),e=t._limitZoom(i+e)-i,this._delta=0,this._startTime=null,e&&("center"===t.options.scrollWheelZoom?t.setZoom(i+e):t.setZoomAround(this._lastMousePos,i+e))}}),s.Map.addInitHook("addHandler","scrollWheelZoom",s.Map.ScrollWheelZoom),s.extend(s.DomEvent,{_touchstart:s.Browser.msPointer?"MSPointerDown":s.Browser.pointer?"pointerdown":"touchstart",_touchend:s.Browser.msPointer?"MSPointerUp":s.Browser.pointer?"pointerup":"touchend",addDoubleTapListener:function(t,e,n){function o(t){var e;if(s.Browser.pointer?(m.push(t.pointerId),e=m.length):e=t.touches.length,!(e>1)){var i=Date.now(),n=i-(r||i);l=t.touches?t.touches[0]:t,h=n>0&&u>=n,r=i}}function a(t){if(s.Browser.pointer){var i=m.indexOf(t.pointerId);if(-1===i)return;m.splice(i,1)}if(h){if(s.Browser.pointer){var n,o={};for(var a in l)n=l[a],o[a]="function"==typeof n?n.bind(l):n;l=o}l.type="dblclick",e(l),r=null
  }}var r,l,h=!1,u=250,c="_leaflet_",p=this._touchstart,d=this._touchend,m=[];t[c+p+n]=o,t[c+d+n]=a;var f=s.Browser.pointer?i.documentElement:t;return t.addEventListener(p,o,!1),f.addEventListener(d,a,!1),s.Browser.pointer&&f.addEventListener(s.DomEvent.POINTER_CANCEL,a,!1),this},removeDoubleTapListener:function(t,e){var n="_leaflet_";return t.removeEventListener(this._touchstart,t[n+this._touchstart+e],!1),(s.Browser.pointer?i.documentElement:t).removeEventListener(this._touchend,t[n+this._touchend+e],!1),s.Browser.pointer&&i.documentElement.removeEventListener(s.DomEvent.POINTER_CANCEL,t[n+this._touchend+e],!1),this}}),s.extend(s.DomEvent,{POINTER_DOWN:s.Browser.msPointer?"MSPointerDown":"pointerdown",POINTER_MOVE:s.Browser.msPointer?"MSPointerMove":"pointermove",POINTER_UP:s.Browser.msPointer?"MSPointerUp":"pointerup",POINTER_CANCEL:s.Browser.msPointer?"MSPointerCancel":"pointercancel",_pointers:[],_pointerDocumentListener:!1,addPointerListener:function(t,e,i,n){switch(e){case"touchstart":return this.addPointerListenerStart(t,e,i,n);case"touchend":return this.addPointerListenerEnd(t,e,i,n);case"touchmove":return this.addPointerListenerMove(t,e,i,n);default:throw"Unknown touch event type"}},addPointerListenerStart:function(t,e,n,o){var a="_leaflet_",r=this._pointers,l=function(t){s.DomEvent.preventDefault(t);for(var e=!1,i=0;i<r.length;i++)if(r[i].pointerId===t.pointerId){e=!0;break}e||r.push(t),t.touches=r.slice(),t.changedTouches=[t],n(t)};if(t[a+"touchstart"+o]=l,t.addEventListener(this.POINTER_DOWN,l,!1),!this._pointerDocumentListener){var h=function(t){for(var e=0;e<r.length;e++)if(r[e].pointerId===t.pointerId){r.splice(e,1);break}};i.documentElement.addEventListener(this.POINTER_UP,h,!1),i.documentElement.addEventListener(this.POINTER_CANCEL,h,!1),this._pointerDocumentListener=!0}return this},addPointerListenerMove:function(t,e,i,n){function o(t){if(t.pointerType!==t.MSPOINTER_TYPE_MOUSE&&"mouse"!==t.pointerType||0!==t.buttons){for(var e=0;e<a.length;e++)if(a[e].pointerId===t.pointerId){a[e]=t;break}t.touches=a.slice(),t.changedTouches=[t],i(t)}}var s="_leaflet_",a=this._pointers;return t[s+"touchmove"+n]=o,t.addEventListener(this.POINTER_MOVE,o,!1),this},addPointerListenerEnd:function(t,e,i,n){var o="_leaflet_",s=this._pointers,a=function(t){for(var e=0;e<s.length;e++)if(s[e].pointerId===t.pointerId){s.splice(e,1);break}t.touches=s.slice(),t.changedTouches=[t],i(t)};return t[o+"touchend"+n]=a,t.addEventListener(this.POINTER_UP,a,!1),t.addEventListener(this.POINTER_CANCEL,a,!1),this},removePointerListener:function(t,e,i){var n="_leaflet_",o=t[n+e+i];switch(e){case"touchstart":t.removeEventListener(this.POINTER_DOWN,o,!1);break;case"touchmove":t.removeEventListener(this.POINTER_MOVE,o,!1);break;case"touchend":t.removeEventListener(this.POINTER_UP,o,!1),t.removeEventListener(this.POINTER_CANCEL,o,!1)}return this}}),s.Map.mergeOptions({touchZoom:s.Browser.touch&&!s.Browser.android23,bounceAtZoomLimits:!0}),s.Map.TouchZoom=s.Handler.extend({addHooks:function(){s.DomEvent.on(this._map._container,"touchstart",this._onTouchStart,this)},removeHooks:function(){s.DomEvent.off(this._map._container,"touchstart",this._onTouchStart,this)},_onTouchStart:function(t){var e=this._map;if(t.touches&&2===t.touches.length&&!e._animatingZoom&&!this._zooming){var n=e.mouseEventToLayerPoint(t.touches[0]),o=e.mouseEventToLayerPoint(t.touches[1]),a=e._getCenterLayerPoint();this._startCenter=n.add(o)._divideBy(2),this._startDist=n.distanceTo(o),this._moved=!1,this._zooming=!0,this._centerOffset=a.subtract(this._startCenter),e._panAnim&&e._panAnim.stop(),s.DomEvent.on(i,"touchmove",this._onTouchMove,this).on(i,"touchend",this._onTouchEnd,this),s.DomEvent.preventDefault(t)}},_onTouchMove:function(t){var e=this._map;if(t.touches&&2===t.touches.length&&this._zooming){var i=e.mouseEventToLayerPoint(t.touches[0]),n=e.mouseEventToLayerPoint(t.touches[1]);this._scale=i.distanceTo(n)/this._startDist,this._delta=i._add(n)._divideBy(2)._subtract(this._startCenter),1!==this._scale&&(e.options.bounceAtZoomLimits||!(e.getZoom()===e.getMinZoom()&&this._scale<1||e.getZoom()===e.getMaxZoom()&&this._scale>1))&&(this._moved||(s.DomUtil.addClass(e._mapPane,"leaflet-touching"),e.fire("movestart").fire("zoomstart"),this._moved=!0),s.Util.cancelAnimFrame(this._animRequest),this._animRequest=s.Util.requestAnimFrame(this._updateOnMove,this,!0,this._map._container),s.DomEvent.preventDefault(t))}},_updateOnMove:function(){var t=this._map,e=this._getScaleOrigin(),i=t.layerPointToLatLng(e),n=t.getScaleZoom(this._scale);t._animateZoom(i,n,this._startCenter,this._scale,this._delta,!1,!0)},_onTouchEnd:function(){if(!this._moved||!this._zooming)return this._zooming=!1,void 0;var t=this._map;this._zooming=!1,s.DomUtil.removeClass(t._mapPane,"leaflet-touching"),s.Util.cancelAnimFrame(this._animRequest),s.DomEvent.off(i,"touchmove",this._onTouchMove).off(i,"touchend",this._onTouchEnd);var e=this._getScaleOrigin(),n=t.layerPointToLatLng(e),o=t.getZoom(),a=t.getScaleZoom(this._scale)-o,r=a>0?Math.ceil(a):Math.floor(a),l=t._limitZoom(o+r),h=t.getZoomScale(l)/this._scale;t._animateZoom(n,l,e,h)},_getScaleOrigin:function(){var t=this._centerOffset.subtract(this._delta).divideBy(this._scale);return this._startCenter.add(t)}}),s.Map.addInitHook("addHandler","touchZoom",s.Map.TouchZoom),s.Map.mergeOptions({tap:!0,tapTolerance:15}),s.Map.Tap=s.Handler.extend({addHooks:function(){s.DomEvent.on(this._map._container,"touchstart",this._onDown,this)},removeHooks:function(){s.DomEvent.off(this._map._container,"touchstart",this._onDown,this)},_onDown:function(t){if(t.touches){if(s.DomEvent.preventDefault(t),this._fireClick=!0,t.touches.length>1)return this._fireClick=!1,clearTimeout(this._holdTimeout),void 0;var e=t.touches[0],n=e.target;this._startPos=this._newPos=new s.Point(e.clientX,e.clientY),n.tagName&&"a"===n.tagName.toLowerCase()&&s.DomUtil.addClass(n,"leaflet-active"),this._holdTimeout=setTimeout(s.bind(function(){this._isTapValid()&&(this._fireClick=!1,this._onUp(),this._simulateEvent("contextmenu",e))},this),1e3),s.DomEvent.on(i,"touchmove",this._onMove,this).on(i,"touchend",this._onUp,this)}},_onUp:function(t){if(clearTimeout(this._holdTimeout),s.DomEvent.off(i,"touchmove",this._onMove,this).off(i,"touchend",this._onUp,this),this._fireClick&&t&&t.changedTouches){var e=t.changedTouches[0],n=e.target;n&&n.tagName&&"a"===n.tagName.toLowerCase()&&s.DomUtil.removeClass(n,"leaflet-active"),this._isTapValid()&&this._simulateEvent("click",e)}},_isTapValid:function(){return this._newPos.distanceTo(this._startPos)<=this._map.options.tapTolerance},_onMove:function(t){var e=t.touches[0];this._newPos=new s.Point(e.clientX,e.clientY)},_simulateEvent:function(e,n){var o=i.createEvent("MouseEvents");o._simulated=!0,n.target._simulatedClick=!0,o.initMouseEvent(e,!0,!0,t,1,n.screenX,n.screenY,n.clientX,n.clientY,!1,!1,!1,!1,0,null),n.target.dispatchEvent(o)}}),s.Browser.touch&&!s.Browser.pointer&&s.Map.addInitHook("addHandler","tap",s.Map.Tap),s.Map.mergeOptions({boxZoom:!0}),s.Map.BoxZoom=s.Handler.extend({initialize:function(t){this._map=t,this._container=t._container,this._pane=t._panes.overlayPane,this._moved=!1},addHooks:function(){s.DomEvent.on(this._container,"mousedown",this._onMouseDown,this)},removeHooks:function(){s.DomEvent.off(this._container,"mousedown",this._onMouseDown),this._moved=!1},moved:function(){return this._moved},_onMouseDown:function(t){return this._moved=!1,!t.shiftKey||1!==t.which&&1!==t.button?!1:(s.DomUtil.disableTextSelection(),s.DomUtil.disableImageDrag(),this._startLayerPoint=this._map.mouseEventToLayerPoint(t),s.DomEvent.on(i,"mousemove",this._onMouseMove,this).on(i,"mouseup",this._onMouseUp,this).on(i,"keydown",this._onKeyDown,this),void 0)},_onMouseMove:function(t){this._moved||(this._box=s.DomUtil.create("div","leaflet-zoom-box",this._pane),s.DomUtil.setPosition(this._box,this._startLayerPoint),this._container.style.cursor="crosshair",this._map.fire("boxzoomstart"));var e=this._startLayerPoint,i=this._box,n=this._map.mouseEventToLayerPoint(t),o=n.subtract(e),a=new s.Point(Math.min(n.x,e.x),Math.min(n.y,e.y));s.DomUtil.setPosition(i,a),this._moved=!0,i.style.width=Math.max(0,Math.abs(o.x)-4)+"px",i.style.height=Math.max(0,Math.abs(o.y)-4)+"px"},_finish:function(){this._moved&&(this._pane.removeChild(this._box),this._container.style.cursor=""),s.DomUtil.enableTextSelection(),s.DomUtil.enableImageDrag(),s.DomEvent.off(i,"mousemove",this._onMouseMove).off(i,"mouseup",this._onMouseUp).off(i,"keydown",this._onKeyDown)},_onMouseUp:function(t){this._finish();var e=this._map,i=e.mouseEventToLayerPoint(t);if(!this._startLayerPoint.equals(i)){var n=new s.LatLngBounds(e.layerPointToLatLng(this._startLayerPoint),e.layerPointToLatLng(i));e.fitBounds(n),e.fire("boxzoomend",{boxZoomBounds:n})}},_onKeyDown:function(t){27===t.keyCode&&this._finish()}}),s.Map.addInitHook("addHandler","boxZoom",s.Map.BoxZoom),s.Map.mergeOptions({keyboard:!0,keyboardPanOffset:80,keyboardZoomOffset:1}),s.Map.Keyboard=s.Handler.extend({keyCodes:{left:[37],right:[39],down:[40],up:[38],zoomIn:[187,107,61,171],zoomOut:[189,109,173]},initialize:function(t){this._map=t,this._setPanOffset(t.options.keyboardPanOffset),this._setZoomOffset(t.options.keyboardZoomOffset)},addHooks:function(){var t=this._map._container;-1===t.tabIndex&&(t.tabIndex="0"),s.DomEvent.on(t,"focus",this._onFocus,this).on(t,"blur",this._onBlur,this).on(t,"mousedown",this._onMouseDown,this),this._map.on("focus",this._addHooks,this).on("blur",this._removeHooks,this)},removeHooks:function(){this._removeHooks();var t=this._map._container;s.DomEvent.off(t,"focus",this._onFocus,this).off(t,"blur",this._onBlur,this).off(t,"mousedown",this._onMouseDown,this),this._map.off("focus",this._addHooks,this).off("blur",this._removeHooks,this)},_onMouseDown:function(){if(!this._focused){var e=i.body,n=i.documentElement,o=e.scrollTop||n.scrollTop,s=e.scrollLeft||n.scrollLeft;this._map._container.focus(),t.scrollTo(s,o)}},_onFocus:function(){this._focused=!0,this._map.fire("focus")},_onBlur:function(){this._focused=!1,this._map.fire("blur")},_setPanOffset:function(t){var e,i,n=this._panKeys={},o=this.keyCodes;for(e=0,i=o.left.length;i>e;e++)n[o.left[e]]=[-1*t,0];for(e=0,i=o.right.length;i>e;e++)n[o.right[e]]=[t,0];for(e=0,i=o.down.length;i>e;e++)n[o.down[e]]=[0,t];for(e=0,i=o.up.length;i>e;e++)n[o.up[e]]=[0,-1*t]},_setZoomOffset:function(t){var e,i,n=this._zoomKeys={},o=this.keyCodes;for(e=0,i=o.zoomIn.length;i>e;e++)n[o.zoomIn[e]]=t;for(e=0,i=o.zoomOut.length;i>e;e++)n[o.zoomOut[e]]=-t},_addHooks:function(){s.DomEvent.on(i,"keydown",this._onKeyDown,this)},_removeHooks:function(){s.DomEvent.off(i,"keydown",this._onKeyDown,this)},_onKeyDown:function(t){var e=t.keyCode,i=this._map;if(e in this._panKeys){if(i._panAnim&&i._panAnim._inProgress)return;i.panBy(this._panKeys[e]),i.options.maxBounds&&i.panInsideBounds(i.options.maxBounds)}else{if(!(e in this._zoomKeys))return;i.setZoom(i.getZoom()+this._zoomKeys[e])}s.DomEvent.stop(t)}}),s.Map.addInitHook("addHandler","keyboard",s.Map.Keyboard),s.Handler.MarkerDrag=s.Handler.extend({initialize:function(t){this._marker=t},addHooks:function(){var t=this._marker._icon;this._draggable||(this._draggable=new s.Draggable(t,t)),this._draggable.on("dragstart",this._onDragStart,this).on("drag",this._onDrag,this).on("dragend",this._onDragEnd,this),this._draggable.enable(),s.DomUtil.addClass(this._marker._icon,"leaflet-marker-draggable")},removeHooks:function(){this._draggable.off("dragstart",this._onDragStart,this).off("drag",this._onDrag,this).off("dragend",this._onDragEnd,this),this._draggable.disable(),s.DomUtil.removeClass(this._marker._icon,"leaflet-marker-draggable")},moved:function(){return this._draggable&&this._draggable._moved},_onDragStart:function(){this._marker.closePopup().fire("movestart").fire("dragstart")},_onDrag:function(){var t=this._marker,e=t._shadow,i=s.DomUtil.getPosition(t._icon),n=t._map.layerPointToLatLng(i);e&&s.DomUtil.setPosition(e,i),t._latlng=n,t.fire("move",{latlng:n}).fire("drag")},_onDragEnd:function(t){this._marker.fire("moveend").fire("dragend",t)}}),s.Control=s.Class.extend({options:{position:"topright"},initialize:function(t){s.setOptions(this,t)},getPosition:function(){return this.options.position},setPosition:function(t){var e=this._map;return e&&e.removeControl(this),this.options.position=t,e&&e.addControl(this),this},getContainer:function(){return this._container},addTo:function(t){this._map=t;var e=this._container=this.onAdd(t),i=this.getPosition(),n=t._controlCorners[i];return s.DomUtil.addClass(e,"leaflet-control"),-1!==i.indexOf("bottom")?n.insertBefore(e,n.firstChild):n.appendChild(e),this},removeFrom:function(t){var e=this.getPosition(),i=t._controlCorners[e];return i.removeChild(this._container),this._map=null,this.onRemove&&this.onRemove(t),this},_refocusOnMap:function(){this._map&&this._map.getContainer().focus()}}),s.control=function(t){return new s.Control(t)},s.Map.include({addControl:function(t){return t.addTo(this),this},removeControl:function(t){return t.removeFrom(this),this},_initControlPos:function(){function t(t,o){var a=i+t+" "+i+o;e[t+o]=s.DomUtil.create("div",a,n)}var e=this._controlCorners={},i="leaflet-",n=this._controlContainer=s.DomUtil.create("div",i+"control-container",this._container);t("top","left"),t("top","right"),t("bottom","left"),t("bottom","right")},_clearControlPos:function(){this._container.removeChild(this._controlContainer)}}),s.Control.Zoom=s.Control.extend({options:{position:"topleft",zoomInText:"+",zoomInTitle:"Zoom in",zoomOutText:"-",zoomOutTitle:"Zoom out"},onAdd:function(t){var e="leaflet-control-zoom",i=s.DomUtil.create("div",e+" leaflet-bar");return this._map=t,this._zoomInButton=this._createButton(this.options.zoomInText,this.options.zoomInTitle,e+"-in",i,this._zoomIn,this),this._zoomOutButton=this._createButton(this.options.zoomOutText,this.options.zoomOutTitle,e+"-out",i,this._zoomOut,this),this._updateDisabled(),t.on("zoomend zoomlevelschange",this._updateDisabled,this),i},onRemove:function(t){t.off("zoomend zoomlevelschange",this._updateDisabled,this)},_zoomIn:function(t){this._map.zoomIn(t.shiftKey?3:1)},_zoomOut:function(t){this._map.zoomOut(t.shiftKey?3:1)},_createButton:function(t,e,i,n,o,a){var r=s.DomUtil.create("a",i,n);r.innerHTML=t,r.href="#",r.title=e;var l=s.DomEvent.stopPropagation;return s.DomEvent.on(r,"click",l).on(r,"mousedown",l).on(r,"dblclick",l).on(r,"click",s.DomEvent.preventDefault).on(r,"click",o,a).on(r,"click",this._refocusOnMap,a),r},_updateDisabled:function(){var t=this._map,e="leaflet-disabled";s.DomUtil.removeClass(this._zoomInButton,e),s.DomUtil.removeClass(this._zoomOutButton,e),t._zoom===t.getMinZoom()&&s.DomUtil.addClass(this._zoomOutButton,e),t._zoom===t.getMaxZoom()&&s.DomUtil.addClass(this._zoomInButton,e)}}),s.Map.mergeOptions({zoomControl:!0}),s.Map.addInitHook(function(){this.options.zoomControl&&(this.zoomControl=new s.Control.Zoom,this.addControl(this.zoomControl))}),s.control.zoom=function(t){return new s.Control.Zoom(t)},s.Control.Attribution=s.Control.extend({options:{position:"bottomright",prefix:'<a href="http://leafletjs.com" title="A JS library for interactive maps">Leaflet</a>'},initialize:function(t){s.setOptions(this,t),this._attributions={}},onAdd:function(t){this._container=s.DomUtil.create("div","leaflet-control-attribution"),s.DomEvent.disableClickPropagation(this._container);for(var e in t._layers)t._layers[e].getAttribution&&this.addAttribution(t._layers[e].getAttribution());return t.on("layeradd",this._onLayerAdd,this).on("layerremove",this._onLayerRemove,this),this._update(),this._container},onRemove:function(t){t.off("layeradd",this._onLayerAdd).off("layerremove",this._onLayerRemove)},setPrefix:function(t){return this.options.prefix=t,this._update(),this},addAttribution:function(t){return t?(this._attributions[t]||(this._attributions[t]=0),this._attributions[t]++,this._update(),this):void 0},removeAttribution:function(t){return t?(this._attributions[t]&&(this._attributions[t]--,this._update()),this):void 0},_update:function(){if(this._map){var t=[];for(var e in this._attributions)this._attributions[e]&&t.push(e);var i=[];this.options.prefix&&i.push(this.options.prefix),t.length&&i.push(t.join(", ")),this._container.innerHTML=i.join(" | ")}},_onLayerAdd:function(t){t.layer.getAttribution&&this.addAttribution(t.layer.getAttribution())},_onLayerRemove:function(t){t.layer.getAttribution&&this.removeAttribution(t.layer.getAttribution())}}),s.Map.mergeOptions({attributionControl:!0}),s.Map.addInitHook(function(){this.options.attributionControl&&(this.attributionControl=(new s.Control.Attribution).addTo(this))}),s.control.attribution=function(t){return new s.Control.Attribution(t)},s.Control.Scale=s.Control.extend({options:{position:"bottomleft",maxWidth:100,metric:!0,imperial:!0,updateWhenIdle:!1},onAdd:function(t){this._map=t;var e="leaflet-control-scale",i=s.DomUtil.create("div",e),n=this.options;return this._addScales(n,e,i),t.on(n.updateWhenIdle?"moveend":"move",this._update,this),t.whenReady(this._update,this),i},onRemove:function(t){t.off(this.options.updateWhenIdle?"moveend":"move",this._update,this)},_addScales:function(t,e,i){t.metric&&(this._mScale=s.DomUtil.create("div",e+"-line",i)),t.imperial&&(this._iScale=s.DomUtil.create("div",e+"-line",i))},_update:function(){var t=this._map.getBounds(),e=t.getCenter().lat,i=6378137*Math.PI*Math.cos(e*Math.PI/180),n=i*(t.getNorthEast().lng-t.getSouthWest().lng)/180,o=this._map.getSize(),s=this.options,a=0;o.x>0&&(a=n*(s.maxWidth/o.x)),this._updateScales(s,a)},_updateScales:function(t,e){t.metric&&e&&this._updateMetric(e),t.imperial&&e&&this._updateImperial(e)},_updateMetric:function(t){var e=this._getRoundNum(t);this._mScale.style.width=this._getScaleWidth(e/t)+"px",this._mScale.innerHTML=1e3>e?e+" m":e/1e3+" km"},_updateImperial:function(t){var e,i,n,o=3.2808399*t,s=this._iScale;o>5280?(e=o/5280,i=this._getRoundNum(e),s.style.width=this._getScaleWidth(i/e)+"px",s.innerHTML=i+" mi"):(n=this._getRoundNum(o),s.style.width=this._getScaleWidth(n/o)+"px",s.innerHTML=n+" ft")},_getScaleWidth:function(t){return Math.round(this.options.maxWidth*t)-10},_getRoundNum:function(t){var e=Math.pow(10,(Math.floor(t)+"").length-1),i=t/e;return i=i>=10?10:i>=5?5:i>=3?3:i>=2?2:1,e*i}}),s.control.scale=function(t){return new s.Control.Scale(t)},s.Control.Layers=s.Control.extend({options:{collapsed:!0,position:"topright",autoZIndex:!0},initialize:function(t,e,i){s.setOptions(this,i),this._layers={},this._lastZIndex=0,this._handlingClick=!1;for(var n in t)this._addLayer(t[n],n);for(n in e)this._addLayer(e[n],n,!0)},onAdd:function(t){return this._initLayout(),this._update(),t.on("layeradd",this._onLayerChange,this).on("layerremove",this._onLayerChange,this),this._container},onRemove:function(t){t.off("layeradd",this._onLayerChange,this).off("layerremove",this._onLayerChange,this)},addBaseLayer:function(t,e){return this._addLayer(t,e),this._update(),this},addOverlay:function(t,e){return this._addLayer(t,e,!0),this._update(),this},removeLayer:function(t){var e=s.stamp(t);return delete this._layers[e],this._update(),this},_initLayout:function(){var t="leaflet-control-layers",e=this._container=s.DomUtil.create("div",t);e.setAttribute("aria-haspopup",!0),s.Browser.touch?s.DomEvent.on(e,"click",s.DomEvent.stopPropagation):s.DomEvent.disableClickPropagation(e).disableScrollPropagation(e);var i=this._form=s.DomUtil.create("form",t+"-list");if(this.options.collapsed){s.Browser.android||s.DomEvent.on(e,"mouseover",this._expand,this).on(e,"mouseout",this._collapse,this);var n=this._layersLink=s.DomUtil.create("a",t+"-toggle",e);n.href="#",n.title="Layers",s.Browser.touch?s.DomEvent.on(n,"click",s.DomEvent.stop).on(n,"click",this._expand,this):s.DomEvent.on(n,"focus",this._expand,this),s.DomEvent.on(i,"click",function(){setTimeout(s.bind(this._onInputClick,this),0)},this),this._map.on("click",this._collapse,this)}else this._expand();this._baseLayersList=s.DomUtil.create("div",t+"-base",i),this._separator=s.DomUtil.create("div",t+"-separator",i),this._overlaysList=s.DomUtil.create("div",t+"-overlays",i),e.appendChild(i)},_addLayer:function(t,e,i){var n=s.stamp(t);this._layers[n]={layer:t,name:e,overlay:i},this.options.autoZIndex&&t.setZIndex&&(this._lastZIndex++,t.setZIndex(this._lastZIndex))},_update:function(){if(this._container){this._baseLayersList.innerHTML="",this._overlaysList.innerHTML="";var t,e,i=!1,n=!1;for(t in this._layers)e=this._layers[t],this._addItem(e),n=n||e.overlay,i=i||!e.overlay;this._separator.style.display=n&&i?"":"none"}},_onLayerChange:function(t){var e=this._layers[s.stamp(t.layer)];if(e){this._handlingClick||this._update();var i=e.overlay?"layeradd"===t.type?"overlayadd":"overlayremove":"layeradd"===t.type?"baselayerchange":null;i&&this._map.fire(i,e)}},_createRadioElement:function(t,e){var n='<input type="radio" class="leaflet-control-layers-selector" name="'+t+'"';e&&(n+=' checked="checked"'),n+="/>";var o=i.createElement("div");return o.innerHTML=n,o.firstChild},_addItem:function(t){var e,n=i.createElement("label"),o=this._map.hasLayer(t.layer);t.overlay?(e=i.createElement("input"),e.type="checkbox",e.className="leaflet-control-layers-selector",e.defaultChecked=o):e=this._createRadioElement("leaflet-base-layers",o),e.layerId=s.stamp(t.layer),s.DomEvent.on(e,"click",this._onInputClick,this);var a=i.createElement("span");a.innerHTML=" "+t.name,n.appendChild(e),n.appendChild(a);var r=t.overlay?this._overlaysList:this._baseLayersList;return r.appendChild(n),n},_onInputClick:function(){var t,e,i,n=this._form.getElementsByTagName("input"),o=n.length;for(this._handlingClick=!0,t=0;o>t;t++)e=n[t],i=this._layers[e.layerId],e.checked&&!this._map.hasLayer(i.layer)?this._map.addLayer(i.layer):!e.checked&&this._map.hasLayer(i.layer)&&this._map.removeLayer(i.layer);this._handlingClick=!1,this._refocusOnMap()},_expand:function(){s.DomUtil.addClass(this._container,"leaflet-control-layers-expanded")},_collapse:function(){this._container.className=this._container.className.replace(" leaflet-control-layers-expanded","")}}),s.control.layers=function(t,e,i){return new s.Control.Layers(t,e,i)},s.PosAnimation=s.Class.extend({includes:s.Mixin.Events,run:function(t,e,i,n){this.stop(),this._el=t,this._inProgress=!0,this._newPos=e,this.fire("start"),t.style[s.DomUtil.TRANSITION]="all "+(i||.25)+"s cubic-bezier(0,0,"+(n||.5)+",1)",s.DomEvent.on(t,s.DomUtil.TRANSITION_END,this._onTransitionEnd,this),s.DomUtil.setPosition(t,e),s.Util.falseFn(t.offsetWidth),this._stepTimer=setInterval(s.bind(this._onStep,this),50)},stop:function(){this._inProgress&&(s.DomUtil.setPosition(this._el,this._getPos()),this._onTransitionEnd(),s.Util.falseFn(this._el.offsetWidth))},_onStep:function(){var t=this._getPos();return t?(this._el._leaflet_pos=t,this.fire("step"),void 0):(this._onTransitionEnd(),void 0)},_transformRe:/([-+]?(?:\d*\.)?\d+)\D*, ([-+]?(?:\d*\.)?\d+)\D*\)/,_getPos:function(){var e,i,n,o=this._el,a=t.getComputedStyle(o);if(s.Browser.any3d){if(n=a[s.DomUtil.TRANSFORM].match(this._transformRe),!n)return;e=parseFloat(n[1]),i=parseFloat(n[2])}else e=parseFloat(a.left),i=parseFloat(a.top);return new s.Point(e,i,!0)},_onTransitionEnd:function(){s.DomEvent.off(this._el,s.DomUtil.TRANSITION_END,this._onTransitionEnd,this),this._inProgress&&(this._inProgress=!1,this._el.style[s.DomUtil.TRANSITION]="",this._el._leaflet_pos=this._newPos,clearInterval(this._stepTimer),this.fire("step").fire("end"))}}),s.Map.include({setView:function(t,e,i){if(e=e===n?this._zoom:this._limitZoom(e),t=this._limitCenter(s.latLng(t),e,this.options.maxBounds),i=i||{},this._panAnim&&this._panAnim.stop(),this._loaded&&!i.reset&&i!==!0){i.animate!==n&&(i.zoom=s.extend({animate:i.animate},i.zoom),i.pan=s.extend({animate:i.animate},i.pan));var o=this._zoom!==e?this._tryAnimatedZoom&&this._tryAnimatedZoom(t,e,i.zoom):this._tryAnimatedPan(t,i.pan);if(o)return clearTimeout(this._sizeTimer),this}return this._resetView(t,e),this},panBy:function(t,e){if(t=s.point(t).round(),e=e||{},!t.x&&!t.y)return this;if(this._panAnim||(this._panAnim=new s.PosAnimation,this._panAnim.on({step:this._onPanTransitionStep,end:this._onPanTransitionEnd},this)),e.noMoveStart||this.fire("movestart"),e.animate!==!1){s.DomUtil.addClass(this._mapPane,"leaflet-pan-anim");var i=this._getMapPanePos().subtract(t);this._panAnim.run(this._mapPane,i,e.duration||.25,e.easeLinearity)}else this._rawPanBy(t),this.fire("move").fire("moveend");return this},_onPanTransitionStep:function(){this.fire("move")},_onPanTransitionEnd:function(){s.DomUtil.removeClass(this._mapPane,"leaflet-pan-anim"),this.fire("moveend")},_tryAnimatedPan:function(t,e){var i=this._getCenterOffset(t)._floor();return(e&&e.animate)===!0||this.getSize().contains(i)?(this.panBy(i,e),!0):!1}}),s.PosAnimation=s.DomUtil.TRANSITION?s.PosAnimation:s.PosAnimation.extend({run:function(t,e,i,n){this.stop(),this._el=t,this._inProgress=!0,this._duration=i||.25,this._easeOutPower=1/Math.max(n||.5,.2),this._startPos=s.DomUtil.getPosition(t),this._offset=e.subtract(this._startPos),this._startTime=+new Date,this.fire("start"),this._animate()},stop:function(){this._inProgress&&(this._step(),this._complete())},_animate:function(){this._animId=s.Util.requestAnimFrame(this._animate,this),this._step()},_step:function(){var t=+new Date-this._startTime,e=1e3*this._duration;e>t?this._runFrame(this._easeOut(t/e)):(this._runFrame(1),this._complete())},_runFrame:function(t){var e=this._startPos.add(this._offset.multiplyBy(t));s.DomUtil.setPosition(this._el,e),this.fire("step")},_complete:function(){s.Util.cancelAnimFrame(this._animId),this._inProgress=!1,this.fire("end")},_easeOut:function(t){return 1-Math.pow(1-t,this._easeOutPower)}}),s.Map.mergeOptions({zoomAnimation:!0,zoomAnimationThreshold:4}),s.DomUtil.TRANSITION&&s.Map.addInitHook(function(){this._zoomAnimated=this.options.zoomAnimation&&s.DomUtil.TRANSITION&&s.Browser.any3d&&!s.Browser.android23&&!s.Browser.mobileOpera,this._zoomAnimated&&s.DomEvent.on(this._mapPane,s.DomUtil.TRANSITION_END,this._catchTransitionEnd,this)}),s.Map.include(s.DomUtil.TRANSITION?{_catchTransitionEnd:function(t){this._animatingZoom&&t.propertyName.indexOf("transform")>=0&&this._onZoomTransitionEnd()},_nothingToAnimate:function(){return!this._container.getElementsByClassName("leaflet-zoom-animated").length},_tryAnimatedZoom:function(t,e,i){if(this._animatingZoom)return!0;if(i=i||{},!this._zoomAnimated||i.animate===!1||this._nothingToAnimate()||Math.abs(e-this._zoom)>this.options.zoomAnimationThreshold)return!1;var n=this.getZoomScale(e),o=this._getCenterOffset(t)._divideBy(1-1/n),s=this._getCenterLayerPoint()._add(o);return i.animate===!0||this.getSize().contains(o)?(this.fire("movestart").fire("zoomstart"),this._animateZoom(t,e,s,n,null,!0),!0):!1},_animateZoom:function(t,e,i,n,o,a,r){r||(this._animatingZoom=!0),s.DomUtil.addClass(this._mapPane,"leaflet-zoom-anim"),this._animateToCenter=t,this._animateToZoom=e,s.Draggable&&(s.Draggable._disabled=!0),s.Util.requestAnimFrame(function(){this.fire("zoomanim",{center:t,zoom:e,origin:i,scale:n,delta:o,backwards:a})},this)},_onZoomTransitionEnd:function(){this._animatingZoom=!1,s.DomUtil.removeClass(this._mapPane,"leaflet-zoom-anim"),this._resetView(this._animateToCenter,this._animateToZoom,!0,!0),s.Draggable&&(s.Draggable._disabled=!1)}}:{}),s.TileLayer.include({_animateZoom:function(t){this._animating||(this._animating=!0,this._prepareBgBuffer());var e=this._bgBuffer,i=s.DomUtil.TRANSFORM,n=t.delta?s.DomUtil.getTranslateString(t.delta):e.style[i],o=s.DomUtil.getScaleString(t.scale,t.origin);e.style[i]=t.backwards?o+" "+n:n+" "+o},_endZoomAnim:function(){var t=this._tileContainer,e=this._bgBuffer;t.style.visibility="",t.parentNode.appendChild(t),s.Util.falseFn(e.offsetWidth),this._animating=!1},_clearBgBuffer:function(){var t=this._map;!t||t._animatingZoom||t.touchZoom._zooming||(this._bgBuffer.innerHTML="",this._bgBuffer.style[s.DomUtil.TRANSFORM]="")},_prepareBgBuffer:function(){var t=this._tileContainer,e=this._bgBuffer,i=this._getLoadedTilesPercentage(e),n=this._getLoadedTilesPercentage(t);return e&&i>.5&&.5>n?(t.style.visibility="hidden",this._stopLoadingImages(t),void 0):(e.style.visibility="hidden",e.style[s.DomUtil.TRANSFORM]="",this._tileContainer=e,e=this._bgBuffer=t,this._stopLoadingImages(e),clearTimeout(this._clearBgBufferTimer),void 0)},_getLoadedTilesPercentage:function(t){var e,i,n=t.getElementsByTagName("img"),o=0;for(e=0,i=n.length;i>e;e++)n[e].complete&&o++;return o/i},_stopLoadingImages:function(t){var e,i,n,o=Array.prototype.slice.call(t.getElementsByTagName("img"));for(e=0,i=o.length;i>e;e++)n=o[e],n.complete||(n.onload=s.Util.falseFn,n.onerror=s.Util.falseFn,n.src=s.Util.emptyImageUrl,n.parentNode.removeChild(n))}}),s.Map.include({_defaultLocateOptions:{watch:!1,setView:!1,maxZoom:1/0,timeout:1e4,maximumAge:0,enableHighAccuracy:!1},locate:function(t){if(t=this._locateOptions=s.extend(this._defaultLocateOptions,t),!navigator.geolocation)return this._handleGeolocationError({code:0,message:"Geolocation not supported."}),this;var e=s.bind(this._handleGeolocationResponse,this),i=s.bind(this._handleGeolocationError,this);return t.watch?this._locationWatchId=navigator.geolocation.watchPosition(e,i,t):navigator.geolocation.getCurrentPosition(e,i,t),this},stopLocate:function(){return navigator.geolocation&&navigator.geolocation.clearWatch(this._locationWatchId),this._locateOptions&&(this._locateOptions.setView=!1),this},_handleGeolocationError:function(t){var e=t.code,i=t.message||(1===e?"permission denied":2===e?"position unavailable":"timeout");this._locateOptions.setView&&!this._loaded&&this.fitWorld(),this.fire("locationerror",{code:e,message:"Geolocation error: "+i+"."})},_handleGeolocationResponse:function(t){var e=t.coords.latitude,i=t.coords.longitude,n=new s.LatLng(e,i),o=180*t.coords.accuracy/40075017,a=o/Math.cos(s.LatLng.DEG_TO_RAD*e),r=s.latLngBounds([e-o,i-a],[e+o,i+a]),l=this._locateOptions;if(l.setView){var h=Math.min(this.getBoundsZoom(r),l.maxZoom);this.setView(n,h)}var u={latlng:n,bounds:r,timestamp:t.timestamp};for(var c in t.coords)"number"==typeof t.coords[c]&&(u[c]=t.coords[c]);this.fire("locationfound",u)}})}(window,document)},{}],3:[function(t,e,i){!function(t,e){if("object"==typeof i&&i)e(i);else{var n={};e(n),"function"==typeof define&&define.amd?define(n):t.Mustache=n}}(this,function(t){function e(t,e){return L.call(t,e)}function i(t){return!e(_,t)}function n(t){return"function"==typeof t}function o(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function s(t){return String(t).replace(/[&<>"'\/]/g,function(t){return P[t]})}function a(t){this.string=t,this.tail=t,this.pos=0}function r(t,e){this.view=null==t?{}:t,this.parent=e,this._cache={".":this.view}}function l(){this.clearCache()}function h(e,i,o,s){function a(t){return i.render(t,o)}for(var r,l,u,c="",p=0,d=e.length;d>p;++p)switch(r=e[p],l=r[1],r[0]){case"#":if(u=o.lookup(l),"object"==typeof u||"string"==typeof u)if(T(u))for(var m=0,f=u.length;f>m;++m)c+=h(r[4],i,o.push(u[m]),s);else u&&(c+=h(r[4],i,o.push(u),s));else if(n(u)){var _=null==s?null:s.slice(r[3],r[5]);u=u.call(o.view,_,a),null!=u&&(c+=u)}else u&&(c+=h(r[4],i,o,s));break;case"^":u=o.lookup(l),(!u||T(u)&&0===u.length)&&(c+=h(r[4],i,o,s));break;case">":u=i.getPartial(l),n(u)&&(c+=u(o));break;case"&":u=o.lookup(l),null!=u&&(c+=u);break;case"name":u=o.lookup(l),null!=u&&(c+=t.escape(u));break;case"text":c+=l}return c}function u(t){for(var e,i=[],n=i,o=[],s=0,a=t.length;a>s;++s)switch(e=t[s],e[0]){case"#":case"^":o.push(e),n.push(e),n=e[4]=[];break;case"/":var r=o.pop();r[5]=e[2],n=o.length>0?o[o.length-1][4]:i;break;default:n.push(e)}return i}function c(t){for(var e,i,n=[],o=0,s=t.length;s>o;++o)e=t[o],e&&("text"===e[0]&&i&&"text"===i[0]?(i[1]+=e[1],i[3]=e[3]):(i=e,n.push(e)));return n}function p(t){return[new RegExp(o(t[0])+"\\s*"),new RegExp("\\s*"+o(t[1]))]}function d(e,n){function s(){if(w&&!C)for(;x.length;)delete E[x.pop()];
  else x=[];w=!1,C=!1}if(e=e||"",n=n||t.tags,"string"==typeof n&&(n=n.split(f)),2!==n.length)throw new Error("Invalid tags: "+n.join(", "));for(var r,l,h,d,_,L,b=p(n),T=new a(e),P=[],E=[],x=[],w=!1,C=!1;!T.eos();){if(r=T.pos,h=T.scanUntil(b[0]))for(var M=0,D=h.length;D>M;++M)d=h.charAt(M),i(d)?x.push(E.length):C=!0,E.push(["text",d,r,r+1]),r+=1,"\n"==d&&s();if(!T.scan(b[0]))break;if(w=!0,l=T.scan(y)||"name",T.scan(m),"="===l?(h=T.scanUntil(g),T.scan(g),T.scanUntil(b[1])):"{"===l?(h=T.scanUntil(new RegExp("\\s*"+o("}"+n[1]))),T.scan(v),T.scanUntil(b[1]),l="&"):h=T.scanUntil(b[1]),!T.scan(b[1]))throw new Error("Unclosed tag at "+T.pos);if(_=[l,h,r,T.pos],E.push(_),"#"===l||"^"===l)P.push(_);else if("/"===l){if(L=P.pop(),!L)throw new Error('Unopened section "'+h+'" at '+r);if(L[1]!==h)throw new Error('Unclosed section "'+L[1]+'" at '+r)}else if("name"===l||"{"===l||"&"===l)C=!0;else if("="===l){if(n=h.split(f),2!==n.length)throw new Error("Invalid tags at "+r+": "+n.join(", "));b=p(n)}}if(L=P.pop())throw new Error('Unclosed section "'+L[1]+'" at '+T.pos);return u(c(E))}var m=/\s*/,f=/\s+/,_=/\S/,g=/\s*=/,v=/\s*\}/,y=/#|\^|\/|>|\{|&|=|!/,L=RegExp.prototype.test,b=Object.prototype.toString,T=Array.isArray||function(t){return"[object Array]"===b.call(t)},P={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;"};a.prototype.eos=function(){return""===this.tail},a.prototype.scan=function(t){var e=this.tail.match(t);if(e&&0===e.index){var i=e[0];return this.tail=this.tail.substring(i.length),this.pos+=i.length,i}return""},a.prototype.scanUntil=function(t){var e,i=this.tail.search(t);switch(i){case-1:e=this.tail,this.tail="";break;case 0:e="";break;default:e=this.tail.substring(0,i),this.tail=this.tail.substring(i)}return this.pos+=e.length,e},r.make=function(t){return t instanceof r?t:new r(t)},r.prototype.push=function(t){return new r(t,this)},r.prototype.lookup=function(t){var e;if(t in this._cache)e=this._cache[t];else{for(var i=this;i;){if(t.indexOf(".")>0){e=i.view;for(var o=t.split("."),s=0;null!=e&&s<o.length;)e=e[o[s++]]}else e=i.view[t];if(null!=e)break;i=i.parent}this._cache[t]=e}return n(e)&&(e=e.call(this.view)),e},l.prototype.clearCache=function(){this._cache={},this._partialCache={}},l.prototype.compile=function(e,i){var n=this._cache[e];if(!n){var o=t.parse(e,i);n=this._cache[e]=this.compileTokens(o,e)}return n},l.prototype.compilePartial=function(t,e,i){var n=this.compile(e,i);return this._partialCache[t]=n,n},l.prototype.getPartial=function(t){return t in this._partialCache||!this._loadPartial||this.compilePartial(t,this._loadPartial(t)),this._partialCache[t]},l.prototype.compileTokens=function(t,e){var i=this;return function(o,s){if(s)if(n(s))i._loadPartial=s;else for(var a in s)i.compilePartial(a,s[a]);return h(t,i,r.make(o),e)}},l.prototype.render=function(t,e,i){return this.compile(t)(e,i)},t.name="mustache.js",t.version="0.7.3",t.tags=["{{","}}"],t.Scanner=a,t.Context=r,t.Writer=l,t.parse=d,t.escape=s;var E=new l;t.clearCache=function(){return E.clearCache()},t.compile=function(t,e){return E.compile(t,e)},t.compilePartial=function(t,e,i){return E.compilePartial(t,e,i)},t.compileTokens=function(t,e){return E.compileTokens(t,e)},t.render=function(t,e,i){return E.render(t,e,i)},t.to_html=function(e,i,o,s){var a=t.render(e,i,o);return n(s)?(s(a),void 0):a}})},{}],4:[function(t,e){function i(t){"use strict";return/^https?/.test(t.getScheme())?t.toString():/^mailto?/.test(t.getScheme())?t.toString():"data"==t.getScheme()&&/^image/.test(t.getPath())?t.toString():void 0}function n(t){return t}var o=t("./sanitizer-bundle.js");e.exports=function(t){return t?o(t,i,n):""}},{"./sanitizer-bundle.js":5}],5:[function(t,e){var i=function(){function t(t){var e=(""+t).match(d);return e?new l(h(e[1]),h(e[2]),h(e[3]),h(e[4]),h(e[5]),h(e[6]),h(e[7])):null}function e(t,e,s,a,r,h,u){var c=new l(n(t,m),n(e,m),i(s),a>0?a.toString():null,n(r,f),null,i(u));return h&&("string"==typeof h?c.setRawQuery(h.replace(/[^?&=0-9A-Za-z_\-~.%]/g,o)):c.setAllParameters(h)),c}function i(t){return"string"==typeof t?encodeURIComponent(t):null}function n(t,e){return"string"==typeof t?encodeURI(t).replace(e,o):null}function o(t){var e=t.charCodeAt(0);return"%"+"0123456789ABCDEF".charAt(e>>4&15)+"0123456789ABCDEF".charAt(15&e)}function s(t){return t.replace(/(^|\/)\.(?:\/|$)/g,"$1").replace(/\/{2,}/g,"/")}function a(t){if(null===t)return null;for(var e,i=s(t),n=c;(e=i.replace(n,"$1"))!=i;i=e);return i}function r(t,e){var i=t.clone(),n=e.hasScheme();n?i.setRawScheme(e.getRawScheme()):n=e.hasCredentials(),n?i.setRawCredentials(e.getRawCredentials()):n=e.hasDomain(),n?i.setRawDomain(e.getRawDomain()):n=e.hasPort();var o=e.getRawPath(),s=a(o);if(n)i.setPort(e.getPort()),s=s&&s.replace(p,"");else if(n=!!o){if(47!==s.charCodeAt(0)){var r=a(i.getRawPath()||"").replace(p,""),l=r.lastIndexOf("/")+1;s=a((l?r.substring(0,l):"")+a(o)).replace(p,"")}}else s=s&&s.replace(p,""),s!==o&&i.setRawPath(s);return n?i.setRawPath(s):n=e.hasQuery(),n?i.setRawQuery(e.getRawQuery()):n=e.hasFragment(),n&&i.setRawFragment(e.getRawFragment()),i}function l(t,e,i,n,o,s,a){this.scheme_=t,this.credentials_=e,this.domain_=i,this.port_=n,this.path_=o,this.query_=s,this.fragment_=a,this.paramCache_=null}function h(t){return"string"==typeof t&&t.length>0?t:null}var u=new RegExp("(/|^)(?:[^./][^/]*|\\.{2,}(?:[^./][^/]*)|\\.{3,}[^/]*)/\\.\\.(?:/|$)"),c=new RegExp(u),p=/^(?:\.\.\/)*(?:\.\.$)?/;l.prototype.toString=function(){var t=[];return null!==this.scheme_&&t.push(this.scheme_,":"),null!==this.domain_&&(t.push("//"),null!==this.credentials_&&t.push(this.credentials_,"@"),t.push(this.domain_),null!==this.port_&&t.push(":",this.port_.toString())),null!==this.path_&&t.push(this.path_),null!==this.query_&&t.push("?",this.query_),null!==this.fragment_&&t.push("#",this.fragment_),t.join("")},l.prototype.clone=function(){return new l(this.scheme_,this.credentials_,this.domain_,this.port_,this.path_,this.query_,this.fragment_)},l.prototype.getScheme=function(){return this.scheme_&&decodeURIComponent(this.scheme_).toLowerCase()},l.prototype.getRawScheme=function(){return this.scheme_},l.prototype.setScheme=function(t){return this.scheme_=n(t,m),this},l.prototype.setRawScheme=function(t){return this.scheme_=t?t:null,this},l.prototype.hasScheme=function(){return null!==this.scheme_},l.prototype.getCredentials=function(){return this.credentials_&&decodeURIComponent(this.credentials_)},l.prototype.getRawCredentials=function(){return this.credentials_},l.prototype.setCredentials=function(t){return this.credentials_=n(t,m),this},l.prototype.setRawCredentials=function(t){return this.credentials_=t?t:null,this},l.prototype.hasCredentials=function(){return null!==this.credentials_},l.prototype.getDomain=function(){return this.domain_&&decodeURIComponent(this.domain_)},l.prototype.getRawDomain=function(){return this.domain_},l.prototype.setDomain=function(t){return this.setRawDomain(t&&encodeURIComponent(t))},l.prototype.setRawDomain=function(t){return this.domain_=t?t:null,this.setRawPath(this.path_)},l.prototype.hasDomain=function(){return null!==this.domain_},l.prototype.getPort=function(){return this.port_&&decodeURIComponent(this.port_)},l.prototype.setPort=function(t){if(t){if(t=Number(t),t!==(65535&t))throw new Error("Bad port number "+t);this.port_=""+t}else this.port_=null;return this},l.prototype.hasPort=function(){return null!==this.port_},l.prototype.getPath=function(){return this.path_&&decodeURIComponent(this.path_)},l.prototype.getRawPath=function(){return this.path_},l.prototype.setPath=function(t){return this.setRawPath(n(t,f))},l.prototype.setRawPath=function(t){return t?(t=String(t),this.path_=!this.domain_||/^\//.test(t)?t:"/"+t):this.path_=null,this},l.prototype.hasPath=function(){return null!==this.path_},l.prototype.getQuery=function(){return this.query_&&decodeURIComponent(this.query_).replace(/\+/g," ")},l.prototype.getRawQuery=function(){return this.query_},l.prototype.setQuery=function(t){return this.paramCache_=null,this.query_=i(t),this},l.prototype.setRawQuery=function(t){return this.paramCache_=null,this.query_=t?t:null,this},l.prototype.hasQuery=function(){return null!==this.query_},l.prototype.setAllParameters=function(t){if("object"==typeof t&&!(t instanceof Array)&&(t instanceof Object||"[object Array]"!==Object.prototype.toString.call(t))){var e=[],i=-1;for(var n in t){var o=t[n];"string"==typeof o&&(e[++i]=n,e[++i]=o)}t=e}this.paramCache_=null;for(var s=[],a="",r=0;r<t.length;){var n=t[r++],o=t[r++];s.push(a,encodeURIComponent(n.toString())),a="&",o&&s.push("=",encodeURIComponent(o.toString()))}return this.query_=s.join(""),this},l.prototype.checkParameterCache_=function(){if(!this.paramCache_){var t=this.query_;if(t){for(var e=t.split(/[&\?]/),i=[],n=-1,o=0;o<e.length;++o){var s=e[o].match(/^([^=]*)(?:=(.*))?$/);i[++n]=decodeURIComponent(s[1]).replace(/\+/g," "),i[++n]=decodeURIComponent(s[2]||"").replace(/\+/g," ")}this.paramCache_=i}else this.paramCache_=[]}},l.prototype.setParameterValues=function(t,e){"string"==typeof e&&(e=[e]),this.checkParameterCache_();for(var i=0,n=this.paramCache_,o=[],s=0;s<n.length;s+=2)t===n[s]?i<e.length&&o.push(t,e[i++]):o.push(n[s],n[s+1]);for(;i<e.length;)o.push(t,e[i++]);return this.setAllParameters(o),this},l.prototype.removeParameter=function(t){return this.setParameterValues(t,[])},l.prototype.getAllParameters=function(){return this.checkParameterCache_(),this.paramCache_.slice(0,this.paramCache_.length)},l.prototype.getParameterValues=function(t){this.checkParameterCache_();for(var e=[],i=0;i<this.paramCache_.length;i+=2)t===this.paramCache_[i]&&e.push(this.paramCache_[i+1]);return e},l.prototype.getParameterMap=function(){this.checkParameterCache_();for(var t={},e=0;e<this.paramCache_.length;e+=2){var i=this.paramCache_[e++],n=this.paramCache_[e++];i in t?t[i].push(n):t[i]=[n]}return t},l.prototype.getParameterValue=function(t){this.checkParameterCache_();for(var e=0;e<this.paramCache_.length;e+=2)if(t===this.paramCache_[e])return this.paramCache_[e+1];return null},l.prototype.getFragment=function(){return this.fragment_&&decodeURIComponent(this.fragment_)},l.prototype.getRawFragment=function(){return this.fragment_},l.prototype.setFragment=function(t){return this.fragment_=t?encodeURIComponent(t):null,this},l.prototype.setRawFragment=function(t){return this.fragment_=t?t:null,this},l.prototype.hasFragment=function(){return null!==this.fragment_};var d=new RegExp("^(?:([^:/?#]+):)?(?://(?:([^/?#]*)@)?([^/?#:@]*)(?::([0-9]+))?)?([^?#]+)?(?:\\?([^#]*))?(?:#(.*))?$"),m=/[#\/\?@]/g,f=/[\#\?]/g;return l.parse=t,l.create=e,l.resolve=r,l.collapse_dots=a,l.utils={mimeTypeOf:function(e){var i=t(e);return/\.html$/.test(i.getPath())?"text/html":"application/javascript"},resolve:function(e,i){return e?r(t(e),t(i)).toString():""+i}},l}(),n={};if(n.atype={NONE:0,URI:1,URI_FRAGMENT:11,SCRIPT:2,STYLE:3,HTML:12,ID:4,IDREF:5,IDREFS:6,GLOBAL_NAME:7,LOCAL_NAME:8,CLASSES:9,FRAME_TARGET:10,MEDIA_QUERY:13},n.atype=n.atype,n.ATTRIBS={"*::class":9,"*::dir":0,"*::draggable":0,"*::hidden":0,"*::id":4,"*::inert":0,"*::itemprop":0,"*::itemref":6,"*::itemscope":0,"*::lang":0,"*::onblur":2,"*::onchange":2,"*::onclick":2,"*::ondblclick":2,"*::onfocus":2,"*::onkeydown":2,"*::onkeypress":2,"*::onkeyup":2,"*::onload":2,"*::onmousedown":2,"*::onmousemove":2,"*::onmouseout":2,"*::onmouseover":2,"*::onmouseup":2,"*::onreset":2,"*::onscroll":2,"*::onselect":2,"*::onsubmit":2,"*::onunload":2,"*::spellcheck":0,"*::style":3,"*::title":0,"*::translate":0,"a::accesskey":0,"a::coords":0,"a::href":1,"a::hreflang":0,"a::name":7,"a::onblur":2,"a::onfocus":2,"a::shape":0,"a::tabindex":0,"a::target":10,"a::type":0,"area::accesskey":0,"area::alt":0,"area::coords":0,"area::href":1,"area::nohref":0,"area::onblur":2,"area::onfocus":2,"area::shape":0,"area::tabindex":0,"area::target":10,"audio::controls":0,"audio::loop":0,"audio::mediagroup":5,"audio::muted":0,"audio::preload":0,"bdo::dir":0,"blockquote::cite":1,"br::clear":0,"button::accesskey":0,"button::disabled":0,"button::name":8,"button::onblur":2,"button::onfocus":2,"button::tabindex":0,"button::type":0,"button::value":0,"canvas::height":0,"canvas::width":0,"caption::align":0,"col::align":0,"col::char":0,"col::charoff":0,"col::span":0,"col::valign":0,"col::width":0,"colgroup::align":0,"colgroup::char":0,"colgroup::charoff":0,"colgroup::span":0,"colgroup::valign":0,"colgroup::width":0,"command::checked":0,"command::command":5,"command::disabled":0,"command::icon":1,"command::label":0,"command::radiogroup":0,"command::type":0,"data::value":0,"del::cite":1,"del::datetime":0,"details::open":0,"dir::compact":0,"div::align":0,"dl::compact":0,"fieldset::disabled":0,"font::color":0,"font::face":0,"font::size":0,"form::accept":0,"form::action":1,"form::autocomplete":0,"form::enctype":0,"form::method":0,"form::name":7,"form::novalidate":0,"form::onreset":2,"form::onsubmit":2,"form::target":10,"h1::align":0,"h2::align":0,"h3::align":0,"h4::align":0,"h5::align":0,"h6::align":0,"hr::align":0,"hr::noshade":0,"hr::size":0,"hr::width":0,"iframe::align":0,"iframe::frameborder":0,"iframe::height":0,"iframe::marginheight":0,"iframe::marginwidth":0,"iframe::width":0,"img::align":0,"img::alt":0,"img::border":0,"img::height":0,"img::hspace":0,"img::ismap":0,"img::name":7,"img::src":1,"img::usemap":11,"img::vspace":0,"img::width":0,"input::accept":0,"input::accesskey":0,"input::align":0,"input::alt":0,"input::autocomplete":0,"input::checked":0,"input::disabled":0,"input::inputmode":0,"input::ismap":0,"input::list":5,"input::max":0,"input::maxlength":0,"input::min":0,"input::multiple":0,"input::name":8,"input::onblur":2,"input::onchange":2,"input::onfocus":2,"input::onselect":2,"input::placeholder":0,"input::readonly":0,"input::required":0,"input::size":0,"input::src":1,"input::step":0,"input::tabindex":0,"input::type":0,"input::usemap":11,"input::value":0,"ins::cite":1,"ins::datetime":0,"label::accesskey":0,"label::for":5,"label::onblur":2,"label::onfocus":2,"legend::accesskey":0,"legend::align":0,"li::type":0,"li::value":0,"map::name":7,"menu::compact":0,"menu::label":0,"menu::type":0,"meter::high":0,"meter::low":0,"meter::max":0,"meter::min":0,"meter::value":0,"ol::compact":0,"ol::reversed":0,"ol::start":0,"ol::type":0,"optgroup::disabled":0,"optgroup::label":0,"option::disabled":0,"option::label":0,"option::selected":0,"option::value":0,"output::for":6,"output::name":8,"p::align":0,"pre::width":0,"progress::max":0,"progress::min":0,"progress::value":0,"q::cite":1,"select::autocomplete":0,"select::disabled":0,"select::multiple":0,"select::name":8,"select::onblur":2,"select::onchange":2,"select::onfocus":2,"select::required":0,"select::size":0,"select::tabindex":0,"source::type":0,"table::align":0,"table::bgcolor":0,"table::border":0,"table::cellpadding":0,"table::cellspacing":0,"table::frame":0,"table::rules":0,"table::summary":0,"table::width":0,"tbody::align":0,"tbody::char":0,"tbody::charoff":0,"tbody::valign":0,"td::abbr":0,"td::align":0,"td::axis":0,"td::bgcolor":0,"td::char":0,"td::charoff":0,"td::colspan":0,"td::headers":6,"td::height":0,"td::nowrap":0,"td::rowspan":0,"td::scope":0,"td::valign":0,"td::width":0,"textarea::accesskey":0,"textarea::autocomplete":0,"textarea::cols":0,"textarea::disabled":0,"textarea::inputmode":0,"textarea::name":8,"textarea::onblur":2,"textarea::onchange":2,"textarea::onfocus":2,"textarea::onselect":2,"textarea::placeholder":0,"textarea::readonly":0,"textarea::required":0,"textarea::rows":0,"textarea::tabindex":0,"textarea::wrap":0,"tfoot::align":0,"tfoot::char":0,"tfoot::charoff":0,"tfoot::valign":0,"th::abbr":0,"th::align":0,"th::axis":0,"th::bgcolor":0,"th::char":0,"th::charoff":0,"th::colspan":0,"th::headers":6,"th::height":0,"th::nowrap":0,"th::rowspan":0,"th::scope":0,"th::valign":0,"th::width":0,"thead::align":0,"thead::char":0,"thead::charoff":0,"thead::valign":0,"tr::align":0,"tr::bgcolor":0,"tr::char":0,"tr::charoff":0,"tr::valign":0,"track::default":0,"track::kind":0,"track::label":0,"track::srclang":0,"ul::compact":0,"ul::type":0,"video::controls":0,"video::height":0,"video::loop":0,"video::mediagroup":5,"video::muted":0,"video::poster":1,"video::preload":0,"video::width":0},n.ATTRIBS=n.ATTRIBS,n.eflags={OPTIONAL_ENDTAG:1,EMPTY:2,CDATA:4,RCDATA:8,UNSAFE:16,FOLDABLE:32,SCRIPT:64,STYLE:128,VIRTUALIZED:256},n.eflags=n.eflags,n.ELEMENTS={a:0,abbr:0,acronym:0,address:0,applet:272,area:2,article:0,aside:0,audio:0,b:0,base:274,basefont:274,bdi:0,bdo:0,big:0,blockquote:0,body:305,br:2,button:0,canvas:0,caption:0,center:0,cite:0,code:0,col:2,colgroup:1,command:2,data:0,datalist:0,dd:1,del:0,details:0,dfn:0,dialog:272,dir:0,div:0,dl:0,dt:1,em:0,fieldset:0,figcaption:0,figure:0,font:0,footer:0,form:0,frame:274,frameset:272,h1:0,h2:0,h3:0,h4:0,h5:0,h6:0,head:305,header:0,hgroup:0,hr:2,html:305,i:0,iframe:4,img:2,input:2,ins:0,isindex:274,kbd:0,keygen:274,label:0,legend:0,li:1,link:274,map:0,mark:0,menu:0,meta:274,meter:0,nav:0,nobr:0,noembed:276,noframes:276,noscript:276,object:272,ol:0,optgroup:0,option:1,output:0,p:1,param:274,pre:0,progress:0,q:0,s:0,samp:0,script:84,section:0,select:0,small:0,source:2,span:0,strike:0,strong:0,style:148,sub:0,summary:0,sup:0,table:0,tbody:1,td:1,textarea:8,tfoot:1,th:1,thead:1,time:0,title:280,tr:1,track:2,tt:0,u:0,ul:0,"var":0,video:0,wbr:2},n.ELEMENTS=n.ELEMENTS,n.ELEMENT_DOM_INTERFACES={a:"HTMLAnchorElement",abbr:"HTMLElement",acronym:"HTMLElement",address:"HTMLElement",applet:"HTMLAppletElement",area:"HTMLAreaElement",article:"HTMLElement",aside:"HTMLElement",audio:"HTMLAudioElement",b:"HTMLElement",base:"HTMLBaseElement",basefont:"HTMLBaseFontElement",bdi:"HTMLElement",bdo:"HTMLElement",big:"HTMLElement",blockquote:"HTMLQuoteElement",body:"HTMLBodyElement",br:"HTMLBRElement",button:"HTMLButtonElement",canvas:"HTMLCanvasElement",caption:"HTMLTableCaptionElement",center:"HTMLElement",cite:"HTMLElement",code:"HTMLElement",col:"HTMLTableColElement",colgroup:"HTMLTableColElement",command:"HTMLCommandElement",data:"HTMLElement",datalist:"HTMLDataListElement",dd:"HTMLElement",del:"HTMLModElement",details:"HTMLDetailsElement",dfn:"HTMLElement",dialog:"HTMLDialogElement",dir:"HTMLDirectoryElement",div:"HTMLDivElement",dl:"HTMLDListElement",dt:"HTMLElement",em:"HTMLElement",fieldset:"HTMLFieldSetElement",figcaption:"HTMLElement",figure:"HTMLElement",font:"HTMLFontElement",footer:"HTMLElement",form:"HTMLFormElement",frame:"HTMLFrameElement",frameset:"HTMLFrameSetElement",h1:"HTMLHeadingElement",h2:"HTMLHeadingElement",h3:"HTMLHeadingElement",h4:"HTMLHeadingElement",h5:"HTMLHeadingElement",h6:"HTMLHeadingElement",head:"HTMLHeadElement",header:"HTMLElement",hgroup:"HTMLElement",hr:"HTMLHRElement",html:"HTMLHtmlElement",i:"HTMLElement",iframe:"HTMLIFrameElement",img:"HTMLImageElement",input:"HTMLInputElement",ins:"HTMLModElement",isindex:"HTMLUnknownElement",kbd:"HTMLElement",keygen:"HTMLKeygenElement",label:"HTMLLabelElement",legend:"HTMLLegendElement",li:"HTMLLIElement",link:"HTMLLinkElement",map:"HTMLMapElement",mark:"HTMLElement",menu:"HTMLMenuElement",meta:"HTMLMetaElement",meter:"HTMLMeterElement",nav:"HTMLElement",nobr:"HTMLElement",noembed:"HTMLElement",noframes:"HTMLElement",noscript:"HTMLElement",object:"HTMLObjectElement",ol:"HTMLOListElement",optgroup:"HTMLOptGroupElement",option:"HTMLOptionElement",output:"HTMLOutputElement",p:"HTMLParagraphElement",param:"HTMLParamElement",pre:"HTMLPreElement",progress:"HTMLProgressElement",q:"HTMLQuoteElement",s:"HTMLElement",samp:"HTMLElement",script:"HTMLScriptElement",section:"HTMLElement",select:"HTMLSelectElement",small:"HTMLElement",source:"HTMLSourceElement",span:"HTMLSpanElement",strike:"HTMLElement",strong:"HTMLElement",style:"HTMLStyleElement",sub:"HTMLElement",summary:"HTMLElement",sup:"HTMLElement",table:"HTMLTableElement",tbody:"HTMLTableSectionElement",td:"HTMLTableDataCellElement",textarea:"HTMLTextAreaElement",tfoot:"HTMLTableSectionElement",th:"HTMLTableHeaderCellElement",thead:"HTMLTableSectionElement",time:"HTMLTimeElement",title:"HTMLTitleElement",tr:"HTMLTableRowElement",track:"HTMLTrackElement",tt:"HTMLElement",u:"HTMLElement",ul:"HTMLUListElement","var":"HTMLElement",video:"HTMLVideoElement",wbr:"HTMLElement"},n.ELEMENT_DOM_INTERFACES=n.ELEMENT_DOM_INTERFACES,n.ueffects={NOT_LOADED:0,SAME_DOCUMENT:1,NEW_DOCUMENT:2},n.ueffects=n.ueffects,n.URIEFFECTS={"a::href":2,"area::href":2,"blockquote::cite":0,"command::icon":1,"del::cite":0,"form::action":2,"img::src":1,"input::src":1,"ins::cite":0,"q::cite":0,"video::poster":1},n.URIEFFECTS=n.URIEFFECTS,n.ltypes={UNSANDBOXED:2,SANDBOXED:1,DATA:0},n.ltypes=n.ltypes,n.LOADERTYPES={"a::href":2,"area::href":2,"blockquote::cite":2,"command::icon":1,"del::cite":2,"form::action":2,"img::src":1,"input::src":1,"ins::cite":2,"q::cite":2,"video::poster":1},n.LOADERTYPES=n.LOADERTYPES,"i"!=="I".toLowerCase())throw"I/i problem";var o=function(t){function e(t){if(k.hasOwnProperty(t))return k[t];var e=t.match(A);if(e)return String.fromCharCode(parseInt(e[1],10));if(e=t.match(U))return String.fromCharCode(parseInt(e[1],16));if(I&&O.test(t)){I.innerHTML="&"+t+";";var i=I.textContent;return k[t]=i,i}return"&"+t+";"}function n(t,i){return e(i)}function o(t){return t.replace(R,"")}function s(t){return t.replace(z,n)}function a(t){return(""+t).replace(N,"&amp;").replace(Z,"&lt;").replace(j,"&gt;").replace(F,"&#34;")}function r(t){return t.replace(H,"&amp;$1").replace(Z,"&lt;").replace(j,"&gt;")}function l(t){var e={cdata:t.cdata||t.cdata,comment:t.comment||t.comment,endDoc:t.endDoc||t.endDoc,endTag:t.endTag||t.endTag,pcdata:t.pcdata||t.pcdata,rcdata:t.rcdata||t.rcdata,startDoc:t.startDoc||t.startDoc,startTag:t.startTag||t.startTag};return function(t,i){return h(t,e,i)}}function h(t,e,i){var n=p(t),o={noMoreGT:!1,noMoreEndComments:!1};c(e,n,0,o,i)}function u(t,e,i,n,o){return function(){c(t,e,i,n,o)}}function c(e,i,n,o,s){try{e.startDoc&&0==n&&e.startDoc(s);for(var a,r,l,h=n,c=i.length;c>h;){var p=i[h++],_=i[h];switch(p){case"&":B.test(_)?(e.pcdata&&e.pcdata("&"+_,s,V,u(e,i,h,o,s)),h++):e.pcdata&&e.pcdata("&amp;",s,V,u(e,i,h,o,s));break;case"</":(a=/^([-\w:]+)[^\'\"]*/.exec(_))?a[0].length===_.length&&">"===i[h+1]?(h+=2,l=a[1].toLowerCase(),e.endTag&&e.endTag(l,s,V,u(e,i,h,o,s))):h=d(i,h,e,s,V,o):e.pcdata&&e.pcdata("&lt;/",s,V,u(e,i,h,o,s));break;case"<":if(a=/^([-\w:]+)\s*\/?/.exec(_))if(a[0].length===_.length&&">"===i[h+1]){h+=2,l=a[1].toLowerCase(),e.startTag&&e.startTag(l,[],s,V,u(e,i,h,o,s));var g=t.ELEMENTS[l];if(g&q){var v={name:l,next:h,eflags:g};h=f(i,v,e,s,V,o)}}else h=m(i,h,e,s,V,o);else e.pcdata&&e.pcdata("&lt;",s,V,u(e,i,h,o,s));break;case"<!--":if(!o.noMoreEndComments){for(r=h+1;c>r&&(">"!==i[r]||!/--$/.test(i[r-1]));r++);if(c>r){if(e.comment){var y=i.slice(h,r).join("");e.comment(y.substr(0,y.length-2),s,V,u(e,i,r+1,o,s))}h=r+1}else o.noMoreEndComments=!0}o.noMoreEndComments&&e.pcdata&&e.pcdata("&lt;!--",s,V,u(e,i,h,o,s));break;case"<!":if(/^\w/.test(_)){if(!o.noMoreGT){for(r=h+1;c>r&&">"!==i[r];r++);c>r?h=r+1:o.noMoreGT=!0}o.noMoreGT&&e.pcdata&&e.pcdata("&lt;!",s,V,u(e,i,h,o,s))}else e.pcdata&&e.pcdata("&lt;!",s,V,u(e,i,h,o,s));break;case"<?":if(!o.noMoreGT){for(r=h+1;c>r&&">"!==i[r];r++);c>r?h=r+1:o.noMoreGT=!0}o.noMoreGT&&e.pcdata&&e.pcdata("&lt;?",s,V,u(e,i,h,o,s));break;case">":e.pcdata&&e.pcdata("&gt;",s,V,u(e,i,h,o,s));break;case"":break;default:e.pcdata&&e.pcdata(p,s,V,u(e,i,h,o,s))}}e.endDoc&&e.endDoc(s)}catch(L){if(L!==V)throw L}}function p(t){var e=/(<\/|<\!--|<[!?]|[&<>])/g;if(t+="",W)return t.split(e);for(var i,n=[],o=0;null!==(i=e.exec(t));)n.push(t.substring(o,i.index)),n.push(i[0]),o=i.index+i[0].length;return n.push(t.substring(o)),n}function d(t,e,i,n,o,s){var a=_(t,e);return a?(i.endTag&&i.endTag(a.name,n,o,u(i,t,e,s,n)),a.next):t.length}function m(t,e,i,n,o,s){var a=_(t,e);return a?(i.startTag&&i.startTag(a.name,a.attrs,n,o,u(i,t,a.next,s,n)),a.eflags&q?f(t,a,i,n,o,s):a.next):t.length}function f(e,i,n,o,s,a){var l=e.length;J.hasOwnProperty(i.name)||(J[i.name]=new RegExp("^"+i.name+"(?:[\\s\\/]|$)","i"));for(var h=J[i.name],c=i.next,p=i.next+1;l>p&&("</"!==e[p-1]||!h.test(e[p]));p++);l>p&&(p-=1);var d=e.slice(c,p).join("");if(i.eflags&t.eflags.CDATA)n.cdata&&n.cdata(d,o,s,u(n,e,p,a,o));else{if(!(i.eflags&t.eflags.RCDATA))throw new Error("bug");n.rcdata&&n.rcdata(r(d),o,s,u(n,e,p,a,o))}return p}function _(e,i){var n=/^([-\w:]+)/.exec(e[i]),o={};o.name=n[1].toLowerCase(),o.eflags=t.ELEMENTS[o.name];for(var s=e[i].substr(n[0].length),a=i+1,r=e.length;r>a&&">"!==e[a];a++)s+=e[a];if(a>=r)return void 0;for(var l=[];""!==s;)if(n=G.exec(s)){if(n[4]&&!n[5]||n[6]&&!n[7]){for(var h=n[4]||n[6],u=!1,c=[s,e[a++]];r>a;a++){if(u){if(">"===e[a])break}else 0<=e[a].indexOf(h)&&(u=!0);c.push(e[a])}if(a>=r)break;s=c.join("");continue}var p=n[1].toLowerCase(),d=n[2]?g(n[3]):"";l.push(p,d),s=s.substr(n[0].length)}else s=s.replace(/^[\s\S][^a-z\s]*/,"");return o.attrs=l,o.next=a+1,o}function g(t){var e=t.charCodeAt(0);return(34===e||39===e)&&(t=t.substr(1,t.length-2)),s(o(t))}function v(e){var i,n,o=function(t,e){n||e.push(t)};return l({startDoc:function(){i=[],n=!1},startTag:function(o,s,r){if(!n&&t.ELEMENTS.hasOwnProperty(o)){var l=t.ELEMENTS[o];if(!(l&t.eflags.FOLDABLE)){var h=e(o,s);if(!h)return n=!(l&t.eflags.EMPTY),void 0;if("object"!=typeof h)throw new Error("tagPolicy did not return object (old API?)");if(!("attribs"in h))throw new Error("tagPolicy gave no attribs");s=h.attribs;var u,c;if("tagName"in h?(c=h.tagName,u=t.ELEMENTS[c]):(c=o,u=l),l&t.eflags.OPTIONAL_ENDTAG){var p=i[i.length-1];!p||p.orig!==o||p.rep===c&&o===c||r.push("</",p.rep,">")}l&t.eflags.EMPTY||i.push({orig:o,rep:c}),r.push("<",c);for(var d=0,m=s.length;m>d;d+=2){var f=s[d],_=s[d+1];null!==_&&void 0!==_&&r.push(" ",f,'="',a(_),'"')}r.push(">"),l&t.eflags.EMPTY&&!(u&t.eflags.EMPTY)&&r.push("</",c,">")}}},endTag:function(e,o){if(n)return n=!1,void 0;if(t.ELEMENTS.hasOwnProperty(e)){var s=t.ELEMENTS[e];if(!(s&(t.eflags.EMPTY|t.eflags.FOLDABLE))){var a;if(s&t.eflags.OPTIONAL_ENDTAG)for(a=i.length;--a>=0;){var r=i[a].orig;if(r===e)break;if(!(t.ELEMENTS[r]&t.eflags.OPTIONAL_ENDTAG))return}else for(a=i.length;--a>=0&&i[a].orig!==e;);if(0>a)return;for(var l=i.length;--l>a;){var h=i[l].rep;t.ELEMENTS[h]&t.eflags.OPTIONAL_ENDTAG||o.push("</",h,">")}a<i.length&&(e=i[a].rep),i.length=a,o.push("</",e,">")}}},pcdata:o,rcdata:o,cdata:o,endDoc:function(t){for(;i.length;i.length--)t.push("</",i[i.length-1].rep,">")}})}function y(t,e,n,o,s){if(!s)return null;try{var a=i.parse(""+t);if(a&&(!a.hasScheme()||K.test(a.getScheme()))){var r=s(a,e,n,o);return r?r.toString():null}}catch(l){return null}return null}function L(t,e,i,n,o){if(i||t(e+" removed",{change:"removed",tagName:e}),n!==o){var s="changed";n&&!o?s="removed":!n&&o&&(s="added"),t(e+"."+i+" "+s,{change:s,tagName:e,attribName:i,oldValue:n,newValue:o})}}function b(t,e,i){var n;return n=e+"::"+i,t.hasOwnProperty(n)?t[n]:(n="*::"+i,t.hasOwnProperty(n)?t[n]:void 0)}function T(e,i){return b(t.LOADERTYPES,e,i)}function P(e,i){return b(t.URIEFFECTS,e,i)}function E(e,i,n,o,s){for(var a=0;a<i.length;a+=2){var r,l=i[a],h=i[a+1],u=h,c=null;if(r=e+"::"+l,(t.ATTRIBS.hasOwnProperty(r)||(r="*::"+l,t.ATTRIBS.hasOwnProperty(r)))&&(c=t.ATTRIBS[r]),null!==c)switch(c){case t.atype.NONE:break;case t.atype.SCRIPT:h=null,s&&L(s,e,l,u,h);break;case t.atype.STYLE:if("undefined"==typeof M){h=null,s&&L(s,e,l,u,h);break}var p=[];M(h,{declaration:function(e,i){var o=e.toLowerCase(),s=S[o];s&&(D(o,s,i,n?function(e){return y(e,t.ueffects.SAME_DOCUMENT,t.ltypes.SANDBOXED,{TYPE:"CSS",CSS_PROP:o},n)}:null),p.push(e+": "+i.join(" ")))}}),h=p.length>0?p.join(" ; "):null,s&&L(s,e,l,u,h);break;case t.atype.ID:case t.atype.IDREF:case t.atype.IDREFS:case t.atype.GLOBAL_NAME:case t.atype.LOCAL_NAME:case t.atype.CLASSES:h=o?o(h):h,s&&L(s,e,l,u,h);break;case t.atype.URI:h=y(h,P(e,l),T(e,l),{TYPE:"MARKUP",XML_ATTR:l,XML_TAG:e},n),s&&L(s,e,l,u,h);break;case t.atype.URI_FRAGMENT:h&&"#"===h.charAt(0)?(h=h.substring(1),h=o?o(h):h,null!==h&&void 0!==h&&(h="#"+h)):h=null,s&&L(s,e,l,u,h);break;default:h=null,s&&L(s,e,l,u,h)}else h=null,s&&L(s,e,l,u,h);i[a+1]=h}return i}function x(e,i,n){return function(o,s){return t.ELEMENTS[o]&t.eflags.UNSAFE?(n&&L(n,o,void 0,void 0,void 0),void 0):{attribs:E(o,s,e,i,n)}}}function w(t,e){var i=[];return v(e)(t,i),i.join("")}function C(t,e,i,n){var o=x(e,i,n);return w(t,o)}var M,D,S;"undefined"!=typeof window&&(M=window.parseCssDeclarations,D=window.sanitizeCssProperty,S=window.cssSchema);var k={lt:"<",LT:"<",gt:">",GT:">",amp:"&",AMP:"&",quot:'"',apos:"'",nbsp:"Â "},A=/^#(\d+)$/,U=/^#x([0-9A-Fa-f]+)$/,O=/^[A-Za-z][A-za-z0-9]+$/,I="undefined"!=typeof window&&window.document?window.document.createElement("textarea"):null,R=/\0/g,z=/&(#[0-9]+|#[xX][0-9A-Fa-f]+|\w+);/g,B=/^(#[0-9]+|#[xX][0-9A-Fa-f]+|\w+);/,N=/&/g,H=/&([^a-z#]|#(?:[^0-9x]|x(?:[^0-9a-f]|$)|$)|$)/gi,Z=/[<]/g,j=/>/g,F=/\"/g,G=new RegExp("^\\s*([-.:\\w]+)(?:\\s*(=)\\s*((\")[^\"]*(\"|$)|(')[^']*('|$)|(?=[a-z][-\\w]*\\s*=)|[^\"'\\s]*))?","i"),W=3==="a,b".split(/(,)/).length,q=t.eflags.CDATA|t.eflags.RCDATA,V={},J={},K=/^(?:https?|mailto|data)$/i,X={};return X.escapeAttrib=X.escapeAttrib=a,X.makeHtmlSanitizer=X.makeHtmlSanitizer=v,X.makeSaxParser=X.makeSaxParser=l,X.makeTagPolicy=X.makeTagPolicy=x,X.normalizeRCData=X.normalizeRCData=r,X.sanitize=X.sanitize=C,X.sanitizeAttribs=X.sanitizeAttribs=E,X.sanitizeWithPolicy=X.sanitizeWithPolicy=w,X.unescapeEntities=X.unescapeEntities=s,X}(n),s=o.sanitize;n.ATTRIBS["*::style"]=0,n.ELEMENTS.style=0,n.ATTRIBS["a::target"]=0,n.ELEMENTS.video=0,n.ATTRIBS["video::src"]=0,n.ATTRIBS["video::poster"]=0,n.ATTRIBS["video::controls"]=0,n.ELEMENTS.audio=0,n.ATTRIBS["audio::src"]=0,n.ATTRIBS["video::autoplay"]=0,n.ATTRIBS["video::controls"]=0,"undefined"!=typeof e&&(e.exports=s)},{}],6:[function(t,e){e.exports={author:"Mapbox",name:"mapbox.js",description:"mapbox javascript api",version:"2.1.5",homepage:"http://mapbox.com/",repository:{type:"git",url:"git://github.com/mapbox/mapbox.js.git"},main:"src/index.js",dependencies:{leaflet:"0.7.3",mustache:"0.7.3",corslite:"0.0.6","sanitize-caja":"0.1.2"},scripts:{test:"jshint src/*.js && mocha-phantomjs test/index.html"},devDependencies:{"leaflet-hash":"0.2.1","leaflet-fullscreen":"0.0.4","uglify-js":"2.4.8",mocha:"1.17.1","expect.js":"0.3.1",sinon:"1.10.2","mocha-phantomjs":"3.1.6",happen:"0.1.3",browserify:"^6.3.2",jshint:"2.4.4","clean-css":"~2.0.7",minimist:"0.0.5",marked:"~0.3.0"},optionalDependencies:{},engines:{node:"*"}}},{}],7:[function(t,e){"use strict";e.exports={HTTP_URL:"http://a.tiles.mapbox.com/v4",HTTPS_URL:"https://a.tiles.mapbox.com/v4",FORCE_HTTPS:!1,REQUIRE_ACCESS_TOKEN:!0}},{}],8:[function(t,e){"use strict";var i=t("./util"),n=t("./url"),o=t("./request"),s=t("./marker"),a=t("./simplestyle"),r=L.FeatureGroup.extend({options:{filter:function(){return!0},sanitizer:t("sanitize-caja"),style:a.style,popupOptions:{closeButton:!1}},initialize:function(t,e){L.setOptions(this,e),this._layers={},"string"==typeof t?i.idUrl(t,this):t&&"object"==typeof t&&this.setGeoJSON(t)},setGeoJSON:function(t){return this._geojson=t,this.clearLayers(),this._initialize(t),this},getGeoJSON:function(){return this._geojson},loadURL:function(t){return this._request&&"abort"in this._request&&this._request.abort(),this._request=o(t,L.bind(function(e,n){this._request=null,e&&"abort"!==e.type?(i.log("could not load features at "+t),this.fire("error",{error:e})):n&&(this.setGeoJSON(n),this.fire("ready"))},this)),this},loadID:function(t){return this.loadURL(n("/"+t+"/features.json",this.options.accessToken))},setFilter:function(t){return this.options.filter=t,this._geojson&&(this.clearLayers(),this._initialize(this._geojson)),this},getFilter:function(){return this.options.filter},_initialize:function(t){var e,i,n=L.Util.isArray(t)?t:t.features;if(n)for(e=0,i=n.length;i>e;e++)(n[e].geometries||n[e].geometry||n[e].features)&&this._initialize(n[e]);else if(this.options.filter(t)){var o={accessToken:this.options.accessToken},r=L.GeoJSON.geometryToLayer(t,function(t,e){return s.style(t,e,o)
  }),l=s.createPopup(t,this.options.sanitizer);"setStyle"in r&&r.setStyle(a.style(t)),r.feature=t,l&&r.bindPopup(l,this.options.popupOptions),this.addLayer(r)}}});e.exports.FeatureLayer=r,e.exports.featureLayer=function(t,e){return new r(t,e)}},{"./marker":22,"./request":23,"./simplestyle":25,"./url":27,"./util":28,"sanitize-caja":4}],9:[function(t,e){"use strict";var i=t("./util"),n=t("./url"),o=t("./request");e.exports=function(t,e){var s={};return i.strict(t,"string"),-1===t.indexOf("/")&&(t=n("/geocode/"+t+"/{query}.json",e&&e.accessToken)),s.getURL=function(){return t},s.queryURL=function(t){if("string"!=typeof t){for(var e=[],i=0;i<t.length;i++)e[i]=encodeURIComponent(t[i]);return L.Util.template(s.getURL(),{query:e.join(";")})}return L.Util.template(s.getURL(),{query:encodeURIComponent(t)})},s.query=function(t,e){return i.strict(e,"function"),o(s.queryURL(t),function(t,n){if(n&&(n.length||n.features)){var o={results:n};n.features&&n.features.length&&(o.latlng=[n.features[0].center[1],n.features[0].center[0]],n.features[0].bbox&&(o.bounds=n.features[0].bbox,o.lbounds=i.lbounds(o.bounds))),e(null,o)}else e(t||!0)}),s},s.reverseQuery=function(t,e){function i(t){return void 0!==t.lat&&void 0!==t.lng?t.lng+","+t.lat:void 0!==t.lat&&void 0!==t.lon?t.lon+","+t.lat:t[0]+","+t[1]}var n="";if(t.length&&t[0].length){for(var a=0,r=[];a<t.length;a++)r.push(i(t[a]));n=r.join(";")}else n=i(t);return o(s.queryURL(n),function(t,i){e(t,i)}),s},s}},{"./request":23,"./url":27,"./util":28}],10:[function(t,e){"use strict";var i=t("./geocoder"),n=t("./util"),o=L.Control.extend({includes:L.Mixin.Events,options:{position:"topleft",pointZoom:16,keepOpen:!1,autocomplete:!1},initialize:function(t,e){L.Util.setOptions(this,e),this.setURL(t),this._updateSubmit=L.bind(this._updateSubmit,this),this._updateAutocomplete=L.bind(this._updateAutocomplete,this),this._chooseResult=L.bind(this._chooseResult,this)},setURL:function(t){return this.geocoder=i(t,{accessToken:this.options.accessToken}),this},getURL:function(){return this.geocoder.getURL()},setID:function(t){return this.setURL(t)},setTileJSON:function(t){return this.setURL(t.geocoder)},_toggle:function(t){t&&L.DomEvent.stop(t),L.DomUtil.hasClass(this._container,"active")?(L.DomUtil.removeClass(this._container,"active"),this._results.innerHTML="",this._input.blur()):(L.DomUtil.addClass(this._container,"active"),this._input.focus(),this._input.select())},_closeIfOpen:function(){L.DomUtil.hasClass(this._container,"active")&&!this.options.keepOpen&&(L.DomUtil.removeClass(this._container,"active"),this._results.innerHTML="",this._input.blur())},onAdd:function(t){var e=L.DomUtil.create("div","leaflet-control-mapbox-geocoder leaflet-bar leaflet-control"),i=L.DomUtil.create("a","leaflet-control-mapbox-geocoder-toggle mapbox-icon mapbox-icon-geocoder",e),n=L.DomUtil.create("div","leaflet-control-mapbox-geocoder-results",e),o=L.DomUtil.create("div","leaflet-control-mapbox-geocoder-wrap",e),s=L.DomUtil.create("form","leaflet-control-mapbox-geocoder-form",o),a=L.DomUtil.create("input","",s);return i.href="#",i.innerHTML="&nbsp;",a.type="text",a.setAttribute("placeholder","Search"),L.DomEvent.addListener(s,"submit",this._geocode,this),L.DomEvent.addListener(a,"keyup",this._autocomplete,this),L.DomEvent.disableClickPropagation(e),this._map=t,this._results=n,this._input=a,this._form=s,this.options.keepOpen?L.DomUtil.addClass(e,"active"):(this._map.on("click",this._closeIfOpen,this),L.DomEvent.addListener(i,"click",this._toggle,this)),e},_updateSubmit:function(t,e){if(L.DomUtil.removeClass(this._container,"searching"),this._results.innerHTML="",t||!e)this.fire("error",{error:t});else{var i=[];e.results&&e.results.features&&(i=e.results.features),1===i.length?(this.fire("autoselect",{feature:i[0]}),this.fire("found",{results:e.results}),this._chooseResult(i[0]),this._closeIfOpen()):i.length>1?(this.fire("found",{results:e.results}),this._displayResults(i)):this._displayResults(i)}},_updateAutocomplete:function(t,e){if(this._results.innerHTML="",t||!e)this.fire("error",{error:t});else{var i=[];e.results&&e.results.features&&(i=e.results.features),i.length&&this.fire("found",{results:e.results}),this._displayResults(i)}},_displayResults:function(t){for(var e=0,i=Math.min(t.length,5);i>e;e++){var n=t[e],o=n.place_name;if(o.length){var s=L.DomUtil.create("a","",this._results),a="innerText"in s?"innerText":"textContent";s[a]=o,s.href="#",L.bind(function(t){L.DomEvent.addListener(s,"click",function(e){this._chooseResult(t),L.DomEvent.stop(e),this.fire("select",{feature:t})},this)},this)(n)}}if(t.length>5){var r=L.DomUtil.create("span","",this._results);r.innerHTML="Top 5 of "+t.length+"  results"}},_chooseResult:function(t){t.bbox?this._map.fitBounds(n.lbounds(t.bbox)):t.center&&this._map.setView([t.center[1],t.center[0]],void 0===this._map.getZoom()?this.options.pointZoom:Math.max(this._map.getZoom(),this.options.pointZoom))},_geocode:function(t){return L.DomEvent.preventDefault(t),""===this._input.value?this._updateSubmit():(L.DomUtil.addClass(this._container,"searching"),this.geocoder.query(this._input.value,this._updateSubmit),void 0)},_autocomplete:function(){return this.options.autocomplete?""===this._input.value?this._updateAutocomplete():(this.geocoder.query(this._input.value,this._updateAutocomplete),void 0):void 0}});e.exports.GeocoderControl=o,e.exports.geocoderControl=function(t,e){return new o(t,e)}},{"./geocoder":9,"./util":28}],11:[function(t,e){"use strict";function i(t){return t>=93&&t--,t>=35&&t--,t-32}e.exports=function(t){return function(e,n){if(t){var o=i(t.grid[n].charCodeAt(e)),s=t.keys[o];return t.data[s]}}}},{}],12:[function(t,e){"use strict";var i=t("./util"),n=t("mustache"),o=L.Control.extend({options:{pinnable:!0,follow:!1,sanitizer:t("sanitize-caja"),touchTeaser:!0,location:!0},_currentContent:"",_pinned:!1,initialize:function(t,e){L.Util.setOptions(this,e),i.strict_instance(t,L.Class,"L.mapbox.gridLayer"),this._layer=t},setTemplate:function(t){return i.strict(t,"string"),this.options.template=t,this},_template:function(t,e){if(e){var i=this.options.template||this._layer.getTileJSON().template;if(i){var o={};return o["__"+t+"__"]=!0,this.options.sanitizer(n.to_html(i,L.extend(o,e)))}}},_show:function(t,e){t!==this._currentContent&&(this._currentContent=t,this.options.follow?(this._popup.setContent(t).setLatLng(e.latLng),this._map._popup!==this._popup&&this._popup.openOn(this._map)):(this._container.style.display="block",this._contentWrapper.innerHTML=t))},hide:function(){return this._pinned=!1,this._currentContent="",this._map.closePopup(),this._container.style.display="none",this._contentWrapper.innerHTML="",L.DomUtil.removeClass(this._container,"closable"),this},_mouseover:function(t){if(t.data?L.DomUtil.addClass(this._map._container,"map-clickable"):L.DomUtil.removeClass(this._map._container,"map-clickable"),!this._pinned){var e=this._template("teaser",t.data);e?this._show(e,t):this.hide()}},_mousemove:function(t){this._pinned||this.options.follow&&this._popup.setLatLng(t.latLng)},_navigateTo:function(t){window.top.location.href=t},_click:function(t){var e=this._template("location",t.data);if(this.options.location&&e&&0===e.search(/^https?:/))return this._navigateTo(this._template("location",t.data));if(this.options.pinnable){var i=this._template("full",t.data);!i&&this.options.touchTeaser&&L.Browser.touch&&(i=this._template("teaser",t.data)),i?(L.DomUtil.addClass(this._container,"closable"),this._pinned=!0,this._show(i,t)):this._pinned&&(L.DomUtil.removeClass(this._container,"closable"),this._pinned=!1,this.hide())}},_onPopupClose:function(){this._currentContent=null,this._pinned=!1},_createClosebutton:function(t,e){var i=L.DomUtil.create("a","close",t);return i.innerHTML="close",i.href="#",i.title="close",L.DomEvent.on(i,"click",L.DomEvent.stopPropagation).on(i,"mousedown",L.DomEvent.stopPropagation).on(i,"dblclick",L.DomEvent.stopPropagation).on(i,"click",L.DomEvent.preventDefault).on(i,"click",e,this),i},onAdd:function(t){this._map=t;var e="leaflet-control-grid map-tooltip",i=L.DomUtil.create("div",e),n=L.DomUtil.create("div","map-tooltip-content");return i.style.display="none",this._createClosebutton(i,this.hide),i.appendChild(n),this._contentWrapper=n,this._popup=new L.Popup({autoPan:!1,closeOnClick:!1}),t.on("popupclose",this._onPopupClose,this),L.DomEvent.disableClickPropagation(i).addListener(i,"mousewheel",L.DomEvent.stopPropagation),this._layer.on("mouseover",this._mouseover,this).on("mousemove",this._mousemove,this).on("click",this._click,this),i},onRemove:function(t){t.off("popupclose",this._onPopupClose,this),this._layer.off("mouseover",this._mouseover,this).off("mousemove",this._mousemove,this).off("click",this._click,this)}});e.exports.GridControl=o,e.exports.gridControl=function(t,e){return new o(t,e)}},{"./util":28,mustache:3,"sanitize-caja":4}],13:[function(t,e){"use strict";var i=t("./util"),n=t("./request"),o=t("./grid"),s=L.Class.extend({includes:[L.Mixin.Events,t("./load_tilejson")],options:{template:function(){return""}},_mouseOn:null,_tilejson:{},_cache:{},initialize:function(t,e){L.Util.setOptions(this,e),this._loadTileJSON(t)},_setTileJSON:function(t){return i.strict(t,"object"),L.extend(this.options,{grids:t.grids,minZoom:t.minzoom,maxZoom:t.maxzoom,bounds:t.bounds&&i.lbounds(t.bounds)}),this._tilejson=t,this._cache={},this._update(),this},getTileJSON:function(){return this._tilejson},active:function(){return!!(this._map&&this.options.grids&&this.options.grids.length)},addTo:function(t){return t.addLayer(this),this},onAdd:function(t){this._map=t,this._update(),this._map.on("click",this._click,this).on("mousemove",this._move,this).on("moveend",this._update,this)},onRemove:function(){this._map.off("click",this._click,this).off("mousemove",this._move,this).off("moveend",this._update,this)},getData:function(t,e){if(this.active()){var i=this._map,n=i.project(t.wrap()),o=256,s=4,a=Math.floor(n.x/o),r=Math.floor(n.y/o),l=i.options.crs.scale(i.getZoom())/o;return a=(a+l)%l,r=(r+l)%l,this._getTile(i.getZoom(),a,r,function(t){var i=Math.floor((n.x-a*o)/s),l=Math.floor((n.y-r*o)/s);e(t(i,l))}),this}},_click:function(t){this.getData(t.latlng,L.bind(function(e){this.fire("click",{latLng:t.latlng,data:e})},this))},_move:function(t){this.getData(t.latlng,L.bind(function(e){e!==this._mouseOn?(this._mouseOn&&this.fire("mouseout",{latLng:t.latlng,data:this._mouseOn}),this.fire("mouseover",{latLng:t.latlng,data:e}),this._mouseOn=e):this.fire("mousemove",{latLng:t.latlng,data:e})},this))},_getTileURL:function(t){var e=this.options.grids,i=(t.x+t.y)%e.length,n=e[i];return L.Util.template(n,t)},_update:function(){if(this.active()){var t=this._map.getPixelBounds(),e=this._map.getZoom(),i=256;if(!(e>this.options.maxZoom||e<this.options.minZoom))for(var n=L.bounds(t.min.divideBy(i)._floor(),t.max.divideBy(i)._floor()),o=this._map.options.crs.scale(e)/i,s=n.min.x;s<=n.max.x;s++)for(var a=n.min.y;a<=n.max.y;a++)this._getTile(e,(s%o+o)%o,(a%o+o)%o)}},_getTile:function(t,e,i,s){var a=t+"_"+e+"_"+i,r=L.point(e,i);if(r.z=t,this._tileShouldBeLoaded(r)){if(a in this._cache){if(!s)return;return"function"==typeof this._cache[a]?s(this._cache[a]):this._cache[a].push(s),void 0}this._cache[a]=[],s&&this._cache[a].push(s),n(this._getTileURL(r),L.bind(function(t,e){var i=this._cache[a];this._cache[a]=o(e);for(var n=0;n<i.length;++n)i[n](this._cache[a])},this))}},_tileShouldBeLoaded:function(t){if(t.z>this.options.maxZoom||t.z<this.options.minZoom)return!1;if(this.options.bounds){var e=256,i=t.multiplyBy(e),n=i.add(new L.Point(e,e)),o=this._map.unproject(i),s=this._map.unproject(n),a=new L.LatLngBounds([o,s]);if(!this.options.bounds.intersects(a))return!1}return!0}});e.exports.GridLayer=s,e.exports.gridLayer=function(t,e){return new s(t,e)}},{"./grid":11,"./load_tilejson":18,"./request":23,"./util":28}],14:[function(t){t("./leaflet"),t("./mapbox")},{"./leaflet":16,"./mapbox":20}],15:[function(t,e){"use strict";var i=L.Control.extend({options:{position:"bottomright",sanitizer:t("sanitize-caja")},initialize:function(t){L.setOptions(this,t),this._info={}},onAdd:function(t){this._container=L.DomUtil.create("div","mapbox-control-info mapbox-small"),this._content=L.DomUtil.create("div","map-info-container",this._container);var e=L.DomUtil.create("a","mapbox-info-toggle mapbox-icon mapbox-icon-info",this._container);e.href="#",L.DomEvent.addListener(e,"click",this._showInfo,this),L.DomEvent.disableClickPropagation(this._container);for(var i in t._layers)t._layers[i].getAttribution&&this.addInfo(t._layers[i].getAttribution());return t.on("layeradd",this._onLayerAdd,this).on("layerremove",this._onLayerRemove,this),this._update(),this._container},onRemove:function(t){t.off("layeradd",this._onLayerAdd,this).off("layerremove",this._onLayerRemove,this)},addInfo:function(t){return t?(this._info[t]||(this._info[t]=0),this._info[t]=!0,this._update()):this},removeInfo:function(t){return t?(this._info[t]&&(this._info[t]=!1),this._update()):this},_showInfo:function(t){return L.DomEvent.preventDefault(t),this._active===!0?this._hidecontent():(L.DomUtil.addClass(this._container,"active"),this._active=!0,this._update(),void 0)},_hidecontent:function(){this._content.innerHTML="",this._active=!1,L.DomUtil.removeClass(this._container,"active")},_update:function(){if(!this._map)return this;this._content.innerHTML="";var t="none",e=[];for(var i in this._info)this._info.hasOwnProperty(i)&&this._info[i]&&(e.push(this.options.sanitizer(i)),t="block");return this._content.innerHTML+=e.join(" | "),this._container.style.display=t,this},_onLayerAdd:function(t){t.layer.getAttribution&&t.layer.getAttribution()?this.addInfo(t.layer.getAttribution()):"on"in t.layer&&t.layer.getAttribution&&t.layer.on("ready",L.bind(function(){this.addInfo(t.layer.getAttribution())},this))},_onLayerRemove:function(t){t.layer.getAttribution&&this.removeInfo(t.layer.getAttribution())}});e.exports.InfoControl=i,e.exports.infoControl=function(t){return new i(t)}},{"sanitize-caja":4}],16:[function(t){window.L=t("leaflet/dist/leaflet-src")},{"leaflet/dist/leaflet-src":2}],17:[function(t,e){"use strict";var i=L.Control.extend({options:{position:"bottomright",sanitizer:t("sanitize-caja")},initialize:function(t){L.setOptions(this,t),this._legends={}},onAdd:function(){return this._container=L.DomUtil.create("div","map-legends wax-legends"),L.DomEvent.disableClickPropagation(this._container),this._update(),this._container},addLegend:function(t){return t?(this._legends[t]||(this._legends[t]=0),this._legends[t]++,this._update()):this},removeLegend:function(t){return t?(this._legends[t]&&this._legends[t]--,this._update()):this},_update:function(){if(!this._map)return this;this._container.innerHTML="";var t="none";for(var e in this._legends)if(this._legends.hasOwnProperty(e)&&this._legends[e]){var i=L.DomUtil.create("div","map-legend wax-legend",this._container);i.innerHTML=this.options.sanitizer(e),t="block"}return this._container.style.display=t,this}});e.exports.LegendControl=i,e.exports.legendControl=function(t){return new i(t)}},{"sanitize-caja":4}],18:[function(t,e){"use strict";var i=t("./request"),n=t("./url"),o=t("./util");e.exports={_loadTileJSON:function(t){"string"==typeof t?(t=n.tileJSON(t,this.options&&this.options.accessToken),i(t,L.bind(function(e,i){e?(o.log("could not load TileJSON at "+t),this.fire("error",{error:e})):i&&(this._setTileJSON(i),this.fire("ready"))},this))):t&&"object"==typeof t&&this._setTileJSON(t)}}},{"./request":23,"./url":27,"./util":28}],19:[function(t,e){"use strict";function i(t,e){return!e||t.accessToken?t:L.extend({accessToken:e},t)}var n=(t("./util"),t("./tile_layer").tileLayer),o=t("./feature_layer").featureLayer,s=t("./grid_layer").gridLayer,a=t("./grid_control").gridControl,r=t("./info_control").infoControl,l=t("./share_control").shareControl,h=t("./legend_control").legendControl,u=t("./mapbox_logo").mapboxLogoControl,c=L.Map.extend({includes:[t("./load_tilejson")],options:{tileLayer:{},featureLayer:{},gridLayer:{},legendControl:{},gridControl:{},infoControl:!1,shareControl:!1},_tilejson:{},initialize:function(t,e,c){L.Map.prototype.initialize.call(this,t,L.extend({},L.Map.prototype.options,c)),this.attributionControl&&this.attributionControl.setPrefix(""),this.options.tileLayer&&(this.tileLayer=n(void 0,i(this.options.tileLayer,this.options.accessToken)),this.addLayer(this.tileLayer)),this.options.featureLayer&&(this.featureLayer=o(void 0,i(this.options.featureLayer,this.options.accessToken)),this.addLayer(this.featureLayer)),this.options.gridLayer&&(this.gridLayer=s(void 0,i(this.options.gridLayer,this.options.accessToken)),this.addLayer(this.gridLayer)),this.options.gridLayer&&this.options.gridControl&&(this.gridControl=a(this.gridLayer,this.options.gridControl),this.addControl(this.gridControl)),this.options.infoControl&&(this.infoControl=r(this.options.infoControl),this.addControl(this.infoControl)),this.options.legendControl&&(this.legendControl=h(this.options.legendControl),this.addControl(this.legendControl)),this.options.shareControl&&(this.shareControl=l(void 0,i(this.options.shareControl,this.options.accessToken)),this.addControl(this.shareControl)),this._mapboxLogoControl=u(this.options.mapboxLogoControl),this.addControl(this._mapboxLogoControl),this._loadTileJSON(e)},addLayer:function(t){return"on"in t&&t.on("ready",L.bind(function(){this._updateLayer(t)},this)),L.Map.prototype.addLayer.call(this,t)},_setTileJSON:function(t){return this._tilejson=t,this._initialize(t),this},getTileJSON:function(){return this._tilejson},_initialize:function(t){if(this.tileLayer&&(this.tileLayer._setTileJSON(t),this._updateLayer(this.tileLayer)),this.featureLayer&&!this.featureLayer.getGeoJSON()&&t.data&&t.data[0]&&this.featureLayer.loadURL(t.data[0]),this.gridLayer&&(this.gridLayer._setTileJSON(t),this._updateLayer(this.gridLayer)),this.infoControl&&t.attribution&&this.infoControl.addInfo(t.attribution),this.legendControl&&t.legend&&this.legendControl.addLegend(t.legend),this.shareControl&&this.shareControl._setTileJSON(t),this._mapboxLogoControl._setTileJSON(t),!this._loaded&&t.center){var e=void 0!==this.getZoom()?this.getZoom():t.center[2],i=L.latLng(t.center[1],t.center[0]);this.setView(i,e)}},_editLink:function(){if(this._controlContainer.getElementsByClassName){var t=this._controlContainer.getElementsByClassName("mapbox-improve-map");if(t.length&&this._loaded)for(var e=this.getCenter().wrap(),i=this._tilejson||{},n=i.id||"",o=0;o<t.length;o++)t[o].href=t[o].href.split("#")[0]+"#"+n+"/"+e.lng.toFixed(3)+"/"+e.lat.toFixed(3)+"/"+this.getZoom()}},_updateLayer:function(t){t.options&&(this.infoControl&&this._loaded&&this.infoControl.addInfo(t.options.infoControl),this.attributionControl&&this._loaded&&t.getAttribution&&this.attributionControl.addAttribution(t.getAttribution()),this.on("moveend",this._editLink,this),L.stamp(t)in this._zoomBoundLayers||!t.options.maxZoom&&!t.options.minZoom||(this._zoomBoundLayers[L.stamp(t)]=t),this._editLink(),this._updateZoomLevels())}});e.exports.Map=c,e.exports.map=function(t,e,i){return new c(t,e,i)}},{"./feature_layer":8,"./grid_control":12,"./grid_layer":13,"./info_control":15,"./legend_control":17,"./load_tilejson":18,"./mapbox_logo":21,"./share_control":24,"./tile_layer":26,"./util":28}],20:[function(t,e){"use strict";var i=t("./geocoder_control"),n=t("./grid_control"),o=t("./feature_layer"),s=t("./legend_control"),a=t("./share_control"),r=t("./tile_layer"),l=t("./info_control"),h=t("./map"),u=t("./grid_layer");L.mapbox=e.exports={VERSION:t("../package.json").version,geocoder:t("./geocoder"),marker:t("./marker"),simplestyle:t("./simplestyle"),tileLayer:r.tileLayer,TileLayer:r.TileLayer,infoControl:l.infoControl,InfoControl:l.InfoControl,shareControl:a.shareControl,ShareControl:a.ShareControl,legendControl:s.legendControl,LegendControl:s.LegendControl,geocoderControl:i.geocoderControl,GeocoderControl:i.GeocoderControl,gridControl:n.gridControl,GridControl:n.GridControl,gridLayer:u.gridLayer,GridLayer:u.GridLayer,featureLayer:o.featureLayer,FeatureLayer:o.FeatureLayer,map:h.map,Map:h.Map,config:t("./config"),sanitize:t("sanitize-caja"),template:t("mustache").to_html},window.L.Icon.Default.imagePath=("https:"==document.location.protocol||"http:"==document.location.protocol?"":"https:")+"//api.tiles.mapbox.com/mapbox.js/v"+t("../package.json").version+"/images"},{"../package.json":6,"./config":7,"./feature_layer":8,"./geocoder":9,"./geocoder_control":10,"./grid_control":12,"./grid_layer":13,"./info_control":15,"./legend_control":17,"./map":19,"./marker":22,"./share_control":24,"./simplestyle":25,"./tile_layer":26,mustache:3,"sanitize-caja":4}],21:[function(t,e){"use strict";var i=L.Control.extend({options:{position:"bottomleft"},initialize:function(t){L.setOptions(this,t)},onAdd:function(){return this._container=L.DomUtil.create("div","mapbox-logo"),this._container},_setTileJSON:function(t){t.mapbox_logo&&L.DomUtil.addClass(this._container,"mapbox-logo-true")}});e.exports.MapboxLogoControl=i,e.exports.mapboxLogoControl=function(t){return new i(t)}},{}],22:[function(t,e){"use strict";function i(t,e){t=t||{};var i={small:[20,50],medium:[30,70],large:[35,90]},n=t["marker-size"]||"medium",o="marker-symbol"in t&&""!==t["marker-symbol"]?"-"+t["marker-symbol"]:"",a=(t["marker-color"]||"7e7e7e").replace("#","");return L.icon({iconUrl:s("/marker/pin-"+n.charAt(0)+o+"+"+a+(L.Browser.retina?"@2x":"")+".png",e&&e.accessToken),iconSize:i[n],iconAnchor:[i[n][0]/2,i[n][1]/2],popupAnchor:[0,-i[n][1]/2]})}function n(t,e,n){return L.marker(e,{icon:i(t.properties,n),title:a.strip_tags(r(t.properties&&t.properties.title||""))})}function o(t,e){if(!t||!t.properties)return"";var i="";return t.properties.title&&(i+='<div class="marker-title">'+t.properties.title+"</div>"),t.properties.description&&(i+='<div class="marker-description">'+t.properties.description+"</div>"),(e||r)(i)}var s=t("./url"),a=t("./util"),r=t("sanitize-caja");e.exports={icon:i,style:n,createPopup:o}},{"./url":27,"./util":28,"sanitize-caja":4}],23:[function(t,e){"use strict";var i=t("corslite"),n=t("./util").strict,o=t("./config"),s=/^(https?:)?(?=\/\/(.|api)\.tiles\.mapbox\.com\/)/;e.exports=function(t,e){function a(t,i){!t&&i&&(i=JSON.parse(i.responseText)),e(t,i)}return n(t,"string"),n(e,"function"),t=t.replace(s,function(t,e){return"withCredentials"in new window.XMLHttpRequest?"https:"===e||"https:"===document.location.protocol||o.FORCE_HTTPS?"https:":"http:":document.location.protocol}),i(t,a)}},{"./config":7,"./util":28,corslite:1}],24:[function(t,e){"use strict";var i=t("./url"),n=L.Control.extend({includes:[t("./load_tilejson")],options:{position:"topleft",url:""},initialize:function(t,e){L.setOptions(this,e),this._loadTileJSON(t)},_setTileJSON:function(t){this._tilejson=t},onAdd:function(t){this._map=t;var e=L.DomUtil.create("div","leaflet-control-mapbox-share leaflet-bar"),i=L.DomUtil.create("a","mapbox-share mapbox-icon mapbox-icon-share",e);return i.href="#",this._modal=L.DomUtil.create("div","mapbox-modal",this._map._container),this._mask=L.DomUtil.create("div","mapbox-modal-mask",this._modal),this._content=L.DomUtil.create("div","mapbox-modal-content",this._modal),L.DomEvent.addListener(i,"click",this._shareClick,this),L.DomEvent.disableClickPropagation(e),this._map.on("mousedown",this._clickOut,this),e},_clickOut:function(t){return this._sharing?(L.DomEvent.preventDefault(t),L.DomUtil.removeClass(this._modal,"active"),this._content.innerHTML="",this._sharing=null,void 0):void 0},_shareClick:function(t){if(L.DomEvent.stop(t),this._sharing)return this._clickOut(t);var e=this._tilejson||this._map._tilejson||{},n=encodeURIComponent(this.options.url||e.webpage||window.location),o=encodeURIComponent(e.name),s=i("/"+e.id+"/"+this._map.getCenter().lng+","+this._map.getCenter().lat+","+this._map.getZoom()+"/600x600.png",this.options.accessToken),a=i("/"+e.id+".html",this.options.accessToken),r="//twitter.com/intent/tweet?status="+o+" "+n,l="//www.facebook.com/sharer.php?u="+n+"&t="+encodeURIComponent(e.name),h="//www.pinterest.com/pin/create/button/?url="+n+"&media="+s+"&description="+e.name,u="<h3>Share this map</h3><div class='mapbox-share-buttons'><a class='mapbox-button mapbox-button-icon mapbox-icon-facebook' target='_blank' href='{{facebook}}'>Facebook</a><a class='mapbox-button mapbox-button-icon mapbox-icon-twitter' target='_blank' href='{{twitter}}'>Twitter</a><a class='mapbox-button mapbox-button-icon mapbox-icon-pinterest' target='_blank' href='{{pinterest}}'>Pinterest</a></div>".replace("{{twitter}}",r).replace("{{facebook}}",l).replace("{{pinterest}}",h),c='<iframe width="100%" height="500px" frameBorder="0" src="{{embed}}"></iframe>'.replace("{{embed}}",a),p="Copy and paste this <strong>HTML code</strong> into documents to embed this map on web pages.";L.DomUtil.addClass(this._modal,"active"),this._sharing=L.DomUtil.create("div","mapbox-modal-body",this._content),this._sharing.innerHTML=u;var d=L.DomUtil.create("input","mapbox-embed",this._sharing);d.type="text",d.value=c;var m=L.DomUtil.create("label","mapbox-embed-description",this._sharing);m.innerHTML=p;var f=L.DomUtil.create("a","leaflet-popup-close-button",this._sharing);f.href="#",L.DomEvent.disableClickPropagation(this._sharing),L.DomEvent.addListener(f,"click",this._clickOut,this),L.DomEvent.addListener(d,"click",function(t){t.target.focus(),t.target.select()})}});e.exports.ShareControl=n,e.exports.shareControl=function(t,e){return new n(t,e)}},{"./load_tilejson":18,"./url":27}],25:[function(t,e){"use strict";function i(t,e){var i={};for(var n in e)i[n]=void 0===t[n]?e[n]:t[n];return i}function n(t){for(var e={},i=0;i<a.length;i++)e[a[i][1]]=t[a[i][0]];return e}function o(t){return n(i(t.properties||{},s))}var s={stroke:"#555555","stroke-width":2,"stroke-opacity":1,fill:"#555555","fill-opacity":.5},a=[["stroke","color"],["stroke-width","weight"],["stroke-opacity","opacity"],["fill","fillColor"],["fill-opacity","fillOpacity"]];e.exports={style:o,defaults:s}},{}],26:[function(t,e){"use strict";var i=t("./util"),n=L.TileLayer.extend({includes:[t("./load_tilejson")],options:{format:"png"},formats:["png","png32","png64","png128","png256","jpg70","jpg80","jpg90"],scalePrefix:"@2x.",initialize:function(t,e){L.TileLayer.prototype.initialize.call(this,void 0,e),this._tilejson={},e&&e.format&&i.strict_oneof(e.format,this.formats),this._loadTileJSON(t)},setFormat:function(t){return i.strict(t,"string"),this.options.format=t,this.redraw(),this},setUrl:null,_setTileJSON:function(t){return i.strict(t,"object"),L.extend(this.options,{tiles:t.tiles,attribution:t.attribution,minZoom:t.minzoom||0,maxZoom:t.maxzoom||18,tms:"tms"===t.scheme,bounds:t.bounds&&i.lbounds(t.bounds)}),this._tilejson=t,this.redraw(),this},getTileJSON:function(){return this._tilejson},getTileUrl:function(t){var e=this.options.tiles,i=Math.floor(Math.abs(t.x+t.y)%e.length),n=e[i],o=L.Util.template(n,t);return o?o.replace(".png",(L.Browser.retina?this.scalePrefix:".")+this.options.format):o},_update:function(){this.options.tiles&&L.TileLayer.prototype._update.call(this)}});e.exports.TileLayer=n,e.exports.tileLayer=function(t,e){return new n(t,e)}},{"./load_tilejson":18,"./util":28}],27:[function(t,e){"use strict";var i=t("./config"),n=t("../package.json").version;e.exports=function(t,e){if(e=e||L.mapbox.accessToken,!e&&i.REQUIRE_ACCESS_TOKEN)throw new Error("An API access token is required to use Mapbox.js. See https://www.mapbox.com/mapbox.js/api/v"+n+"/api-access-tokens/");var o="https:"===document.location.protocol||i.FORCE_HTTPS?i.HTTPS_URL:i.HTTP_URL;if(o+=t,o+=-1!==o.indexOf("?")?"&access_token=":"?access_token=",i.REQUIRE_ACCESS_TOKEN){if("s"===e[0])throw new Error("Use a public access token (pk.*) with Mapbox.js, not a secret access token (sk.*). See https://www.mapbox.com/mapbox.js/api/v"+n+"/api-access-tokens/");o+=e}return o},e.exports.tileJSON=function(t,i){if(-1!==t.indexOf("/"))return t;var n=e.exports("/"+t+".json",i);return 0===n.indexOf("https")&&(n+="&secure"),n}},{"../package.json":6,"./config":7}],28:[function(t,e){"use strict";function i(t,e){if(!e||!e.length)return!1;for(var i=0;i<e.length;i++)if(e[i]==t)return!0;return!1}e.exports={idUrl:function(t,e){-1==t.indexOf("/")?e.loadID(t):e.loadURL(t)},log:function(t){"object"==typeof console&&"function"==typeof console.error&&console.error(t)},strict:function(t,e){if(typeof t!==e)throw new Error("Invalid argument: "+e+" expected")},strict_instance:function(t,e,i){if(!(t instanceof e))throw new Error("Invalid argument: "+i+" expected")},strict_oneof:function(t,e){if(!i(t,e))throw new Error("Invalid argument: "+t+" given, valid values are "+e.join(", "))},strip_tags:function(t){return t.replace(/<[^<]+>/g,"")},lbounds:function(t){return new L.LatLngBounds([[t[1],t[0]],[t[3],t[2]]])}}},{}]},{},[14]);
  
  var eon = eon || {};
  eon.subsub = eon.subsub || subsub;
  eon.m = {
    create: function (options) {
  
      if(typeof(PUBNUB) == "undefined" && console) {
        return console.error("PubNub not found. See http://www.pubnub.com/docs/javascript/javascript-sdk.html#_where_do_i_get_the_code");
      }
  
      if(typeof(options.mb_token) == "undefined" && console) {
        return console.error("Please supply a Mapbox Token: https://www.mapbox.com/help/create-api-access-token/");
      }
  
      if(typeof(options.mb_id) == "undefined" && console) {
        return console.error("Please supply a Mapbox Map ID: https://www.mapbox.com/help/define-map-id/");
      }
  
      if(typeof(L) == "undefined" && console) {
        return console.error("You need to include the Mapbox Javascript library.");
      }
  
      var self = this;
  
      L.mapbox.accessToken = options.mb_token;
  
      var geo = {
        bearing : function (lat1,lng1,lat2,lng2) {
          var dLon = this._toRad(lng2-lng1);
          var y = Math.sin(dLon) * Math.cos(this._toRad(lat2));
          var x = Math.cos(this._toRad(lat1))*Math.sin(this._toRad(lat2)) - Math.sin(this._toRad(lat1))*Math.cos(this._toRad(lat2))*Math.cos(dLon);
          var brng = this._toDeg(Math.atan2(y, x));
          return ((brng + 360) % 360);
        },
        _toRad : function(deg) {
           return deg * Math.PI / 180;
        },
        _toDeg : function(rad) {
          return rad * 180 / Math.PI;
        }
      };
  
      self.pubnub = options.pubnub || PUBNUB || false;
  
      if(!self.pubnub) {
        error = "PubNub not found. See http://www.pubnub.com/docs/javascript/javascript-sdk.html#_where_do_i_get_the_code";
      }
  
      options.id = options.id || false;
      options.channel = options.channel || false;
      options.transform = options.transform || function(m){return m};
      options.history = options.history || false;
      options.message = options.message || function(){};
      options.connect = options.connect || function(){};
      options.rotate = options.rotate || false;
      options.marker = options.marker || L.marker;
      options.options = options.options || {};
  
      self.markers = {};
  
      if(!options.id) {
        return console.error('You need to set an ID for your Mapbox element.');
      }
  
      self.map = L.mapbox.map(options.id, options.mb_id, options.options);
  
      self.refreshRate = options.refreshRate || 10;
  
      self.lastUpdate = new Date().getTime();
  
      self.update = function (seed, animate) {
  
        for(var key in seed) {
  
          if(!self.markers.hasOwnProperty(key)) {
  
            var data = seed[key].data || {};
  
            self.markers[key]= options.marker(seed[key].latlng, seed[key].data);
            self.markers[key].addTo(self.map);
  
          } else {
  
            if(animate) {
              self.animate(key, seed[key].latlng);
            } else {
              self.updateMarker(key, seed[key].latlng);
            }
  
          }
  
        }
  
        self.lastUpdate = new Date().getTime();
  
      };
  
      var isNumber = function(n) {
        return !isNaN(parseFloat(n)) && isFinite(n);
      };
  
      self.updateMarker = function (index, point) {
  
        if(point && point.length > 1) {
  
          if(isNumber(point[0]) && isNumber(point[1])) {
            self.markers[index].setLatLng(point);
          }
  
        }
  
      };
  
      self.animations = {};
  
      self.animate = function (index, destination) {
  
        var startlatlng = self.markers[index].getLatLng();
  
        self.animations[index] = {
          start: startlatlng,
          dest: destination,
          time: new Date().getTime(),
          length: new Date().getTime() - self.lastUpdate
        };
  
      };
  
      self.refresh = function() {
  
        for(var index in self.markers) {
  
          if(typeof self.animations[index] !== 'undefined') {
  
            // number of steps in this animations
            var maxSteps = Math.round(self.animations[index].length / self.refreshRate)
  
            // time that has passed since that message
            var timeSince = new Date().getTime() - self.animations[index].time;
            var numSteps = Math.round(timeSince / self.refreshRate)
  
            var position = self.animations[index].start;
  
            var lat = position.lat + ((self.animations[index].dest[0] - position.lat) / maxSteps) * numSteps;
            var lng = position.lng + ((self.animations[index].dest[1] - position.lng) / maxSteps) * numSteps;
  
            var nextStep = [lat, lng];
  
            self.updateMarker(index, nextStep);
  
            if(options.rotate) {
              self.markers[index].options.angle = geo.bearing(position.lat, position.lng, lat, lng);
            }
  
          }
  
          index++;
  
        }
  
      };
  
      subsub.subscribe(self.pubnub, options.channel, false, function(message, env, channel) {
  
        message = options.transform(message);
  
        options.message(message, env, channel);
        self.update(message, true);
  
      });
  
      if(options.history) {
  
        self.pubnub.history({
          channel: options.channel,
          count: 1,
          callback: function(m) {
  
            if(m[0].length) {
              self.update(m[0][0], true);
            }
  
            options.connect();
  
          }
       });
  
      } else {
        options.connect();
      }
  
      self.refresh();
      setInterval(self.refresh, self.refreshRate);
  
      return self.map;
  
    }
  };
  eon.map = function(o) {
    return new eon.m.create(o);
  };
  